PageRenderTime 51ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/application/libraries/Zend/Db/Select.php

https://github.com/shopaholiccompany/shopaholic
PHP | 1345 lines | 634 code | 128 blank | 583 comment | 129 complexity | 6d4728c96f0e3d693d1d4df8c14a6a41 MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-3.0, LGPL-2.1
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Db
  17. * @subpackage Select
  18. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id: Select.php 18511 2009-10-12 14:33:35Z ralph $
  21. */
  22. /**
  23. * @see Zend_Db_Adapter_Abstract
  24. */
  25. // require_once 'Zend/Db/Adapter/Abstract.php';
  26. /**
  27. * @see Zend_Db_Expr
  28. */
  29. // require_once 'Zend/Db/Expr.php';
  30. /**
  31. * Class for SQL SELECT generation and results.
  32. *
  33. * @category Zend
  34. * @package Zend_Db
  35. * @subpackage Select
  36. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  37. * @license http://framework.zend.com/license/new-bsd New BSD License
  38. */
  39. class Zend_Db_Select
  40. {
  41. const DISTINCT = 'distinct';
  42. const COLUMNS = 'columns';
  43. const FROM = 'from';
  44. const UNION = 'union';
  45. const WHERE = 'where';
  46. const GROUP = 'group';
  47. const HAVING = 'having';
  48. const ORDER = 'order';
  49. const LIMIT_COUNT = 'limitcount';
  50. const LIMIT_OFFSET = 'limitoffset';
  51. const FOR_UPDATE = 'forupdate';
  52. const INNER_JOIN = 'inner join';
  53. const LEFT_JOIN = 'left join';
  54. const RIGHT_JOIN = 'right join';
  55. const FULL_JOIN = 'full join';
  56. const CROSS_JOIN = 'cross join';
  57. const NATURAL_JOIN = 'natural join';
  58. const SQL_WILDCARD = '*';
  59. const SQL_SELECT = 'SELECT';
  60. const SQL_UNION = 'UNION';
  61. const SQL_UNION_ALL = 'UNION ALL';
  62. const SQL_FROM = 'FROM';
  63. const SQL_WHERE = 'WHERE';
  64. const SQL_DISTINCT = 'DISTINCT';
  65. const SQL_GROUP_BY = 'GROUP BY';
  66. const SQL_ORDER_BY = 'ORDER BY';
  67. const SQL_HAVING = 'HAVING';
  68. const SQL_FOR_UPDATE = 'FOR UPDATE';
  69. const SQL_AND = 'AND';
  70. const SQL_AS = 'AS';
  71. const SQL_OR = 'OR';
  72. const SQL_ON = 'ON';
  73. const SQL_ASC = 'ASC';
  74. const SQL_DESC = 'DESC';
  75. /**
  76. * Bind variables for query
  77. *
  78. * @var array
  79. */
  80. protected $_bind = array();
  81. /**
  82. * Zend_Db_Adapter_Abstract object.
  83. *
  84. * @var Zend_Db_Adapter_Abstract
  85. */
  86. protected $_adapter;
  87. /**
  88. * The initial values for the $_parts array.
  89. * NOTE: It is important for the 'FOR_UPDATE' part to be last to ensure
  90. * meximum compatibility with database adapters.
  91. *
  92. * @var array
  93. */
  94. protected static $_partsInit = array(
  95. self::DISTINCT => false,
  96. self::COLUMNS => array(),
  97. self::UNION => array(),
  98. self::FROM => array(),
  99. self::WHERE => array(),
  100. self::GROUP => array(),
  101. self::HAVING => array(),
  102. self::ORDER => array(),
  103. self::LIMIT_COUNT => null,
  104. self::LIMIT_OFFSET => null,
  105. self::FOR_UPDATE => false
  106. );
  107. /**
  108. * Specify legal join types.
  109. *
  110. * @var array
  111. */
  112. protected static $_joinTypes = array(
  113. self::INNER_JOIN,
  114. self::LEFT_JOIN,
  115. self::RIGHT_JOIN,
  116. self::FULL_JOIN,
  117. self::CROSS_JOIN,
  118. self::NATURAL_JOIN,
  119. );
  120. /**
  121. * Specify legal union types.
  122. *
  123. * @var array
  124. */
  125. protected static $_unionTypes = array(
  126. self::SQL_UNION,
  127. self::SQL_UNION_ALL
  128. );
  129. /**
  130. * The component parts of a SELECT statement.
  131. * Initialized to the $_partsInit array in the constructor.
  132. *
  133. * @var array
  134. */
  135. protected $_parts = array();
  136. /**
  137. * Tracks which columns are being select from each table and join.
  138. *
  139. * @var array
  140. */
  141. protected $_tableCols = array();
  142. /**
  143. * Class constructor
  144. *
  145. * @param Zend_Db_Adapter_Abstract $adapter
  146. */
  147. public function __construct(Zend_Db_Adapter_Abstract $adapter)
  148. {
  149. $this->_adapter = $adapter;
  150. $this->_parts = self::$_partsInit;
  151. }
  152. /**
  153. * Get bind variables
  154. *
  155. * @return array
  156. */
  157. public function getBind()
  158. {
  159. return $this->_bind;
  160. }
  161. /**
  162. * Set bind variables
  163. *
  164. * @param mixed $bind
  165. * @return Zend_Db_Select
  166. */
  167. public function bind($bind)
  168. {
  169. $this->_bind = $bind;
  170. return $this;
  171. }
  172. /**
  173. * Makes the query SELECT DISTINCT.
  174. *
  175. * @param bool $flag Whether or not the SELECT is DISTINCT (default true).
  176. * @return Zend_Db_Select This Zend_Db_Select object.
  177. */
  178. public function distinct($flag = true)
  179. {
  180. $this->_parts[self::DISTINCT] = (bool) $flag;
  181. return $this;
  182. }
  183. /**
  184. * Adds a FROM table and optional columns to the query.
  185. *
  186. * The first parameter $name can be a simple string, in which case the
  187. * correlation name is generated automatically. If you want to specify
  188. * the correlation name, the first parameter must be an associative
  189. * array in which the key is the physical table name, and the value is
  190. * the correlation name. For example, array('table' => 'alias').
  191. * The correlation name is prepended to all columns fetched for this
  192. * table.
  193. *
  194. * The second parameter can be a single string or Zend_Db_Expr object,
  195. * or else an array of strings or Zend_Db_Expr objects.
  196. *
  197. * The first parameter can be null or an empty string, in which case
  198. * no correlation name is generated or prepended to the columns named
  199. * in the second parameter.
  200. *
  201. * @param array|string|Zend_Db_Expr $name The table name or an associative array relating table name to
  202. * correlation name.
  203. * @param array|string|Zend_Db_Expr $cols The columns to select from this table.
  204. * @param string $schema The schema name to specify, if any.
  205. * @return Zend_Db_Select This Zend_Db_Select object.
  206. */
  207. public function from($name, $cols = '*', $schema = null)
  208. {
  209. return $this->_join(self::FROM, $name, null, $cols, $schema);
  210. }
  211. /**
  212. * Specifies the columns used in the FROM clause.
  213. *
  214. * The parameter can be a single string or Zend_Db_Expr object,
  215. * or else an array of strings or Zend_Db_Expr objects.
  216. *
  217. * @param array|string|Zend_Db_Expr $cols The columns to select from this table.
  218. * @param string $correlationName Correlation name of target table. OPTIONAL
  219. * @return Zend_Db_Select This Zend_Db_Select object.
  220. */
  221. public function columns($cols = '*', $correlationName = null)
  222. {
  223. if ($correlationName === null && count($this->_parts[self::FROM])) {
  224. $correlationName = current(array_keys($this->_parts[self::FROM]));
  225. }
  226. if (!array_key_exists($correlationName, $this->_parts[self::FROM])) {
  227. /**
  228. * @see Zend_Db_Select_Exception
  229. */
  230. // require_once 'Zend/Db/Select/Exception.php';
  231. throw new Zend_Db_Select_Exception("No table has been specified for the FROM clause");
  232. }
  233. $this->_tableCols($correlationName, $cols);
  234. return $this;
  235. }
  236. /**
  237. * Adds a UNION clause to the query.
  238. *
  239. * The first parameter $select can be a string, an existing Zend_Db_Select
  240. * object or an array of either of these types.
  241. *
  242. * @param array|string|Zend_Db_Select $select One or more select clauses for the UNION.
  243. * @return Zend_Db_Select This Zend_Db_Select object.
  244. */
  245. public function union($select = array(), $type = self::SQL_UNION)
  246. {
  247. if (!is_array($select)) {
  248. $select = array();
  249. }
  250. if (!in_array($type, self::$_unionTypes)) {
  251. // require_once 'Zend/Db/Select/Exception.php';
  252. throw new Zend_Db_Select_Exception("Invalid union type '{$type}'");
  253. }
  254. foreach ($select as $target) {
  255. $this->_parts[self::UNION][] = array($target, $type);
  256. }
  257. return $this;
  258. }
  259. /**
  260. * Adds a JOIN table and columns to the query.
  261. *
  262. * The $name and $cols parameters follow the same logic
  263. * as described in the from() method.
  264. *
  265. * @param array|string|Zend_Db_Expr $name The table name.
  266. * @param string $cond Join on this condition.
  267. * @param array|string $cols The columns to select from the joined table.
  268. * @param string $schema The database name to specify, if any.
  269. * @return Zend_Db_Select This Zend_Db_Select object.
  270. */
  271. public function join($name, $cond, $cols = self::SQL_WILDCARD, $schema = null)
  272. {
  273. return $this->joinInner($name, $cond, $cols, $schema);
  274. }
  275. /**
  276. * Add an INNER JOIN table and colums to the query
  277. * Rows in both tables are matched according to the expression
  278. * in the $cond argument. The result set is comprised
  279. * of all cases where rows from the left table match
  280. * rows from the right table.
  281. *
  282. * The $name and $cols parameters follow the same logic
  283. * as described in the from() method.
  284. *
  285. * @param array|string|Zend_Db_Expr $name The table name.
  286. * @param string $cond Join on this condition.
  287. * @param array|string $cols The columns to select from the joined table.
  288. * @param string $schema The database name to specify, if any.
  289. * @return Zend_Db_Select This Zend_Db_Select object.
  290. */
  291. public function joinInner($name, $cond, $cols = self::SQL_WILDCARD, $schema = null)
  292. {
  293. return $this->_join(self::INNER_JOIN, $name, $cond, $cols, $schema);
  294. }
  295. /**
  296. * Add a LEFT OUTER JOIN table and colums to the query
  297. * All rows from the left operand table are included,
  298. * matching rows from the right operand table included,
  299. * and the columns from the right operand table are filled
  300. * with NULLs if no row exists matching the left table.
  301. *
  302. * The $name and $cols parameters follow the same logic
  303. * as described in the from() method.
  304. *
  305. * @param array|string|Zend_Db_Expr $name The table name.
  306. * @param string $cond Join on this condition.
  307. * @param array|string $cols The columns to select from the joined table.
  308. * @param string $schema The database name to specify, if any.
  309. * @return Zend_Db_Select This Zend_Db_Select object.
  310. */
  311. public function joinLeft($name, $cond, $cols = self::SQL_WILDCARD, $schema = null)
  312. {
  313. return $this->_join(self::LEFT_JOIN, $name, $cond, $cols, $schema);
  314. }
  315. /**
  316. * Add a RIGHT OUTER JOIN table and colums to the query.
  317. * Right outer join is the complement of left outer join.
  318. * All rows from the right operand table are included,
  319. * matching rows from the left operand table included,
  320. * and the columns from the left operand table are filled
  321. * with NULLs if no row exists matching the right table.
  322. *
  323. * The $name and $cols parameters follow the same logic
  324. * as described in the from() method.
  325. *
  326. * @param array|string|Zend_Db_Expr $name The table name.
  327. * @param string $cond Join on this condition.
  328. * @param array|string $cols The columns to select from the joined table.
  329. * @param string $schema The database name to specify, if any.
  330. * @return Zend_Db_Select This Zend_Db_Select object.
  331. */
  332. public function joinRight($name, $cond, $cols = self::SQL_WILDCARD, $schema = null)
  333. {
  334. return $this->_join(self::RIGHT_JOIN, $name, $cond, $cols, $schema);
  335. }
  336. /**
  337. * Add a FULL OUTER JOIN table and colums to the query.
  338. * A full outer join is like combining a left outer join
  339. * and a right outer join. All rows from both tables are
  340. * included, paired with each other on the same row of the
  341. * result set if they satisfy the join condition, and otherwise
  342. * paired with NULLs in place of columns from the other table.
  343. *
  344. * The $name and $cols parameters follow the same logic
  345. * as described in the from() method.
  346. *
  347. * @param array|string|Zend_Db_Expr $name The table name.
  348. * @param string $cond Join on this condition.
  349. * @param array|string $cols The columns to select from the joined table.
  350. * @param string $schema The database name to specify, if any.
  351. * @return Zend_Db_Select This Zend_Db_Select object.
  352. */
  353. public function joinFull($name, $cond, $cols = self::SQL_WILDCARD, $schema = null)
  354. {
  355. return $this->_join(self::FULL_JOIN, $name, $cond, $cols, $schema);
  356. }
  357. /**
  358. * Add a CROSS JOIN table and colums to the query.
  359. * A cross join is a cartesian product; there is no join condition.
  360. *
  361. * The $name and $cols parameters follow the same logic
  362. * as described in the from() method.
  363. *
  364. * @param array|string|Zend_Db_Expr $name The table name.
  365. * @param array|string $cols The columns to select from the joined table.
  366. * @param string $schema The database name to specify, if any.
  367. * @return Zend_Db_Select This Zend_Db_Select object.
  368. */
  369. public function joinCross($name, $cols = self::SQL_WILDCARD, $schema = null)
  370. {
  371. return $this->_join(self::CROSS_JOIN, $name, null, $cols, $schema);
  372. }
  373. /**
  374. * Add a NATURAL JOIN table and colums to the query.
  375. * A natural join assumes an equi-join across any column(s)
  376. * that appear with the same name in both tables.
  377. * Only natural inner joins are supported by this API,
  378. * even though SQL permits natural outer joins as well.
  379. *
  380. * The $name and $cols parameters follow the same logic
  381. * as described in the from() method.
  382. *
  383. * @param array|string|Zend_Db_Expr $name The table name.
  384. * @param array|string $cols The columns to select from the joined table.
  385. * @param string $schema The database name to specify, if any.
  386. * @return Zend_Db_Select This Zend_Db_Select object.
  387. */
  388. public function joinNatural($name, $cols = self::SQL_WILDCARD, $schema = null)
  389. {
  390. return $this->_join(self::NATURAL_JOIN, $name, null, $cols, $schema);
  391. }
  392. /**
  393. * Adds a WHERE condition to the query by AND.
  394. *
  395. * If a value is passed as the second param, it will be quoted
  396. * and replaced into the condition wherever a question-mark
  397. * appears. Array values are quoted and comma-separated.
  398. *
  399. * <code>
  400. * // simplest but non-secure
  401. * $select->where("id = $id");
  402. *
  403. * // secure (ID is quoted but matched anyway)
  404. * $select->where('id = ?', $id);
  405. *
  406. * // alternatively, with named binding
  407. * $select->where('id = :id');
  408. * </code>
  409. *
  410. * Note that it is more correct to use named bindings in your
  411. * queries for values other than strings. When you use named
  412. * bindings, don't forget to pass the values when actually
  413. * making a query:
  414. *
  415. * <code>
  416. * $db->fetchAll($select, array('id' => 5));
  417. * </code>
  418. *
  419. * @param string $cond The WHERE condition.
  420. * @param string $value OPTIONAL A single value to quote into the condition.
  421. * @param constant $type OPTIONAL The type of the given value
  422. * @return Zend_Db_Select This Zend_Db_Select object.
  423. */
  424. public function where($cond, $value = null, $type = null)
  425. {
  426. $this->_parts[self::WHERE][] = $this->_where($cond, $value, $type, true);
  427. return $this;
  428. }
  429. /**
  430. * Adds a WHERE condition to the query by OR.
  431. *
  432. * Otherwise identical to where().
  433. *
  434. * @param string $cond The WHERE condition.
  435. * @param string $value OPTIONAL A single value to quote into the condition.
  436. * @param constant $type OPTIONAL The type of the given value
  437. * @return Zend_Db_Select This Zend_Db_Select object.
  438. *
  439. * @see where()
  440. */
  441. public function orWhere($cond, $value = null, $type = null)
  442. {
  443. $this->_parts[self::WHERE][] = $this->_where($cond, $value, $type, false);
  444. return $this;
  445. }
  446. /**
  447. * Adds grouping to the query.
  448. *
  449. * @param array|string $spec The column(s) to group by.
  450. * @return Zend_Db_Select This Zend_Db_Select object.
  451. */
  452. public function group($spec)
  453. {
  454. if (!is_array($spec)) {
  455. $spec = array($spec);
  456. }
  457. foreach ($spec as $val) {
  458. if (preg_match('/\(.*\)/', (string) $val)) {
  459. $val = new Zend_Db_Expr($val);
  460. }
  461. $this->_parts[self::GROUP][] = $val;
  462. }
  463. return $this;
  464. }
  465. /**
  466. * Adds a HAVING condition to the query by AND.
  467. *
  468. * If a value is passed as the second param, it will be quoted
  469. * and replaced into the condition wherever a question-mark
  470. * appears. See {@link where()} for an example
  471. *
  472. * @param string $cond The HAVING condition.
  473. * @param string|Zend_Db_Expr $val A single value to quote into the condition.
  474. * @return Zend_Db_Select This Zend_Db_Select object.
  475. */
  476. public function having($cond)
  477. {
  478. if (func_num_args() > 1) {
  479. $val = func_get_arg(1);
  480. $cond = $this->_adapter->quoteInto($cond, $val);
  481. }
  482. if ($this->_parts[self::HAVING]) {
  483. $this->_parts[self::HAVING][] = self::SQL_AND . " ($cond)";
  484. } else {
  485. $this->_parts[self::HAVING][] = "($cond)";
  486. }
  487. return $this;
  488. }
  489. /**
  490. * Adds a HAVING condition to the query by OR.
  491. *
  492. * Otherwise identical to orHaving().
  493. *
  494. * @param string $cond The HAVING condition.
  495. * @param string $val A single value to quote into the condition.
  496. * @return Zend_Db_Select This Zend_Db_Select object.
  497. *
  498. * @see having()
  499. */
  500. public function orHaving($cond)
  501. {
  502. if (func_num_args() > 1) {
  503. $val = func_get_arg(1);
  504. $cond = $this->_adapter->quoteInto($cond, $val);
  505. }
  506. if ($this->_parts[self::HAVING]) {
  507. $this->_parts[self::HAVING][] = self::SQL_OR . " ($cond)";
  508. } else {
  509. $this->_parts[self::HAVING][] = "($cond)";
  510. }
  511. return $this;
  512. }
  513. /**
  514. * Adds a row order to the query.
  515. *
  516. * @param mixed $spec The column(s) and direction to order by.
  517. * @return Zend_Db_Select This Zend_Db_Select object.
  518. */
  519. public function order($spec)
  520. {
  521. if (!is_array($spec)) {
  522. $spec = array($spec);
  523. }
  524. // force 'ASC' or 'DESC' on each order spec, default is ASC.
  525. foreach ($spec as $val) {
  526. if ($val instanceof Zend_Db_Expr) {
  527. $expr = $val->__toString();
  528. if (empty($expr)) {
  529. continue;
  530. }
  531. $this->_parts[self::ORDER][] = $val;
  532. } else {
  533. if (empty($val)) {
  534. continue;
  535. }
  536. $direction = self::SQL_ASC;
  537. if (preg_match('/(.*\W)(' . self::SQL_ASC . '|' . self::SQL_DESC . ')\b/si', $val, $matches)) {
  538. $val = trim($matches[1]);
  539. $direction = $matches[2];
  540. }
  541. if (preg_match('/\(.*\)/', $val)) {
  542. $val = new Zend_Db_Expr($val);
  543. }
  544. $this->_parts[self::ORDER][] = array($val, $direction);
  545. }
  546. }
  547. return $this;
  548. }
  549. /**
  550. * Sets a limit count and offset to the query.
  551. *
  552. * @param int $count OPTIONAL The number of rows to return.
  553. * @param int $offset OPTIONAL Start returning after this many rows.
  554. * @return Zend_Db_Select This Zend_Db_Select object.
  555. */
  556. public function limit($count = null, $offset = null)
  557. {
  558. $this->_parts[self::LIMIT_COUNT] = (int) $count;
  559. $this->_parts[self::LIMIT_OFFSET] = (int) $offset;
  560. return $this;
  561. }
  562. /**
  563. * Sets the limit and count by page number.
  564. *
  565. * @param int $page Limit results to this page number.
  566. * @param int $rowCount Use this many rows per page.
  567. * @return Zend_Db_Select This Zend_Db_Select object.
  568. */
  569. public function limitPage($page, $rowCount)
  570. {
  571. $page = ($page > 0) ? $page : 1;
  572. $rowCount = ($rowCount > 0) ? $rowCount : 1;
  573. $this->_parts[self::LIMIT_COUNT] = (int) $rowCount;
  574. $this->_parts[self::LIMIT_OFFSET] = (int) $rowCount * ($page - 1);
  575. return $this;
  576. }
  577. /**
  578. * Makes the query SELECT FOR UPDATE.
  579. *
  580. * @param bool $flag Whether or not the SELECT is FOR UPDATE (default true).
  581. * @return Zend_Db_Select This Zend_Db_Select object.
  582. */
  583. public function forUpdate($flag = true)
  584. {
  585. $this->_parts[self::FOR_UPDATE] = (bool) $flag;
  586. return $this;
  587. }
  588. /**
  589. * Get part of the structured information for the currect query.
  590. *
  591. * @param string $part
  592. * @return mixed
  593. * @throws Zend_Db_Select_Exception
  594. */
  595. public function getPart($part)
  596. {
  597. $part = strtolower($part);
  598. if (!array_key_exists($part, $this->_parts)) {
  599. // require_once 'Zend/Db/Select/Exception.php';
  600. throw new Zend_Db_Select_Exception("Invalid Select part '$part'");
  601. }
  602. return $this->_parts[$part];
  603. }
  604. /**
  605. * Executes the current select object and returns the result
  606. *
  607. * @param integer $fetchMode OPTIONAL
  608. * @param mixed $bind An array of data to bind to the placeholders.
  609. * @return PDO_Statement|Zend_Db_Statement
  610. */
  611. public function query($fetchMode = null, $bind = array())
  612. {
  613. if (!empty($bind)) {
  614. $this->bind($bind);
  615. }
  616. $stmt = $this->_adapter->query($this);
  617. if ($fetchMode == null) {
  618. $fetchMode = $this->_adapter->getFetchMode();
  619. }
  620. $stmt->setFetchMode($fetchMode);
  621. return $stmt;
  622. }
  623. /**
  624. * Converts this object to an SQL SELECT string.
  625. *
  626. * @return string|null This object as a SELECT string. (or null if a string cannot be produced.)
  627. */
  628. public function assemble()
  629. {
  630. $sql = self::SQL_SELECT;
  631. foreach (array_keys(self::$_partsInit) as $part) {
  632. $method = '_render' . ucfirst($part);
  633. if (method_exists($this, $method)) {
  634. $sql = $this->$method($sql);
  635. }
  636. }
  637. return $sql;
  638. }
  639. /**
  640. * Clear parts of the Select object, or an individual part.
  641. *
  642. * @param string $part OPTIONAL
  643. * @return Zend_Db_Select
  644. */
  645. public function reset($part = null)
  646. {
  647. if ($part == null) {
  648. $this->_parts = self::$_partsInit;
  649. } else if (array_key_exists($part, self::$_partsInit)) {
  650. $this->_parts[$part] = self::$_partsInit[$part];
  651. }
  652. return $this;
  653. }
  654. /**
  655. * Gets the Zend_Db_Adapter_Abstract for this
  656. * particular Zend_Db_Select object.
  657. *
  658. * @return Zend_Db_Adapter_Abstract
  659. */
  660. public function getAdapter()
  661. {
  662. return $this->_adapter;
  663. }
  664. /**
  665. * Populate the {@link $_parts} 'join' key
  666. *
  667. * Does the dirty work of populating the join key.
  668. *
  669. * The $name and $cols parameters follow the same logic
  670. * as described in the from() method.
  671. *
  672. * @param null|string $type Type of join; inner, left, and null are currently supported
  673. * @param array|string|Zend_Db_Expr $name Table name
  674. * @param string $cond Join on this condition
  675. * @param array|string $cols The columns to select from the joined table
  676. * @param string $schema The database name to specify, if any.
  677. * @return Zend_Db_Select This Zend_Db_Select object
  678. * @throws Zend_Db_Select_Exception
  679. */
  680. protected function _join($type, $name, $cond, $cols, $schema = null)
  681. {
  682. if (!in_array($type, self::$_joinTypes) && $type != self::FROM) {
  683. /**
  684. * @see Zend_Db_Select_Exception
  685. */
  686. // require_once 'Zend/Db/Select/Exception.php';
  687. throw new Zend_Db_Select_Exception("Invalid join type '$type'");
  688. }
  689. if (count($this->_parts[self::UNION])) {
  690. // require_once 'Zend/Db/Select/Exception.php';
  691. throw new Zend_Db_Select_Exception("Invalid use of table with " . self::SQL_UNION);
  692. }
  693. if (empty($name)) {
  694. $correlationName = $tableName = '';
  695. } else if (is_array($name)) {
  696. // Must be array($correlationName => $tableName) or array($ident, ...)
  697. foreach ($name as $_correlationName => $_tableName) {
  698. if (is_string($_correlationName)) {
  699. // We assume the key is the correlation name and value is the table name
  700. $tableName = $_tableName;
  701. $correlationName = $_correlationName;
  702. } else {
  703. // We assume just an array of identifiers, with no correlation name
  704. $tableName = $_tableName;
  705. $correlationName = $this->_uniqueCorrelation($tableName);
  706. }
  707. break;
  708. }
  709. } else if ($name instanceof Zend_Db_Expr|| $name instanceof Zend_Db_Select) {
  710. $tableName = $name;
  711. $correlationName = $this->_uniqueCorrelation('t');
  712. } else if (preg_match('/^(.+)\s+AS\s+(.+)$/i', $name, $m)) {
  713. $tableName = $m[1];
  714. $correlationName = $m[2];
  715. } else {
  716. $tableName = $name;
  717. $correlationName = $this->_uniqueCorrelation($tableName);
  718. }
  719. // Schema from table name overrides schema argument
  720. if (!is_object($tableName) && false !== strpos($tableName, '.')) {
  721. list($schema, $tableName) = explode('.', $tableName);
  722. }
  723. if (!empty($correlationName)) {
  724. if (array_key_exists($correlationName, $this->_parts[self::FROM])) {
  725. /**
  726. * @see Zend_Db_Select_Exception
  727. */
  728. // require_once 'Zend/Db/Select/Exception.php';
  729. throw new Zend_Db_Select_Exception("You cannot define a correlation name '$correlationName' more than once");
  730. }
  731. $lastFromCorrelationName = null;
  732. if ($type == self::FROM) {
  733. // append this from after the last from joinType
  734. $tmpFromParts = $this->_parts[self::FROM];
  735. $this->_parts[self::FROM] = array();
  736. // move all the froms onto the stack
  737. while ($tmpFromParts) {
  738. $currentCorrelationName = key($tmpFromParts);
  739. if ($tmpFromParts[$currentCorrelationName]['joinType'] != self::FROM) {
  740. break;
  741. }
  742. $lastFromCorrelationName = $currentCorrelationName;
  743. $this->_parts[self::FROM][$currentCorrelationName] = array_shift($tmpFromParts);
  744. }
  745. } else {
  746. $tmpFromParts = array();
  747. }
  748. $this->_parts[self::FROM][$correlationName] = array(
  749. 'joinType' => $type,
  750. 'schema' => $schema,
  751. 'tableName' => $tableName,
  752. 'joinCondition' => $cond
  753. );
  754. while ($tmpFromParts) {
  755. $currentCorrelationName = key($tmpFromParts);
  756. $this->_parts[self::FROM][$currentCorrelationName] = array_shift($tmpFromParts);
  757. }
  758. }
  759. // add to the columns from this joined table
  760. if ($type == self::FROM && $lastFromCorrelationName == null) {
  761. $lastFromCorrelationName = true;
  762. }
  763. $this->_tableCols($correlationName, $cols, $lastFromCorrelationName);
  764. return $this;
  765. }
  766. /**
  767. * Handle JOIN... USING... syntax
  768. *
  769. * This is functionality identical to the existing JOIN methods, however
  770. * the join condition can be passed as a single column name. This method
  771. * then completes the ON condition by using the same field for the FROM
  772. * table and the JOIN table.
  773. *
  774. * <code>
  775. * $select = $db->select()->from('table1')
  776. * ->joinUsing('table2', 'column1');
  777. *
  778. * // SELECT * FROM table1 JOIN table2 ON table1.column1 = table2.column2
  779. * </code>
  780. *
  781. * These joins are called by the developer simply by adding 'Using' to the
  782. * method name. E.g.
  783. * * joinUsing
  784. * * joinInnerUsing
  785. * * joinFullUsing
  786. * * joinRightUsing
  787. * * joinLeftUsing
  788. *
  789. * @return Zend_Db_Select This Zend_Db_Select object.
  790. */
  791. public function _joinUsing($type, $name, $cond, $cols = '*', $schema = null)
  792. {
  793. if (empty($this->_parts[self::FROM])) {
  794. // require_once 'Zend/Db/Select/Exception.php';
  795. throw new Zend_Db_Select_Exception("You can only perform a joinUsing after specifying a FROM table");
  796. }
  797. $join = $this->_adapter->quoteIdentifier(key($this->_parts[self::FROM]), true);
  798. $from = $this->_adapter->quoteIdentifier($this->_uniqueCorrelation($name), true);
  799. $cond1 = $from . '.' . $cond;
  800. $cond2 = $join . '.' . $cond;
  801. $cond = $cond1 . ' = ' . $cond2;
  802. return $this->_join($type, $name, $cond, $cols, $schema);
  803. }
  804. /**
  805. * Generate a unique correlation name
  806. *
  807. * @param string|array $name A qualified identifier.
  808. * @return string A unique correlation name.
  809. */
  810. private function _uniqueCorrelation($name)
  811. {
  812. if (is_array($name)) {
  813. $c = end($name);
  814. } else {
  815. // Extract just the last name of a qualified table name
  816. $dot = strrpos($name,'.');
  817. $c = ($dot === false) ? $name : substr($name, $dot+1);
  818. }
  819. for ($i = 2; array_key_exists($c, $this->_parts[self::FROM]); ++$i) {
  820. $c = $name . '_' . (string) $i;
  821. }
  822. return $c;
  823. }
  824. /**
  825. * Adds to the internal table-to-column mapping array.
  826. *
  827. * @param string $tbl The table/join the columns come from.
  828. * @param array|string $cols The list of columns; preferably as
  829. * an array, but possibly as a string containing one column.
  830. * @param bool|string True if it should be prepended, a correlation name if it should be inserted
  831. * @return void
  832. */
  833. protected function _tableCols($correlationName, $cols, $afterCorrelationName = null)
  834. {
  835. if (!is_array($cols)) {
  836. $cols = array($cols);
  837. }
  838. if ($correlationName == null) {
  839. $correlationName = '';
  840. }
  841. $columnValues = array();
  842. foreach (array_filter($cols) as $alias => $col) {
  843. $currentCorrelationName = $correlationName;
  844. if (is_string($col)) {
  845. // Check for a column matching "<column> AS <alias>" and extract the alias name
  846. if (preg_match('/^(.+)\s+' . self::SQL_AS . '\s+(.+)$/i', $col, $m)) {
  847. $col = $m[1];
  848. $alias = $m[2];
  849. }
  850. // Check for columns that look like functions and convert to Zend_Db_Expr
  851. if (preg_match('/\(.*\)/', $col)) {
  852. $col = new Zend_Db_Expr($col);
  853. } elseif (preg_match('/(.+)\.(.+)/', $col, $m)) {
  854. $currentCorrelationName = $m[1];
  855. $col = $m[2];
  856. }
  857. }
  858. $columnValues[] = array($currentCorrelationName, $col, is_string($alias) ? $alias : null);
  859. }
  860. if ($columnValues) {
  861. // should we attempt to prepend or insert these values?
  862. if ($afterCorrelationName === true || is_string($afterCorrelationName)) {
  863. $tmpColumns = $this->_parts[self::COLUMNS];
  864. $this->_parts[self::COLUMNS] = array();
  865. } else {
  866. $tmpColumns = array();
  867. }
  868. // find the correlation name to insert after
  869. if (is_string($afterCorrelationName)) {
  870. while ($tmpColumns) {
  871. $this->_parts[self::COLUMNS][] = $currentColumn = array_shift($tmpColumns);
  872. if ($currentColumn[0] == $afterCorrelationName) {
  873. break;
  874. }
  875. }
  876. }
  877. // apply current values to current stack
  878. foreach ($columnValues as $columnValue) {
  879. array_push($this->_parts[self::COLUMNS], $columnValue);
  880. }
  881. // finish ensuring that all previous values are applied (if they exist)
  882. while ($tmpColumns) {
  883. array_push($this->_parts[self::COLUMNS], array_shift($tmpColumns));
  884. }
  885. }
  886. }
  887. /**
  888. * Internal function for creating the where clause
  889. *
  890. * @param string $condition
  891. * @param string $value optional
  892. * @param string $type optional
  893. * @param boolean $bool true = AND, false = OR
  894. * @return string clause
  895. */
  896. protected function _where($condition, $value = null, $type = null, $bool = true)
  897. {
  898. if (count($this->_parts[self::UNION])) {
  899. // require_once 'Zend/Db/Select/Exception.php';
  900. throw new Zend_Db_Select_Exception("Invalid use of where clause with " . self::SQL_UNION);
  901. }
  902. // Webligo php 5.1 compat
  903. if( is_object($condition) && method_exists($condition, '__toString') ) {
  904. $condition = $condition->__toString();
  905. }
  906. if ($value !== null) {
  907. $condition = $this->_adapter->quoteInto($condition, $value, $type);
  908. }
  909. $cond = "";
  910. if ($this->_parts[self::WHERE]) {
  911. if ($bool === true) {
  912. $cond = self::SQL_AND . ' ';
  913. } else {
  914. $cond = self::SQL_OR . ' ';
  915. }
  916. }
  917. return $cond . "($condition)";
  918. }
  919. /**
  920. * @return array
  921. */
  922. protected function _getDummyTable()
  923. {
  924. return array();
  925. }
  926. /**
  927. * Return a quoted schema name
  928. *
  929. * @param string $schema The schema name OPTIONAL
  930. * @return string|null
  931. */
  932. protected function _getQuotedSchema($schema = null)
  933. {
  934. if ($schema === null) {
  935. return null;
  936. }
  937. return $this->_adapter->quoteIdentifier($schema, true) . '.';
  938. }
  939. /**
  940. * Return a quoted table name
  941. *
  942. * @param string $tableName The table name
  943. * @param string $correlationName The correlation name OPTIONAL
  944. * @return string
  945. */
  946. protected function _getQuotedTable($tableName, $correlationName = null)
  947. {
  948. return $this->_adapter->quoteTableAs($tableName, $correlationName, true);
  949. }
  950. /**
  951. * Render DISTINCT clause
  952. *
  953. * @param string $sql SQL query
  954. * @return string
  955. */
  956. protected function _renderDistinct($sql)
  957. {
  958. if ($this->_parts[self::DISTINCT]) {
  959. $sql .= ' ' . self::SQL_DISTINCT;
  960. }
  961. return $sql;
  962. }
  963. /**
  964. * Render DISTINCT clause
  965. *
  966. * @param string $sql SQL query
  967. * @return string|null
  968. */
  969. protected function _renderColumns($sql)
  970. {
  971. if (!count($this->_parts[self::COLUMNS])) {
  972. return null;
  973. }
  974. $columns = array();
  975. foreach ($this->_parts[self::COLUMNS] as $columnEntry) {
  976. list($correlationName, $column, $alias) = $columnEntry;
  977. if ($column instanceof Zend_Db_Expr) {
  978. $columns[] = $this->_adapter->quoteColumnAs($column, $alias, true);
  979. } else {
  980. if ($column == self::SQL_WILDCARD) {
  981. $column = new Zend_Db_Expr(self::SQL_WILDCARD);
  982. $alias = null;
  983. }
  984. if (empty($correlationName)) {
  985. $columns[] = $this->_adapter->quoteColumnAs($column, $alias, true);
  986. } else {
  987. $columns[] = $this->_adapter->quoteColumnAs(array($correlationName, $column), $alias, true);
  988. }
  989. }
  990. }
  991. return $sql .= ' ' . implode(', ', $columns);
  992. }
  993. /**
  994. * Render FROM clause
  995. *
  996. * @param string $sql SQL query
  997. * @return string
  998. */
  999. protected function _renderFrom($sql)
  1000. {
  1001. /*
  1002. * If no table specified, use RDBMS-dependent solution
  1003. * for table-less query. e.g. DUAL in Oracle.
  1004. */
  1005. if (empty($this->_parts[self::FROM])) {
  1006. $this->_parts[self::FROM] = $this->_getDummyTable();
  1007. }
  1008. $from = array();
  1009. foreach ($this->_parts[self::FROM] as $correlationName => $table) {
  1010. $tmp = '';
  1011. $joinType = ($table['joinType'] == self::FROM) ? self::INNER_JOIN : $table['joinType'];
  1012. // Add join clause (if applicable)
  1013. if (! empty($from)) {
  1014. $tmp .= ' ' . strtoupper($joinType) . ' ';
  1015. }
  1016. $tmp .= $this->_getQuotedSchema($table['schema']);
  1017. $tmp .= $this->_getQuotedTable($table['tableName'], $correlationName);
  1018. // Add join conditions (if applicable)
  1019. if (!empty($from) && ! empty($table['joinCondition'])) {
  1020. $tmp .= ' ' . self::SQL_ON . ' ' . $table['joinCondition'];
  1021. }
  1022. // Add the table name and condition add to the list
  1023. $from[] = $tmp;
  1024. }
  1025. // Add the list of all joins
  1026. if (!empty($from)) {
  1027. $sql .= ' ' . self::SQL_FROM . ' ' . implode("\n", $from);
  1028. }
  1029. return $sql;
  1030. }
  1031. /**
  1032. * Render UNION query
  1033. *
  1034. * @param string $sql SQL query
  1035. * @return string
  1036. */
  1037. protected function _renderUnion($sql)
  1038. {
  1039. if ($this->_parts[self::UNION]) {
  1040. $parts = count($this->_parts[self::UNION]);
  1041. foreach ($this->_parts[self::UNION] as $cnt => $union) {
  1042. list($target, $type) = $union;
  1043. if ($target instanceof Zend_Db_Select) {
  1044. $target = $target->assemble();
  1045. }
  1046. $sql .= $target;
  1047. if ($cnt < $parts - 1) {
  1048. $sql .= ' ' . $type . ' ';
  1049. }
  1050. }
  1051. }
  1052. return $sql;
  1053. }
  1054. /**
  1055. * Render WHERE clause
  1056. *
  1057. * @param string $sql SQL query
  1058. * @return string
  1059. */
  1060. protected function _renderWhere($sql)
  1061. {
  1062. if ($this->_parts[self::FROM] && $this->_parts[self::WHERE]) {
  1063. $sql .= ' ' . self::SQL_WHERE . ' ' . implode(' ', $this->_parts[self::WHERE]);
  1064. }
  1065. return $sql;
  1066. }
  1067. /**
  1068. * Render GROUP clause
  1069. *
  1070. * @param string $sql SQL query
  1071. * @return string
  1072. */
  1073. protected function _renderGroup($sql)
  1074. {
  1075. if ($this->_parts[self::FROM] && $this->_parts[self::GROUP]) {
  1076. $group = array();
  1077. foreach ($this->_parts[self::GROUP] as $term) {
  1078. $group[] = $this->_adapter->quoteIdentifier($term, true);
  1079. }
  1080. $sql .= ' ' . self::SQL_GROUP_BY . ' ' . implode(",\n\t", $group);
  1081. }
  1082. return $sql;
  1083. }
  1084. /**
  1085. * Render HAVING clause
  1086. *
  1087. * @param string $sql SQL query
  1088. * @return string
  1089. */
  1090. protected function _renderHaving($sql)
  1091. {
  1092. if ($this->_parts[self::FROM] && $this->_parts[self::HAVING]) {
  1093. $sql .= ' ' . self::SQL_HAVING . ' ' . implode(' ', $this->_parts[self::HAVING]);
  1094. }
  1095. return $sql;
  1096. }
  1097. /**
  1098. * Render ORDER clause
  1099. *
  1100. * @param string $sql SQL query
  1101. * @return string
  1102. */
  1103. protected function _renderOrder($sql)
  1104. {
  1105. if ($this->_parts[self::ORDER]) {
  1106. $order = array();
  1107. foreach ($this->_parts[self::ORDER] as $term) {
  1108. if (is_array($term)) {
  1109. if(is_numeric($term[0]) && strval(intval($term[0])) == $term[0]) {
  1110. $order[] = (int)trim($term[0]) . ' ' . $term[1];
  1111. } else {
  1112. $order[] = $this->_adapter->quoteIdentifier($term[0], true) . ' ' . $term[1];
  1113. }
  1114. } else if (is_numeric($term) && strval(intval($term)) == $term) {
  1115. $order[] = (int)trim($term);
  1116. } else {
  1117. $order[] = $this->_adapter->quoteIdentifier($term, true);
  1118. }
  1119. }
  1120. $sql .= ' ' . self::SQL_ORDER_BY . ' ' . implode(', ', $order);
  1121. }
  1122. return $sql;
  1123. }
  1124. /**
  1125. * Render LIMIT OFFSET clause
  1126. *
  1127. * @param string $sql SQL query
  1128. * @return string
  1129. */
  1130. protected function _renderLimitoffset($sql)
  1131. {
  1132. $count = 0;
  1133. $offset = 0;
  1134. if (!empty($this->_parts[self::LIMIT_OFFSET])) {
  1135. $offset = (int) $this->_parts[self::LIMIT_OFFSET];
  1136. // This should reduce to the max integer PHP can support
  1137. $count = intval(9223372036854775807);
  1138. }
  1139. if (!empty($this->_parts[self::LIMIT_COUNT])) {
  1140. $count = (int) $this->_parts[self::LIMIT_COUNT];
  1141. }
  1142. /*
  1143. * Add limits clause
  1144. */
  1145. if ($count > 0) {
  1146. $sql = trim($this->_adapter->limit($sql, $count, $offset));
  1147. }
  1148. return $sql;
  1149. }
  1150. /**
  1151. * Render FOR UPDATE clause
  1152. *
  1153. * @param string $sql SQL query
  1154. * @return string
  1155. */
  1156. protected function _renderForupdate($sql)
  1157. {
  1158. if ($this->_parts[self::FOR_UPDATE]) {
  1159. $sql .= ' ' . self::SQL_FOR_UPDATE;
  1160. }
  1161. return $sql;
  1162. }
  1163. /**
  1164. * Turn magic function calls into non-magic function calls
  1165. * for joinUsing syntax
  1166. *
  1167. * @param string $method
  1168. * @param array $args OPTIONAL Zend_Db_Table_Select query modifier
  1169. * @return Zend_Db_Select
  1170. * @throws Zend_Db_Select_Exception If an invalid method is called.
  1171. */
  1172. public function __call($method, array $args)
  1173. {
  1174. $matches = array();
  1175. /**
  1176. * Recognize methods for Has-Many cases:
  1177. * findParent<Class>()
  1178. * findParent<Class>By<Rule>()
  1179. * Use the non-greedy pattern repeat modifier e.g. \w+?
  1180. */
  1181. if (preg_match('/^join([a-zA-Z]*?)Using$/', $method, $matches)) {
  1182. $type = strtolower($matches[1]);
  1183. if ($type) {
  1184. $type .= ' join';
  1185. if (!in_array($type, self::$_joinTypes)) {
  1186. // require_once 'Zend/Db/Select/Exception.php';
  1187. throw new Zend_Db_Select_Exception("Unrecognized method '$method()'");
  1188. }
  1189. if (in_array($type, array(self::CROSS_JOIN, self::NATURAL_JOIN))) {
  1190. // require_once 'Zend/Db/Select/Exception.php';
  1191. throw new Zend_Db_Select_Exception("Cannot perform a joinUsing with method '$method()'");
  1192. }
  1193. } else {
  1194. $type = self::INNER_JOIN;
  1195. }
  1196. array_unshift($args, $type);
  1197. return call_user_func_array(array($this, '_joinUsing'), $args);
  1198. }
  1199. // require_once 'Zend/Db/Select/Exception.php';
  1200. throw new Zend_Db_Select_Exception("Unrecognized method '$method()'");
  1201. }
  1202. /**
  1203. * Implements magic method.
  1204. *
  1205. * @return string This object as a SELECT string.
  1206. */
  1207. public function __toString()
  1208. {
  1209. try {
  1210. $sql = $this->assemble();
  1211. } catch (Exception $e) {
  1212. trigger_error($e->getMessage(), E_USER_WARNING);
  1213. $sql = '';
  1214. }
  1215. return (string)$sql;
  1216. }
  1217. }