Select.class.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. <?php
  2. /**
  3. * A class for creating SQL SELECT statements
  4. *
  5. * @author Ironpilot
  6. * @copyright Copywrite (c) 2011, STAPLE CODE
  7. *
  8. * This file is part of the STAPLE Framework.
  9. *
  10. * The STAPLE Framework is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Lesser General Public License as published by the
  12. * Free Software Foundation, either version 3 of the License, or (at your option)
  13. * any later version.
  14. *
  15. * The STAPLE Framework is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  17. * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
  18. * more details.
  19. *
  20. * You should have received a copy of the GNU Lesser General Public License
  21. * along with the STAPLE Framework. If not, see <http://www.gnu.org/licenses/>.
  22. */
  23. class Staple_Query_Select extends Staple_Query
  24. {
  25. const ALL = 'ALL';
  26. const DISTINCT = 'DISTINCT';
  27. const DISTINCTROW = 'DISTINCTROW';
  28. const HIGH_PRIORITY = 'HIGH_PRIORITY';
  29. const STRAIGHT_JOIN = 'STRAIGHT_JOIN';
  30. const SQL_SMALL_RESULT = 'SQL_SMALL_RESULT';
  31. const SQL_BIG_RESULT = 'SQL_BIG_RESULT';
  32. const SQL_BUFFER_RESULT = 'SQL_BUFFER_RESULT';
  33. const SQL_CACHE = 'SQL_CACHE';
  34. const SQL_NO_CACHE = 'SQL_NO_CACHE';
  35. const SQL_CALC_FOUND_ROWS = 'SQL_CALC_FOUND_ROWS';
  36. /**
  37. * Additional Query Flags
  38. * @var array[string]
  39. */
  40. protected $flags = array();
  41. /**
  42. * The columns with which to act upon.
  43. * @var array[string]
  44. */
  45. public $columns = array();
  46. /**
  47. * Holds the order of the SQL query. It can be either a string or an array of the columns to order by.
  48. * @var string | array
  49. */
  50. protected $order;
  51. /**
  52. * Limit number of rows to return.
  53. * @var int
  54. */
  55. protected $limit;
  56. /**
  57. * The Limit Offset. Used to skip a number of rows before selecting.
  58. * @var int
  59. */
  60. protected $limitOffset;
  61. /**
  62. * Stores the GROUP BY columns;
  63. * @var unknown_type
  64. */
  65. protected $groupBy;
  66. /**
  67. * An array that holds the HAVING clauses
  68. * @var array[Staple_Query_Condition]
  69. */
  70. protected $having = array();
  71. /**
  72. * Array of Staple_Query_Join objects that represent table joins on the query
  73. * @var array[Staple_Query_Join]
  74. */
  75. protected $joins = array();
  76. public function __construct($table = NULL, array $columns = NULL, $db = NULL, $order = NULL, $limit = NULL)
  77. {
  78. parent::__construct(NULL, $db);
  79. //Set Table
  80. if(isset($table))
  81. {
  82. $this->setTable($table);
  83. }
  84. //Set Columns
  85. if(isset($columns))
  86. {
  87. $this->setColumns($columns);
  88. }
  89. //Set Order
  90. if(isset($order))
  91. {
  92. $this->orderBy($order);
  93. }
  94. //Set Limit
  95. if(isset($limit))
  96. {
  97. $this->limit($limit);
  98. }
  99. }
  100. public function addFlag($flag)
  101. {
  102. switch($flag)
  103. {
  104. case self::ALL:
  105. case self::DISTINCT:
  106. case self::DISTINCTROW:
  107. case self::HIGH_PRIORITY:
  108. case self::STRAIGHT_JOIN:
  109. case self::SQL_SMALL_RESULT:
  110. case self::SQL_BIG_RESULT:
  111. case self::SQL_BUFFER_RESULT:
  112. case self::SQL_CACHE:
  113. case self::SQL_NO_CACHE:
  114. case self::SQL_CALC_FOUND_ROWS:
  115. $this->flags[] = $flag;
  116. break;
  117. }
  118. return $this;
  119. }
  120. public function clearFlags()
  121. {
  122. $this->flags = array();
  123. return $this;
  124. }
  125. /**
  126. * @return the $columns
  127. */
  128. public function getColumns()
  129. {
  130. return $this->columns;
  131. }
  132. /**
  133. * Returns the order.
  134. * @return string | array
  135. */
  136. public function getOrder()
  137. {
  138. return $this->order;
  139. }
  140. /**
  141. * @return the $groupBy
  142. */
  143. public function getGroupBy()
  144. {
  145. return $this->groupBy;
  146. }
  147. /**
  148. * @return the $limit
  149. */
  150. public function getLimit()
  151. {
  152. return $this->limit;
  153. }
  154. /**
  155. * @return the $limitOffset
  156. */
  157. public function getLimitOffset()
  158. {
  159. return $this->limitOffset;
  160. }
  161. /**
  162. * @param mixed $table
  163. * @param string $alias
  164. */
  165. public function setTable($table,$alias = NULL)
  166. {
  167. if(is_array($table))
  168. {
  169. $this->table = $table;
  170. }
  171. elseif($table instanceof Staple_Query || $table instanceof Staple_Query_Union)
  172. {
  173. if(!isset($alias))
  174. {
  175. throw new Exception('Every derived table must have its own alias', Staple_Error::DB_ERROR);
  176. }
  177. $this->table = array($alias=>$table);
  178. }
  179. elseif(isset($alias) && is_string($table))
  180. {
  181. $this->table = array($alias=>$table);
  182. }
  183. else
  184. {
  185. $this->table = $table;
  186. }
  187. return $this;
  188. }
  189. /**
  190. * Different from addColumnsArray(), this function replaces all existing columns in the query.
  191. */
  192. public function setColumns(array $columns)
  193. {
  194. $this->columns = array();
  195. foreach($columns as $name=>$col)
  196. {
  197. if(is_string($name))
  198. {
  199. $this->columns[$name] = $col;
  200. }
  201. else
  202. {
  203. $this->columns[] = (string)$col;
  204. }
  205. }
  206. return $this;
  207. }
  208. /**
  209. * Set the order.
  210. * @param string | array $order
  211. */
  212. public function setOrder($order)
  213. {
  214. $this->order = $order;
  215. return $this;
  216. }
  217. /**
  218. * @param string | array $groupBy
  219. */
  220. public function setGroupBy($groupBy)
  221. {
  222. $this->groupBy = $groupBy;
  223. return $this;
  224. }
  225. /**
  226. * @param int $limit
  227. * @return Staple_Query_Select
  228. */
  229. public function setLimit($limit)
  230. {
  231. $this->limit = (int)$limit;
  232. return $this;
  233. }
  234. /**
  235. * @param int $limitOffset
  236. * @return Staple_Query_Select
  237. */
  238. public function setLimitOffset($limitOffset)
  239. {
  240. $this->limitOffset = (int)$limitOffset;
  241. return $this;
  242. }
  243. /**
  244. * Add to the list of columns. Optional parameter to name a column.
  245. * @param string | Staple_Query_Select $col
  246. * @param string $name
  247. */
  248. public function addColumn($col,$name = NULL)
  249. {
  250. if($col instanceof Staple_Query)
  251. $col = '('.(string)$col.')';
  252. if(isset($name))
  253. {
  254. $this->columns[(string)$name] = $col;
  255. }
  256. else
  257. {
  258. $this->columns[] = (string)$col;
  259. }
  260. return $this;
  261. }
  262. /**
  263. * Add an array of columns to the list of selected columns
  264. * @param array $columns
  265. */
  266. public function addColumnsArray(array $columns)
  267. {
  268. foreach($columns as $name=>$col)
  269. {
  270. if(is_string($name))
  271. {
  272. $this->columns[$name] = $col;
  273. }
  274. else
  275. {
  276. $this->columns[] = (string)$col;
  277. }
  278. }
  279. return $this;
  280. }
  281. /**
  282. * An alias of setColumns()
  283. * @param array $cols
  284. * @return Staple_Query_Select
  285. */
  286. public function columns(array $cols)
  287. {
  288. return $this->setColumns($cols);
  289. }
  290. /**
  291. * Remove a column from the $columns array.
  292. * @param string $col
  293. */
  294. public function removeColumn($col)
  295. {
  296. if(($key = array_search($col, $this->columns)) !== false)
  297. {
  298. unset($this->columns[$key]);
  299. return true;
  300. }
  301. return false;
  302. }
  303. /**
  304. * Remove a column from the $columns property by it's alias.
  305. * @param string $name
  306. */
  307. public function removeColumnByName($name)
  308. {
  309. if(array_key_exists($name, $this->columns))
  310. {
  311. unset($this->columns[$name]);
  312. return true;
  313. }
  314. return false;
  315. }
  316. /**
  317. * Alias of setOrder()
  318. * @see self::setOrder()
  319. */
  320. public function orderBy($order)
  321. {
  322. return $this->setOrder($order);
  323. }
  324. /**
  325. * Alias of setGroupBy()
  326. * @param string | array $group
  327. * @see self::setGroupBy()
  328. */
  329. public function groupBy($group)
  330. {
  331. return $this->setGroupBy($group);
  332. }
  333. /**
  334. * Sets the limit and the offset in one function.
  335. * @param int | Staple_Pager $limit
  336. * @param int $offset
  337. */
  338. public function limit($limit,$offset = NULL)
  339. {
  340. if($limit instanceof Staple_Pager)
  341. {
  342. $this->setLimit($limit->getItemsPerPage());
  343. $this->setLimitOffset($limit->getStartingItem());
  344. }
  345. else
  346. {
  347. $this->setLimit($limit);
  348. if(isset($offset))
  349. $this->setLimitOffset($offset);
  350. }
  351. return $this;
  352. }
  353. /*-----------------------------------------------HAVING CLAUSES-----------------------------------------------*/
  354. public function addHaving(Staple_Query_Condition $having)
  355. {
  356. $this->having[] = $having;
  357. return $this;
  358. }
  359. public function clearHaving()
  360. {
  361. $this->having = array();
  362. return $this;
  363. }
  364. public function havingCondition($column, $operator, $value, $columnJoin = NULL)
  365. {
  366. $this->addHaving(Staple_Query_Condition::Get($column, $operator, $value, $columnJoin));
  367. return $this;
  368. }
  369. public function havingStatement($statement)
  370. {
  371. $this->addHaving(Staple_Query_Condition::Statement($statement));
  372. return $this;
  373. }
  374. public function havingEqual($column, $value, $columnJoin = NULL)
  375. {
  376. $this->addHaving(Staple_Query_Condition::Equal($column, $value, $columnJoin));
  377. return $this;
  378. }
  379. public function havingLike($column, $value)
  380. {
  381. $this->addHaving(Staple_Query_Condition::Like($column, $value));
  382. return $this;
  383. }
  384. public function havingNull($column)
  385. {
  386. $this->addHaving(Staple_Query_Condition::Null($column));
  387. return $this;
  388. }
  389. public function havingIn($column, array $values)
  390. {
  391. $this->addHaving(Staple_Query_Condition::In($column, $values));
  392. return $this;
  393. }
  394. public function havingBetween($column, $start, $end)
  395. {
  396. $this->addHaving(Staple_Query_Condition::Between($column, $start, $end));
  397. return $this;
  398. }
  399. /*-----------------------------------------------JOIN FUNCTIONS-----------------------------------------------*/
  400. /**
  401. * Add a join to the query.
  402. * @param Staple_Query_Join $join
  403. */
  404. public function addJoin(Staple_Query_Join $join)
  405. {
  406. $this->joins[] = $join;
  407. return $this;
  408. }
  409. /**
  410. * Remove a join from the query by table name.
  411. * @param string $table
  412. * @return boolean
  413. */
  414. public function removeJoin($table)
  415. {
  416. foreach($this->joins as $key=>$join)
  417. {
  418. if($join->getTable() == $table)
  419. {
  420. unset($this->joins[$key]);
  421. return true;
  422. }
  423. }
  424. return false;
  425. }
  426. /**
  427. * Returns true is specified table is already joined to the query, false otherwise.
  428. * @param string $table
  429. * @return boolean
  430. */
  431. public function isJoined($table)
  432. {
  433. foreach($this->joins as $key=>$join)
  434. {
  435. if($join->getTable() == $table)
  436. {
  437. return true;
  438. }
  439. }
  440. return false;
  441. }
  442. public function leftJoin($table, $condition)
  443. {
  444. $this->addJoin(Staple_Query_Join::left($table, $condition));
  445. return $this;
  446. }
  447. public function innerJoin($table, $condition)
  448. {
  449. $this->addJoin(Staple_Query_Join::inner($table, $condition));
  450. return $this;
  451. }
  452. /**
  453. * Returns the joins array
  454. * @return array[Staple_Query_Join]
  455. */
  456. public function getJoins()
  457. {
  458. return $this->joins;
  459. }
  460. /*-----------------------------------------------BUILD FUNCTION-----------------------------------------------*/
  461. /**
  462. *
  463. * @see Staple_Query::build()
  464. */
  465. function build()
  466. {
  467. $stmt = 'SELECT ';
  468. //Flags
  469. if(count($this->flags) > 0)
  470. {
  471. $stmt .= ' '.implode(' ', $this->flags);
  472. }
  473. //Collect Select Columns
  474. if(count($this->columns) == 0)
  475. {
  476. $columns = '*';
  477. }
  478. else
  479. {
  480. $columns = '';
  481. foreach($this->columns as $name=>$col)
  482. {
  483. if(strlen($columns) >= 1)
  484. {
  485. $columns .= ',';
  486. }
  487. if($col instanceof Staple_Query_Select)
  488. {
  489. $columns .= '('.$col.')';
  490. }
  491. else
  492. {
  493. $columns .= $col;
  494. }
  495. if(is_string($name))
  496. {
  497. $columns .= " AS `$name`";
  498. }
  499. }
  500. }
  501. //Columns and FROM CLAUSE
  502. $stmt .= "\n$columns \nFROM ";
  503. if(is_array($this->table))
  504. {
  505. $tables = '';
  506. foreach($this->table as $name=>$tbl)
  507. {
  508. if(strlen($tables) > 1)
  509. {
  510. $tables .= ',';
  511. }
  512. if($tbl instanceof Staple_Query || $tbl instanceof Staple_Query_Union)
  513. {
  514. $tables = '('.$tbl.')';
  515. }
  516. else
  517. {
  518. $tables .= $tbl;
  519. }
  520. if(is_string($name))
  521. {
  522. $tables .= " AS `$name`";
  523. }
  524. }
  525. $stmt .= $tables;
  526. }
  527. else
  528. {
  529. $stmt .= $this->table;
  530. }
  531. //JOINS
  532. if(count($this->joins) > 0)
  533. {
  534. $stmt .= "\n".implode("\n", $this->joins);
  535. }
  536. //WHERE CLAUSE
  537. if(count($this->where) > 0)
  538. {
  539. $stmt .= "\nWHERE ".implode(' AND ', $this->where);
  540. }
  541. //GROUP BY
  542. if(isset($this->groupBy))
  543. {
  544. $stmt .= "\nGROUP BY ";
  545. if(is_array($this->groupBy))
  546. {
  547. $stmt .= implode(',', $this->groupBy);
  548. }
  549. else
  550. {
  551. $stmt .= $this->groupBy;
  552. }
  553. }
  554. //HAVING
  555. if(count($this->having) > 0)
  556. {
  557. $stmt .= "\nHAVING ".implode(' AND ', $this->having);
  558. }
  559. //ORDER CLAUSE
  560. if(isset($this->order))
  561. {
  562. $stmt .= "\nORDER BY ";
  563. if(is_array($this->order))
  564. {
  565. $stmt .= implode(', ', $this->order);
  566. }
  567. else
  568. {
  569. $stmt .= $this->order;
  570. }
  571. }
  572. //LIMIT CLAUSE
  573. if(isset($this->limit))
  574. {
  575. $stmt .= "\nLIMIT ".$this->getLimit();
  576. if(isset($this->limitOffset))
  577. {
  578. $stmt .= ' OFFSET '.$this->limitOffset;
  579. }
  580. }
  581. return $stmt;
  582. }
  583. }
  584. ?>