2
0

Select.php 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285
  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$
  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->joinInner($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 has to be an array of Zend_Db_Select or
  240. * sql query strings.
  241. *
  242. * <code>
  243. * $sql1 = $db->select();
  244. * $sql2 = "SELECT ...";
  245. * $select = $db->select()
  246. * ->union(array($sql1, $sql2))
  247. * ->order("id");
  248. * </code>
  249. *
  250. * @param array $select Array of select clauses for the union.
  251. * @return Zend_Db_Select This Zend_Db_Select object.
  252. */
  253. public function union($select = array(), $type = self::SQL_UNION)
  254. {
  255. if (!is_array($select)) {
  256. require_once 'Zend/Db/Select/Exception.php';
  257. throw new Zend_Db_Select_Exception(
  258. "union() only accepts an array of Zend_Db_Select instances of sql query strings."
  259. );
  260. }
  261. if (!in_array($type, self::$_unionTypes)) {
  262. require_once 'Zend/Db/Select/Exception.php';
  263. throw new Zend_Db_Select_Exception("Invalid union type '{$type}'");
  264. }
  265. foreach ($select as $target) {
  266. $this->_parts[self::UNION][] = array($target, $type);
  267. }
  268. return $this;
  269. }
  270. /**
  271. * Adds a JOIN table and columns to the query.
  272. *
  273. * The $name and $cols parameters follow the same logic
  274. * as described in the from() method.
  275. *
  276. * @param array|string|Zend_Db_Expr $name The table name.
  277. * @param string $cond Join on this condition.
  278. * @param array|string $cols The columns to select from the joined table.
  279. * @param string $schema The database name to specify, if any.
  280. * @return Zend_Db_Select This Zend_Db_Select object.
  281. */
  282. public function join($name, $cond, $cols = self::SQL_WILDCARD, $schema = null)
  283. {
  284. return $this->joinInner($name, $cond, $cols, $schema);
  285. }
  286. /**
  287. * Add an INNER JOIN table and colums to the query
  288. * Rows in both tables are matched according to the expression
  289. * in the $cond argument. The result set is comprised
  290. * of all cases where rows from the left table match
  291. * rows from the right table.
  292. *
  293. * The $name and $cols parameters follow the same logic
  294. * as described in the from() method.
  295. *
  296. * @param array|string|Zend_Db_Expr $name The table name.
  297. * @param string $cond Join on this condition.
  298. * @param array|string $cols The columns to select from the joined table.
  299. * @param string $schema The database name to specify, if any.
  300. * @return Zend_Db_Select This Zend_Db_Select object.
  301. */
  302. public function joinInner($name, $cond, $cols = self::SQL_WILDCARD, $schema = null)
  303. {
  304. return $this->_join(self::INNER_JOIN, $name, $cond, $cols, $schema);
  305. }
  306. /**
  307. * Add a LEFT OUTER JOIN table and colums to the query
  308. * All rows from the left operand table are included,
  309. * matching rows from the right operand table included,
  310. * and the columns from the right operand table are filled
  311. * with NULLs if no row exists matching the left table.
  312. *
  313. * The $name and $cols parameters follow the same logic
  314. * as described in the from() method.
  315. *
  316. * @param array|string|Zend_Db_Expr $name The table name.
  317. * @param string $cond Join on this condition.
  318. * @param array|string $cols The columns to select from the joined table.
  319. * @param string $schema The database name to specify, if any.
  320. * @return Zend_Db_Select This Zend_Db_Select object.
  321. */
  322. public function joinLeft($name, $cond, $cols = self::SQL_WILDCARD, $schema = null)
  323. {
  324. return $this->_join(self::LEFT_JOIN, $name, $cond, $cols, $schema);
  325. }
  326. /**
  327. * Add a RIGHT OUTER JOIN table and colums to the query.
  328. * Right outer join is the complement of left outer join.
  329. * All rows from the right operand table are included,
  330. * matching rows from the left operand table included,
  331. * and the columns from the left operand table are filled
  332. * with NULLs if no row exists matching the right table.
  333. *
  334. * The $name and $cols parameters follow the same logic
  335. * as described in the from() method.
  336. *
  337. * @param array|string|Zend_Db_Expr $name The table name.
  338. * @param string $cond Join on this condition.
  339. * @param array|string $cols The columns to select from the joined table.
  340. * @param string $schema The database name to specify, if any.
  341. * @return Zend_Db_Select This Zend_Db_Select object.
  342. */
  343. public function joinRight($name, $cond, $cols = self::SQL_WILDCARD, $schema = null)
  344. {
  345. return $this->_join(self::RIGHT_JOIN, $name, $cond, $cols, $schema);
  346. }
  347. /**
  348. * Add a FULL OUTER JOIN table and colums to the query.
  349. * A full outer join is like combining a left outer join
  350. * and a right outer join. All rows from both tables are
  351. * included, paired with each other on the same row of the
  352. * result set if they satisfy the join condition, and otherwise
  353. * paired with NULLs in place of columns from the other table.
  354. *
  355. * The $name and $cols parameters follow the same logic
  356. * as described in the from() method.
  357. *
  358. * @param array|string|Zend_Db_Expr $name The table name.
  359. * @param string $cond Join on this condition.
  360. * @param array|string $cols The columns to select from the joined table.
  361. * @param string $schema The database name to specify, if any.
  362. * @return Zend_Db_Select This Zend_Db_Select object.
  363. */
  364. public function joinFull($name, $cond, $cols = self::SQL_WILDCARD, $schema = null)
  365. {
  366. return $this->_join(self::FULL_JOIN, $name, $cond, $cols, $schema);
  367. }
  368. /**
  369. * Add a CROSS JOIN table and colums to the query.
  370. * A cross join is a cartesian product; there is no join condition.
  371. *
  372. * The $name and $cols parameters follow the same logic
  373. * as described in the from() method.
  374. *
  375. * @param array|string|Zend_Db_Expr $name The table name.
  376. * @param array|string $cols The columns to select from the joined table.
  377. * @param string $schema The database name to specify, if any.
  378. * @return Zend_Db_Select This Zend_Db_Select object.
  379. */
  380. public function joinCross($name, $cols = self::SQL_WILDCARD, $schema = null)
  381. {
  382. return $this->_join(self::CROSS_JOIN, $name, null, $cols, $schema);
  383. }
  384. /**
  385. * Add a NATURAL JOIN table and colums to the query.
  386. * A natural join assumes an equi-join across any column(s)
  387. * that appear with the same name in both tables.
  388. * Only natural inner joins are supported by this API,
  389. * even though SQL permits natural outer joins as well.
  390. *
  391. * The $name and $cols parameters follow the same logic
  392. * as described in the from() method.
  393. *
  394. * @param array|string|Zend_Db_Expr $name The table name.
  395. * @param array|string $cols The columns to select from the joined table.
  396. * @param string $schema The database name to specify, if any.
  397. * @return Zend_Db_Select This Zend_Db_Select object.
  398. */
  399. public function joinNatural($name, $cols = self::SQL_WILDCARD, $schema = null)
  400. {
  401. return $this->_join(self::NATURAL_JOIN, $name, null, $cols, $schema);
  402. }
  403. /**
  404. * Adds a WHERE condition to the query by AND.
  405. *
  406. * If a value is passed as the second param, it will be quoted
  407. * and replaced into the condition wherever a question-mark
  408. * appears. Array values are quoted and comma-separated.
  409. *
  410. * <code>
  411. * // simplest but non-secure
  412. * $select->where("id = $id");
  413. *
  414. * // secure (ID is quoted but matched anyway)
  415. * $select->where('id = ?', $id);
  416. *
  417. * // alternatively, with named binding
  418. * $select->where('id = :id');
  419. * </code>
  420. *
  421. * Note that it is more correct to use named bindings in your
  422. * queries for values other than strings. When you use named
  423. * bindings, don't forget to pass the values when actually
  424. * making a query:
  425. *
  426. * <code>
  427. * $db->fetchAll($select, array('id' => 5));
  428. * </code>
  429. *
  430. * @param string $cond The WHERE condition.
  431. * @param string $value OPTIONAL A single value to quote into the condition.
  432. * @param constant $type OPTIONAL The type of the given value
  433. * @return Zend_Db_Select This Zend_Db_Select object.
  434. */
  435. public function where($cond, $value = null, $type = null)
  436. {
  437. $this->_parts[self::WHERE][] = $this->_where($cond, $value, $type, true);
  438. return $this;
  439. }
  440. /**
  441. * Adds a WHERE condition to the query by OR.
  442. *
  443. * Otherwise identical to where().
  444. *
  445. * @param string $cond The WHERE condition.
  446. * @param string $value OPTIONAL A single value to quote into the condition.
  447. * @param constant $type OPTIONAL The type of the given value
  448. * @return Zend_Db_Select This Zend_Db_Select object.
  449. *
  450. * @see where()
  451. */
  452. public function orWhere($cond, $value = null, $type = null)
  453. {
  454. $this->_parts[self::WHERE][] = $this->_where($cond, $value, $type, false);
  455. return $this;
  456. }
  457. /**
  458. * Adds grouping to the query.
  459. *
  460. * @param array|string $spec The column(s) to group by.
  461. * @return Zend_Db_Select This Zend_Db_Select object.
  462. */
  463. public function group($spec)
  464. {
  465. if (!is_array($spec)) {
  466. $spec = array($spec);
  467. }
  468. foreach ($spec as $val) {
  469. if (preg_match('/\(.*\)/', (string) $val)) {
  470. $val = new Zend_Db_Expr($val);
  471. }
  472. $this->_parts[self::GROUP][] = $val;
  473. }
  474. return $this;
  475. }
  476. /**
  477. * Adds a HAVING condition to the query by AND.
  478. *
  479. * If a value is passed as the second param, it will be quoted
  480. * and replaced into the condition wherever a question-mark
  481. * appears. See {@link where()} for an example
  482. *
  483. * @param string $cond The HAVING condition.
  484. * @param string|Zend_Db_Expr $val A single value to quote into the condition.
  485. * @return Zend_Db_Select This Zend_Db_Select object.
  486. */
  487. public function having($cond)
  488. {
  489. if (func_num_args() > 1) {
  490. $val = func_get_arg(1);
  491. $cond = $this->_adapter->quoteInto($cond, $val);
  492. }
  493. if ($this->_parts[self::HAVING]) {
  494. $this->_parts[self::HAVING][] = self::SQL_AND . " ($cond)";
  495. } else {
  496. $this->_parts[self::HAVING][] = "($cond)";
  497. }
  498. return $this;
  499. }
  500. /**
  501. * Adds a HAVING condition to the query by OR.
  502. *
  503. * Otherwise identical to orHaving().
  504. *
  505. * @param string $cond The HAVING condition.
  506. * @param string $val A single value to quote into the condition.
  507. * @return Zend_Db_Select This Zend_Db_Select object.
  508. *
  509. * @see having()
  510. */
  511. public function orHaving($cond)
  512. {
  513. if (func_num_args() > 1) {
  514. $val = func_get_arg(1);
  515. $cond = $this->_adapter->quoteInto($cond, $val);
  516. }
  517. if ($this->_parts[self::HAVING]) {
  518. $this->_parts[self::HAVING][] = self::SQL_OR . " ($cond)";
  519. } else {
  520. $this->_parts[self::HAVING][] = "($cond)";
  521. }
  522. return $this;
  523. }
  524. /**
  525. * Adds a row order to the query.
  526. *
  527. * @param mixed $spec The column(s) and direction to order by.
  528. * @return Zend_Db_Select This Zend_Db_Select object.
  529. */
  530. public function order($spec)
  531. {
  532. if (!is_array($spec)) {
  533. $spec = array($spec);
  534. }
  535. // force 'ASC' or 'DESC' on each order spec, default is ASC.
  536. foreach ($spec as $val) {
  537. if ($val instanceof Zend_Db_Expr) {
  538. $expr = $val->__toString();
  539. if (empty($expr)) {
  540. continue;
  541. }
  542. $this->_parts[self::ORDER][] = $val;
  543. } else {
  544. if (empty($val)) {
  545. continue;
  546. }
  547. $direction = self::SQL_ASC;
  548. if (preg_match('/(.*\W)(' . self::SQL_ASC . '|' . self::SQL_DESC . ')\b/si', $val, $matches)) {
  549. $val = trim($matches[1]);
  550. $direction = $matches[2];
  551. }
  552. if (preg_match('/\(.*\)/', $val)) {
  553. $val = new Zend_Db_Expr($val);
  554. }
  555. $this->_parts[self::ORDER][] = array($val, $direction);
  556. }
  557. }
  558. return $this;
  559. }
  560. /**
  561. * Sets a limit count and offset to the query.
  562. *
  563. * @param int $count OPTIONAL The number of rows to return.
  564. * @param int $offset OPTIONAL Start returning after this many rows.
  565. * @return Zend_Db_Select This Zend_Db_Select object.
  566. */
  567. public function limit($count = null, $offset = null)
  568. {
  569. $this->_parts[self::LIMIT_COUNT] = (int) $count;
  570. $this->_parts[self::LIMIT_OFFSET] = (int) $offset;
  571. return $this;
  572. }
  573. /**
  574. * Sets the limit and count by page number.
  575. *
  576. * @param int $page Limit results to this page number.
  577. * @param int $rowCount Use this many rows per page.
  578. * @return Zend_Db_Select This Zend_Db_Select object.
  579. */
  580. public function limitPage($page, $rowCount)
  581. {
  582. $page = ($page > 0) ? $page : 1;
  583. $rowCount = ($rowCount > 0) ? $rowCount : 1;
  584. $this->_parts[self::LIMIT_COUNT] = (int) $rowCount;
  585. $this->_parts[self::LIMIT_OFFSET] = (int) $rowCount * ($page - 1);
  586. return $this;
  587. }
  588. /**
  589. * Makes the query SELECT FOR UPDATE.
  590. *
  591. * @param bool $flag Whether or not the SELECT is FOR UPDATE (default true).
  592. * @return Zend_Db_Select This Zend_Db_Select object.
  593. */
  594. public function forUpdate($flag = true)
  595. {
  596. $this->_parts[self::FOR_UPDATE] = (bool) $flag;
  597. return $this;
  598. }
  599. /**
  600. * Get part of the structured information for the currect query.
  601. *
  602. * @param string $part
  603. * @return mixed
  604. * @throws Zend_Db_Select_Exception
  605. */
  606. public function getPart($part)
  607. {
  608. $part = strtolower($part);
  609. if (!array_key_exists($part, $this->_parts)) {
  610. require_once 'Zend/Db/Select/Exception.php';
  611. throw new Zend_Db_Select_Exception("Invalid Select part '$part'");
  612. }
  613. return $this->_parts[$part];
  614. }
  615. /**
  616. * Executes the current select object and returns the result
  617. *
  618. * @param integer $fetchMode OPTIONAL
  619. * @param mixed $bind An array of data to bind to the placeholders.
  620. * @return PDO_Statement|Zend_Db_Statement
  621. */
  622. public function query($fetchMode = null, $bind = array())
  623. {
  624. if (!empty($bind)) {
  625. $this->bind($bind);
  626. }
  627. $stmt = $this->_adapter->query($this);
  628. if ($fetchMode == null) {
  629. $fetchMode = $this->_adapter->getFetchMode();
  630. }
  631. $stmt->setFetchMode($fetchMode);
  632. return $stmt;
  633. }
  634. /**
  635. * Converts this object to an SQL SELECT string.
  636. *
  637. * @return string|null This object as a SELECT string. (or null if a string cannot be produced.)
  638. */
  639. public function assemble()
  640. {
  641. $sql = self::SQL_SELECT;
  642. foreach (array_keys(self::$_partsInit) as $part) {
  643. $method = '_render' . ucfirst($part);
  644. if (method_exists($this, $method)) {
  645. $sql = $this->$method($sql);
  646. }
  647. }
  648. return $sql;
  649. }
  650. /**
  651. * Clear parts of the Select object, or an individual part.
  652. *
  653. * @param string $part OPTIONAL
  654. * @return Zend_Db_Select
  655. */
  656. public function reset($part = null)
  657. {
  658. if ($part == null) {
  659. $this->_parts = self::$_partsInit;
  660. } else if (array_key_exists($part, self::$_partsInit)) {
  661. $this->_parts[$part] = self::$_partsInit[$part];
  662. }
  663. return $this;
  664. }
  665. /**
  666. * Gets the Zend_Db_Adapter_Abstract for this
  667. * particular Zend_Db_Select object.
  668. *
  669. * @return Zend_Db_Adapter_Abstract
  670. */
  671. public function getAdapter()
  672. {
  673. return $this->_adapter;
  674. }
  675. /**
  676. * Populate the {@link $_parts} 'join' key
  677. *
  678. * Does the dirty work of populating the join key.
  679. *
  680. * The $name and $cols parameters follow the same logic
  681. * as described in the from() method.
  682. *
  683. * @param null|string $type Type of join; inner, left, and null are currently supported
  684. * @param array|string|Zend_Db_Expr $name Table name
  685. * @param string $cond Join on this condition
  686. * @param array|string $cols The columns to select from the joined table
  687. * @param string $schema The database name to specify, if any.
  688. * @return Zend_Db_Select This Zend_Db_Select object
  689. * @throws Zend_Db_Select_Exception
  690. */
  691. protected function _join($type, $name, $cond, $cols, $schema = null)
  692. {
  693. if (!in_array($type, self::$_joinTypes)) {
  694. /**
  695. * @see Zend_Db_Select_Exception
  696. */
  697. require_once 'Zend/Db/Select/Exception.php';
  698. throw new Zend_Db_Select_Exception("Invalid join type '$type'");
  699. }
  700. if (count($this->_parts[self::UNION])) {
  701. require_once 'Zend/Db/Select/Exception.php';
  702. throw new Zend_Db_Select_Exception("Invalid use of table with " . self::SQL_UNION);
  703. }
  704. if (empty($name)) {
  705. $correlationName = $tableName = '';
  706. } else if (is_array($name)) {
  707. // Must be array($correlationName => $tableName) or array($ident, ...)
  708. foreach ($name as $_correlationName => $_tableName) {
  709. if (is_string($_correlationName)) {
  710. // We assume the key is the correlation name and value is the table name
  711. $tableName = $_tableName;
  712. $correlationName = $_correlationName;
  713. } else {
  714. // We assume just an array of identifiers, with no correlation name
  715. $tableName = $_tableName;
  716. $correlationName = $this->_uniqueCorrelation($tableName);
  717. }
  718. break;
  719. }
  720. } else if ($name instanceof Zend_Db_Expr|| $name instanceof Zend_Db_Select) {
  721. $tableName = $name;
  722. $correlationName = $this->_uniqueCorrelation('t');
  723. } else if (preg_match('/^(.+)\s+AS\s+(.+)$/i', $name, $m)) {
  724. $tableName = $m[1];
  725. $correlationName = $m[2];
  726. } else {
  727. $tableName = $name;
  728. $correlationName = $this->_uniqueCorrelation($tableName);
  729. }
  730. // Schema from table name overrides schema argument
  731. if (!is_object($tableName) && false !== strpos($tableName, '.')) {
  732. list($schema, $tableName) = explode('.', $tableName);
  733. }
  734. if (!empty($correlationName)) {
  735. if (array_key_exists($correlationName, $this->_parts[self::FROM])) {
  736. /**
  737. * @see Zend_Db_Select_Exception
  738. */
  739. require_once 'Zend/Db/Select/Exception.php';
  740. throw new Zend_Db_Select_Exception("You cannot define a correlation name '$correlationName' more than once");
  741. }
  742. $this->_parts[self::FROM][$correlationName] = array(
  743. 'joinType' => $type,
  744. 'schema' => $schema,
  745. 'tableName' => $tableName,
  746. 'joinCondition' => $cond
  747. );
  748. }
  749. // add to the columns from this joined table
  750. $this->_tableCols($correlationName, $cols);
  751. return $this;
  752. }
  753. /**
  754. * Handle JOIN... USING... syntax
  755. *
  756. * This is functionality identical to the existing JOIN methods, however
  757. * the join condition can be passed as a single column name. This method
  758. * then completes the ON condition by using the same field for the FROM
  759. * table and the JOIN table.
  760. *
  761. * <code>
  762. * $select = $db->select()->from('table1')
  763. * ->joinUsing('table2', 'column1');
  764. *
  765. * // SELECT * FROM table1 JOIN table2 ON table1.column1 = table2.column2
  766. * </code>
  767. *
  768. * These joins are called by the developer simply by adding 'Using' to the
  769. * method name. E.g.
  770. * * joinUsing
  771. * * joinInnerUsing
  772. * * joinFullUsing
  773. * * joinRightUsing
  774. * * joinLeftUsing
  775. *
  776. * @return Zend_Db_Select This Zend_Db_Select object.
  777. */
  778. public function _joinUsing($type, $name, $cond, $cols = '*', $schema = null)
  779. {
  780. if (empty($this->_parts[self::FROM])) {
  781. require_once 'Zend/Db/Select/Exception.php';
  782. throw new Zend_Db_Select_Exception("You can only perform a joinUsing after specifying a FROM table");
  783. }
  784. $join = $this->_adapter->quoteIdentifier(key($this->_parts[self::FROM]), true);
  785. $from = $this->_adapter->quoteIdentifier($this->_uniqueCorrelation($name), true);
  786. $cond1 = $from . '.' . $cond;
  787. $cond2 = $join . '.' . $cond;
  788. $cond = $cond1 . ' = ' . $cond2;
  789. return $this->_join($type, $name, $cond, $cols, $schema);
  790. }
  791. /**
  792. * Generate a unique correlation name
  793. *
  794. * @param string|array $name A qualified identifier.
  795. * @return string A unique correlation name.
  796. */
  797. private function _uniqueCorrelation($name)
  798. {
  799. if (is_array($name)) {
  800. $c = end($name);
  801. } else {
  802. // Extract just the last name of a qualified table name
  803. $dot = strrpos($name,'.');
  804. $c = ($dot === false) ? $name : substr($name, $dot+1);
  805. }
  806. for ($i = 2; array_key_exists($c, $this->_parts[self::FROM]); ++$i) {
  807. $c = $name . '_' . (string) $i;
  808. }
  809. return $c;
  810. }
  811. /**
  812. * Adds to the internal table-to-column mapping array.
  813. *
  814. * @param string $tbl The table/join the columns come from.
  815. * @param array|string $cols The list of columns; preferably as
  816. * an array, but possibly as a string containing one column.
  817. * @return void
  818. */
  819. protected function _tableCols($correlationName, $cols)
  820. {
  821. if (!is_array($cols)) {
  822. $cols = array($cols);
  823. }
  824. if ($correlationName == null) {
  825. $correlationName = '';
  826. }
  827. foreach (array_filter($cols) as $alias => $col) {
  828. $currentCorrelationName = $correlationName;
  829. if (is_string($col)) {
  830. // Check for a column matching "<column> AS <alias>" and extract the alias name
  831. if (preg_match('/^(.+)\s+' . self::SQL_AS . '\s+(.+)$/i', $col, $m)) {
  832. $col = $m[1];
  833. $alias = $m[2];
  834. }
  835. // Check for columns that look like functions and convert to Zend_Db_Expr
  836. if (preg_match('/\(.*\)/', $col)) {
  837. $col = new Zend_Db_Expr($col);
  838. } elseif (preg_match('/(.+)\.(.+)/', $col, $m)) {
  839. $currentCorrelationName = $m[1];
  840. $col = $m[2];
  841. }
  842. }
  843. $this->_parts[self::COLUMNS][] = array($currentCorrelationName, $col, is_string($alias) ? $alias : null);
  844. }
  845. }
  846. /**
  847. * Internal function for creating the where clause
  848. *
  849. * @param string $condition
  850. * @param string $value optional
  851. * @param string $type optional
  852. * @param boolean $bool true = AND, false = OR
  853. * @return string clause
  854. */
  855. protected function _where($condition, $value = null, $type = null, $bool = true)
  856. {
  857. if (count($this->_parts[self::UNION])) {
  858. require_once 'Zend/Db/Select/Exception.php';
  859. throw new Zend_Db_Select_Exception("Invalid use of where clause with " . self::SQL_UNION);
  860. }
  861. if ($value !== null) {
  862. $condition = $this->_adapter->quoteInto($condition, $value, $type);
  863. }
  864. $cond = "";
  865. if ($this->_parts[self::WHERE]) {
  866. if ($bool === true) {
  867. $cond = self::SQL_AND . ' ';
  868. } else {
  869. $cond = self::SQL_OR . ' ';
  870. }
  871. }
  872. return $cond . "($condition)";
  873. }
  874. /**
  875. * @return array
  876. */
  877. protected function _getDummyTable()
  878. {
  879. return array();
  880. }
  881. /**
  882. * Return a quoted schema name
  883. *
  884. * @param string $schema The schema name OPTIONAL
  885. * @return string|null
  886. */
  887. protected function _getQuotedSchema($schema = null)
  888. {
  889. if ($schema === null) {
  890. return null;
  891. }
  892. return $this->_adapter->quoteIdentifier($schema, true) . '.';
  893. }
  894. /**
  895. * Return a quoted table name
  896. *
  897. * @param string $tableName The table name
  898. * @param string $correlationName The correlation name OPTIONAL
  899. * @return string
  900. */
  901. protected function _getQuotedTable($tableName, $correlationName = null)
  902. {
  903. return $this->_adapter->quoteTableAs($tableName, $correlationName, true);
  904. }
  905. /**
  906. * Render DISTINCT clause
  907. *
  908. * @param string $sql SQL query
  909. * @return string
  910. */
  911. protected function _renderDistinct($sql)
  912. {
  913. if ($this->_parts[self::DISTINCT]) {
  914. $sql .= ' ' . self::SQL_DISTINCT;
  915. }
  916. return $sql;
  917. }
  918. /**
  919. * Render DISTINCT clause
  920. *
  921. * @param string $sql SQL query
  922. * @return string|null
  923. */
  924. protected function _renderColumns($sql)
  925. {
  926. if (!count($this->_parts[self::COLUMNS])) {
  927. return null;
  928. }
  929. $columns = array();
  930. foreach ($this->_parts[self::COLUMNS] as $columnEntry) {
  931. list($correlationName, $column, $alias) = $columnEntry;
  932. if ($column instanceof Zend_Db_Expr) {
  933. $columns[] = $this->_adapter->quoteColumnAs($column, $alias, true);
  934. } else {
  935. if ($column == self::SQL_WILDCARD) {
  936. $column = new Zend_Db_Expr(self::SQL_WILDCARD);
  937. $alias = null;
  938. }
  939. if (empty($correlationName)) {
  940. $columns[] = $this->_adapter->quoteColumnAs($column, $alias, true);
  941. } else {
  942. $columns[] = $this->_adapter->quoteColumnAs(array($correlationName, $column), $alias, true);
  943. }
  944. }
  945. }
  946. return $sql .= ' ' . implode(', ', $columns);
  947. }
  948. /**
  949. * Render FROM clause
  950. *
  951. * @param string $sql SQL query
  952. * @return string
  953. */
  954. protected function _renderFrom($sql)
  955. {
  956. /*
  957. * If no table specified, use RDBMS-dependent solution
  958. * for table-less query. e.g. DUAL in Oracle.
  959. */
  960. if (empty($this->_parts[self::FROM])) {
  961. $this->_parts[self::FROM] = $this->_getDummyTable();
  962. }
  963. $from = array();
  964. foreach ($this->_parts[self::FROM] as $correlationName => $table) {
  965. $tmp = '';
  966. // Add join clause (if applicable)
  967. if (! empty($from)) {
  968. $tmp .= ' ' . strtoupper($table['joinType']) . ' ';
  969. }
  970. $tmp .= $this->_getQuotedSchema($table['schema']);
  971. $tmp .= $this->_getQuotedTable($table['tableName'], $correlationName);
  972. // Add join conditions (if applicable)
  973. if (!empty($from) && ! empty($table['joinCondition'])) {
  974. $tmp .= ' ' . self::SQL_ON . ' ' . $table['joinCondition'];
  975. }
  976. // Add the table name and condition add to the list
  977. $from[] = $tmp;
  978. }
  979. // Add the list of all joins
  980. if (!empty($from)) {
  981. $sql .= ' ' . self::SQL_FROM . ' ' . implode("\n", $from);
  982. }
  983. return $sql;
  984. }
  985. /**
  986. * Render UNION query
  987. *
  988. * @param string $sql SQL query
  989. * @return string
  990. */
  991. protected function _renderUnion($sql)
  992. {
  993. if ($this->_parts[self::UNION]) {
  994. $parts = count($this->_parts[self::UNION]);
  995. foreach ($this->_parts[self::UNION] as $cnt => $union) {
  996. list($target, $type) = $union;
  997. if ($target instanceof Zend_Db_Select) {
  998. $target = $target->assemble();
  999. }
  1000. $sql .= $target;
  1001. if ($cnt < $parts - 1) {
  1002. $sql .= ' ' . $type . ' ';
  1003. }
  1004. }
  1005. }
  1006. return $sql;
  1007. }
  1008. /**
  1009. * Render WHERE clause
  1010. *
  1011. * @param string $sql SQL query
  1012. * @return string
  1013. */
  1014. protected function _renderWhere($sql)
  1015. {
  1016. if ($this->_parts[self::FROM] && $this->_parts[self::WHERE]) {
  1017. $sql .= ' ' . self::SQL_WHERE . ' ' . implode(' ', $this->_parts[self::WHERE]);
  1018. }
  1019. return $sql;
  1020. }
  1021. /**
  1022. * Render GROUP clause
  1023. *
  1024. * @param string $sql SQL query
  1025. * @return string
  1026. */
  1027. protected function _renderGroup($sql)
  1028. {
  1029. if ($this->_parts[self::FROM] && $this->_parts[self::GROUP]) {
  1030. $group = array();
  1031. foreach ($this->_parts[self::GROUP] as $term) {
  1032. $group[] = $this->_adapter->quoteIdentifier($term, true);
  1033. }
  1034. $sql .= ' ' . self::SQL_GROUP_BY . ' ' . implode(",\n\t", $group);
  1035. }
  1036. return $sql;
  1037. }
  1038. /**
  1039. * Render HAVING clause
  1040. *
  1041. * @param string $sql SQL query
  1042. * @return string
  1043. */
  1044. protected function _renderHaving($sql)
  1045. {
  1046. if ($this->_parts[self::FROM] && $this->_parts[self::HAVING]) {
  1047. $sql .= ' ' . self::SQL_HAVING . ' ' . implode(' ', $this->_parts[self::HAVING]);
  1048. }
  1049. return $sql;
  1050. }
  1051. /**
  1052. * Render ORDER clause
  1053. *
  1054. * @param string $sql SQL query
  1055. * @return string
  1056. */
  1057. protected function _renderOrder($sql)
  1058. {
  1059. if ($this->_parts[self::ORDER]) {
  1060. $order = array();
  1061. foreach ($this->_parts[self::ORDER] as $term) {
  1062. if (is_array($term)) {
  1063. $order[] = $this->_adapter->quoteIdentifier($term[0], true) . ' ' . $term[1];
  1064. } else {
  1065. $order[] = $this->_adapter->quoteIdentifier($term, true);
  1066. }
  1067. }
  1068. $sql .= ' ' . self::SQL_ORDER_BY . ' ' . implode(', ', $order);
  1069. }
  1070. return $sql;
  1071. }
  1072. /**
  1073. * Render LIMIT OFFSET clause
  1074. *
  1075. * @param string $sql SQL query
  1076. * @return string
  1077. */
  1078. protected function _renderLimitoffset($sql)
  1079. {
  1080. $count = 0;
  1081. $offset = 0;
  1082. if (!empty($this->_parts[self::LIMIT_OFFSET])) {
  1083. $offset = (int) $this->_parts[self::LIMIT_OFFSET];
  1084. // This should reduce to the max integer PHP can support
  1085. $count = intval(9223372036854775807);
  1086. }
  1087. if (!empty($this->_parts[self::LIMIT_COUNT])) {
  1088. $count = (int) $this->_parts[self::LIMIT_COUNT];
  1089. }
  1090. /*
  1091. * Add limits clause
  1092. */
  1093. if ($count > 0) {
  1094. $sql = trim($this->_adapter->limit($sql, $count, $offset));
  1095. }
  1096. return $sql;
  1097. }
  1098. /**
  1099. * Render FOR UPDATE clause
  1100. *
  1101. * @param string $sql SQL query
  1102. * @return string
  1103. */
  1104. protected function _renderForupdate($sql)
  1105. {
  1106. if ($this->_parts[self::FOR_UPDATE]) {
  1107. $sql .= ' ' . self::SQL_FOR_UPDATE;
  1108. }
  1109. return $sql;
  1110. }
  1111. /**
  1112. * Turn magic function calls into non-magic function calls
  1113. * for joinUsing syntax
  1114. *
  1115. * @param string $method
  1116. * @param array $args OPTIONAL Zend_Db_Table_Select query modifier
  1117. * @return Zend_Db_Select
  1118. * @throws Zend_Db_Select_Exception If an invalid method is called.
  1119. */
  1120. public function __call($method, array $args)
  1121. {
  1122. $matches = array();
  1123. /**
  1124. * Recognize methods for Has-Many cases:
  1125. * findParent<Class>()
  1126. * findParent<Class>By<Rule>()
  1127. * Use the non-greedy pattern repeat modifier e.g. \w+?
  1128. */
  1129. if (preg_match('/^join([a-zA-Z]*?)Using$/', $method, $matches)) {
  1130. $type = strtolower($matches[1]);
  1131. if ($type) {
  1132. $type .= ' join';
  1133. if (!in_array($type, self::$_joinTypes)) {
  1134. require_once 'Zend/Db/Select/Exception.php';
  1135. throw new Zend_Db_Select_Exception("Unrecognized method '$method()'");
  1136. }
  1137. if (in_array($type, array(self::CROSS_JOIN, self::NATURAL_JOIN))) {
  1138. require_once 'Zend/Db/Select/Exception.php';
  1139. throw new Zend_Db_Select_Exception("Cannot perform a joinUsing with method '$method()'");
  1140. }
  1141. } else {
  1142. $type = self::INNER_JOIN;
  1143. }
  1144. array_unshift($args, $type);
  1145. return call_user_func_array(array($this, '_joinUsing'), $args);
  1146. }
  1147. require_once 'Zend/Db/Select/Exception.php';
  1148. throw new Zend_Db_Select_Exception("Unrecognized method '$method()'");
  1149. }
  1150. /**
  1151. * Implements magic method.
  1152. *
  1153. * @return string This object as a SELECT string.
  1154. */
  1155. public function __toString()
  1156. {
  1157. try {
  1158. $sql = $this->assemble();
  1159. } catch (Exception $e) {
  1160. trigger_error($e->getMessage(), E_USER_WARNING);
  1161. $sql = '';
  1162. }
  1163. return (string)$sql;
  1164. }
  1165. }