PageRenderTime 46ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Qubit/Db/Table.php

https://gitlab.com/alejandrocepeda25/Qubit-PHP-Framework
PHP | 465 lines | 319 code | 92 blank | 54 comment | 75 complexity | 0e8eb5e0404f57395783c07f2fe2d8ab MD5 | raw file
  1. <?php
  2. /**
  3. * Clase para interfaz de tabla SQL.
  4. *
  5. * Creado por: Alejandro Cepeda
  6. * Ultima modifición: domingo 1 de marzo 2015
  7. * Mas info: Qubit alejandrocepeda25@gmail.com
  8. *
  9. * @category Qubit
  10. * @package Qubit_Db
  11. * @subpackage Table
  12. */
  13. class Qubit_Db_Table{
  14. protected $_name = null;
  15. protected $_primary = null;
  16. protected $_schema = null;
  17. protected $_identity = 1;
  18. protected $_cols;
  19. protected $_metadata = array();
  20. protected $_adapter;
  21. const NAME = 'name';
  22. function __construct() {
  23. $this->_setup();
  24. }
  25. protected function _setup(){
  26. $this->_setupAdapter();
  27. $this->_setupTableName();
  28. }
  29. protected function _setupTableName(){
  30. if (!$this->_name) {
  31. $this->_name = get_class($this);
  32. }
  33. }
  34. public function info($key){
  35. $info = array(
  36. self::NAME => $this->_name
  37. );
  38. if ($key === null) {
  39. return $info;
  40. }
  41. return $info[$key];
  42. }
  43. /*
  44. * estable el objeto del adaptador (Mysqli,Oracle,SQLServer,DB2 Etc)
  45. */
  46. protected function _setupAdapter(){
  47. if (! $this->_adapter) {
  48. $this->_adapter = Qubit_Db::getAdapter();
  49. if (!$this->_adapter instanceof Qubit_Db_Adapter_Abstract) {
  50. throw new Qubit_Exception('No hay resultados para el adaptador ' . get_class($this));
  51. }
  52. }
  53. }
  54. protected function _getCols(){
  55. if (null === $this->_cols) {
  56. $this->_setupMetadata();
  57. $this->_cols = array_keys($this->_metadata);
  58. }
  59. return $this->_cols;
  60. }
  61. protected function _setupMetadata(){
  62. if (count($this->_metadata) > 0) {
  63. return true;
  64. }
  65. $this->_metadata = $this->_adapter->describeTable($this->_name, $this->_schema);
  66. }
  67. public function find(){
  68. $this->_setupPrimaryKey();
  69. $args = func_get_args();
  70. $keyNames = array_values((array) $this->_primary);
  71. if (count($args) < count($keyNames)) {
  72. throw new Qubit_Exception("Muy pocas columnas para la clave primaria");
  73. }
  74. if (count($args) > count($keyNames)) {
  75. throw new Qubit_Exception("Muy pocas columnas para la clave primaria");
  76. }
  77. $whereList = array();
  78. $numberTerms = 0;
  79. foreach ($args as $keyPosition => $keyValues) {
  80. $keyValuesCount = count($keyValues);
  81. if (!is_array($keyValues)) {
  82. $keyValues = array($keyValues);
  83. }
  84. if ($numberTerms == 0) {
  85. $numberTerms = $keyValuesCount;
  86. } else if ($keyValuesCount != $numberTerms) {
  87. throw new Qubit_Exception("Falta el valore(s) para la clave primaria");
  88. }
  89. $keyValues = array_values($keyValues);
  90. for ($i = 0; $i < $keyValuesCount; ++$i) {
  91. if (!isset($whereList[$i])) {
  92. $whereList[$i] = array();
  93. }
  94. $whereList[$i][$keyPosition] = $keyValues[$i];
  95. }
  96. }
  97. $whereClause = null;
  98. if (count($whereList)) {
  99. $whereOrTerms = array();
  100. $tableName = $this->_adapter->quoteTable($this->_name);
  101. foreach ($whereList as $keyValueSets) {
  102. $whereAndTerms = array();
  103. foreach ($keyValueSets as $keyPosition => $keyValue) {
  104. $type = $this->_metadata[$keyNames[$keyPosition]]['DATA_TYPE'];
  105. $columnName = $this->_adapter->quoteTable($keyNames[$keyPosition]);
  106. $whereAndTerms[] = $tableName . '.' . $columnName . ' = ' . $this->_adapter->quote($keyValue,$type);
  107. }
  108. $whereOrTerms[] = '(' . implode(' AND ', $whereAndTerms) . ')';
  109. }
  110. $whereClause = '(' . implode(' OR ', $whereOrTerms) . ')';
  111. }
  112. $select = $this->select();
  113. $select->from($tableName);
  114. $where = (array) $whereClause;
  115. foreach ($where as $key => $val) {
  116. if (is_int($key)) {
  117. $select->where($val);
  118. } else {
  119. $select->where($key, $val);
  120. }
  121. }
  122. return $this->fetchAll($select);
  123. }
  124. public function _setupPrimaryKey(){
  125. if (!$this->_primary) {
  126. $this->_setupMetadata();
  127. $this->_primary = array();
  128. foreach ($this->_metadata as $col) {
  129. if ($col['PRIMARY']) {
  130. $this->_primary[$col['PRIMARY_POSITION'] ] = $col['COLUMN_NAME'];
  131. if ($col['IDENTITY']) {
  132. $this->_identity = $col['PRIMARY_POSITION'];
  133. }
  134. }
  135. }
  136. if (empty($this->_primary)) {
  137. throw new Qubit_Exception('No existe una clave primaria para esta tabla');
  138. }
  139. }
  140. else if (!is_array($this->_primary)) {
  141. $this->_primary = array(1 => $this->_primary);
  142. }
  143. else if (isset($this->_primary[0])) {
  144. array_unshift($this->_primary, null);
  145. unset($this->_primary[0]);
  146. }
  147. $cols = $this->_getCols();
  148. if (! array_intersect((array) $this->_primary, $cols) == (array) $this->_primary) {
  149. throw new Qubit_Exception("Columna de clave principal(s) ("
  150. . implode(',', (array) $this->_primary)
  151. . ") no son las columnas de esta tabla ("
  152. . implode(',', $cols)
  153. . ")");
  154. }
  155. }
  156. public function fetchAll($where = null, $order = null, $count = null, $offset = null){
  157. if (!($where instanceof Qubit_Db_Select)) {
  158. $select = $this->select();
  159. $select->from($this->_name,Qubit_Db_Select::SQL_WILDCARD);
  160. //$row = $select->query();
  161. if ($where !== null) {
  162. $select->where($where);
  163. }
  164. if ($order !== null) {
  165. $select->order($order);
  166. }
  167. if ($count !== null || $offset !== null) {
  168. $select->limit($count, $offset);
  169. }
  170. }
  171. else{
  172. $select = $where;
  173. }
  174. $rows = $this->fetch($select);
  175. return $rows;
  176. }
  177. /*
  178. public function find($where){
  179. $select = $this->select()->where($where);
  180. $row = $select->query();
  181. if (count($row) == 1){
  182. return $row[0];
  183. }
  184. else{
  185. return $row;
  186. }
  187. }
  188. */
  189. protected function _fetch(Qubit_Db_Select $select,$style = null){
  190. if ($style === null) {
  191. $style = Qubit_Db::FETCH_ASSOC;
  192. }
  193. $this->_adapter->query($select);
  194. $data = $this->_adapter->fetch($style);
  195. return $data;
  196. }
  197. public function fetchOne($where = null, $order = null, $limit = null, $offset = null){
  198. if (!($where instanceof Qubit_Db_Select)) {
  199. $select = $this->select();
  200. if ($where !== null) {
  201. $select->where($where);
  202. }
  203. if ($order !== null) {
  204. $select->order($order);
  205. }
  206. $select->limit(1, 0);
  207. }
  208. else{
  209. $select = $where->limit(1, 0);;
  210. }
  211. $row = $this->_fetch($select,Qubit_Db::FETCH_NUM);
  212. if (count($row) == 0) {
  213. return null;
  214. }
  215. return $row[0][0];
  216. }
  217. public function fetchRow($where = null, $order = null, $limit = null, $offset = null){
  218. if (!($where instanceof Qubit_Db_Select)) {
  219. $select = $this->select();
  220. if ($where !== null) {
  221. $select->where($where);
  222. }
  223. if ($order !== null) {
  224. $select->order($order);
  225. }
  226. $select->limit(1, 0);
  227. }
  228. else{
  229. $select = $where->limit(1, 0);;
  230. }
  231. $row = $select->query();
  232. if (count($row) == 0) {
  233. return null;
  234. }
  235. return $row[0];
  236. }
  237. public function fetch($where = null, $order = null, $limit = null, $offset = null){
  238. if (!($where instanceof Qubit_Db_Select)) {
  239. $select = $this->select();
  240. if ($where !== null) {
  241. $select->where($where);
  242. }
  243. if ($order !== null) {
  244. $select->order($order);
  245. }
  246. if ($limit !== null || $offset !== null) {
  247. $select->limit($limit, $offset);
  248. }
  249. }
  250. else{
  251. $select = $where;
  252. }
  253. return $select->query();
  254. }
  255. /*
  256. public function __toString(){
  257. try {
  258. $data = $this->query();
  259. } catch (Qubit_Exception $e) {
  260. $data = '';
  261. }
  262. return $data;
  263. }
  264. */
  265. /*
  266. * retorna la instancia de la clase Qubit_Db_Select
  267. */
  268. public function select(){
  269. $select = new Qubit_Db_Select($this->_adapter);
  270. $select
  271. ->setTableName($this->_name)
  272. ->select();
  273. return $select;
  274. }
  275. // EJECUTA LA SENTANCIA
  276. // recibe un array asociativo campo y valor
  277. public function insert($array){
  278. $table = $this->_adapter->quoteTable($this->_name);
  279. foreach($array as $key => $val){
  280. $val = $this->_adapter->escape_string($val);
  281. $noValid = false;
  282. if (is_array($val)){
  283. if ($val[0] == $val[1]){
  284. $noValid = true;
  285. }
  286. else{
  287. $val = $val[0];
  288. }
  289. }
  290. if (!$noValid){
  291. $datatype = gettype($val);
  292. if (is_numeric($val)){
  293. }
  294. elseif ($datatype == 'string'){
  295. $val = "'".$val."'";
  296. }
  297. $fields.= (strlen($fields) == 0) ? "$key" : ",$key";
  298. $values.= (strlen($values) == 0) ? "$val" : ",$val";
  299. }
  300. }
  301. $query = 'INSERT INTO ' . $table . ' (' . $fields . ') VALUES (' . $values . ');';
  302. $this->_adapter->query($query);
  303. if ($this->_adapter->get_errno() == 0){
  304. return $this->_adapter->get_insert_id();
  305. }
  306. else{
  307. return $this->_adapter->get_errno();
  308. }
  309. }
  310. // EJECUTA LA SENTANCIA
  311. // recibe un array asociativo campo y valor
  312. public function delete($where = null){
  313. $table = $this->_adapter->quoteTable($this->_name);
  314. if (!$where == null){
  315. $where = "WHERE $where";
  316. }
  317. $query = 'DELETE FROM ' . $table . ' ' . $where . ';';
  318. $this->_adapter->query($query);
  319. if ($this->_adapter->get_errno() == 0){
  320. return true;
  321. }
  322. else{
  323. return $this->_adapter->get_errno();
  324. }
  325. }
  326. // EJECUTA LA SENTANCIA
  327. // recibe un array asociativo campo y valor
  328. /*
  329. * @param string or array
  330. */
  331. public function update($array, $where = null){
  332. $table = $this->_adapter->quoteTable($this->_name);
  333. $fields = '';
  334. foreach($array as $key => $val){
  335. $noValid = false;
  336. $val = $this->_adapter->escape_string($val);
  337. if (is_array($val)){
  338. if ($val[0] == $val[1]){
  339. $noValid = true;
  340. }
  341. else{
  342. $val = $val[0];
  343. }
  344. }
  345. if (!$noValid){
  346. $datatype = gettype($val);
  347. if (is_numeric($val)){
  348. }
  349. elseif ($datatype == 'string'){
  350. $val = "'".$val."'";
  351. }
  352. $fields.= (strlen($fields) == 0) ? "$key = $val" : ",$key = $val";
  353. }
  354. }
  355. if (!$where == null){
  356. $where = 'WHERE ' . $where;
  357. }
  358. $query = 'UPDATE ' . $table . ' SET ' . $fields . ' ' . $where . ';';
  359. $this->_adapter->query($query);
  360. if ($this->_adapter->get_errno() == 0){
  361. return true;
  362. }
  363. else{
  364. return $this->_adapter->get_errno();
  365. }
  366. }
  367. }
  368. ?>