Select.php 41 KB

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