Select.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  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 $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)) {
  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. $this->_parts[self::FROM][$correlationName] = array(
  732. 'joinType' => $type,
  733. 'schema' => $schema,
  734. 'tableName' => $tableName,
  735. 'joinCondition' => $cond
  736. );
  737. }
  738. // add to the columns from this joined table
  739. $this->_tableCols($correlationName, $cols);
  740. return $this;
  741. }
  742. /**
  743. * Handle JOIN... USING... syntax
  744. *
  745. * This is functionality identical to the existing JOIN methods, however
  746. * the join condition can be passed as a single column name. This method
  747. * then completes the ON condition by using the same field for the FROM
  748. * table and the JOIN table.
  749. *
  750. * <code>
  751. * $select = $db->select()->from('table1')
  752. * ->joinUsing('table2', 'column1');
  753. *
  754. * // SELECT * FROM table1 JOIN table2 ON table1.column1 = table2.column2
  755. * </code>
  756. *
  757. * These joins are called by the developer simply by adding 'Using' to the
  758. * method name. E.g.
  759. * * joinUsing
  760. * * joinInnerUsing
  761. * * joinFullUsing
  762. * * joinRightUsing
  763. * * joinLeftUsing
  764. *
  765. * @return Zend_Db_Select This Zend_Db_Select object.
  766. */
  767. public function _joinUsing($type, $name, $cond, $cols = '*', $schema = null)
  768. {
  769. if (empty($this->_parts[self::FROM])) {
  770. require_once 'Zend/Db/Select/Exception.php';
  771. throw new Zend_Db_Select_Exception("You can only perform a joinUsing after specifying a FROM table");
  772. }
  773. $join = $this->_adapter->quoteIdentifier(key($this->_parts[self::FROM]), true);
  774. $from = $this->_adapter->quoteIdentifier($this->_uniqueCorrelation($name), true);
  775. $cond1 = $from . '.' . $cond;
  776. $cond2 = $join . '.' . $cond;
  777. $cond = $cond1 . ' = ' . $cond2;
  778. return $this->_join($type, $name, $cond, $cols, $schema);
  779. }
  780. /**
  781. * Generate a unique correlation name
  782. *
  783. * @param string|array $name A qualified identifier.
  784. * @return string A unique correlation name.
  785. */
  786. private function _uniqueCorrelation($name)
  787. {
  788. if (is_array($name)) {
  789. $c = end($name);
  790. } else {
  791. // Extract just the last name of a qualified table name
  792. $dot = strrpos($name,'.');
  793. $c = ($dot === false) ? $name : substr($name, $dot+1);
  794. }
  795. for ($i = 2; array_key_exists($c, $this->_parts[self::FROM]); ++$i) {
  796. $c = $name . '_' . (string) $i;
  797. }
  798. return $c;
  799. }
  800. /**
  801. * Adds to the internal table-to-column mapping array.
  802. *
  803. * @param string $tbl The table/join the columns come from.
  804. * @param array|string $cols The list of columns; preferably as
  805. * an array, but possibly as a string containing one column.
  806. * @return void
  807. */
  808. protected function _tableCols($correlationName, $cols)
  809. {
  810. if (!is_array($cols)) {
  811. $cols = array($cols);
  812. }
  813. if ($correlationName == null) {
  814. $correlationName = '';
  815. }
  816. foreach (array_filter($cols) as $alias => $col) {
  817. $currentCorrelationName = $correlationName;
  818. if (is_string($col)) {
  819. // Check for a column matching "<column> AS <alias>" and extract the alias name
  820. if (preg_match('/^(.+)\s+' . self::SQL_AS . '\s+(.+)$/i', $col, $m)) {
  821. $col = $m[1];
  822. $alias = $m[2];
  823. }
  824. // Check for columns that look like functions and convert to Zend_Db_Expr
  825. if (preg_match('/\(.*\)/', $col)) {
  826. $col = new Zend_Db_Expr($col);
  827. } elseif (preg_match('/(.+)\.(.+)/', $col, $m)) {
  828. $currentCorrelationName = $m[1];
  829. $col = $m[2];
  830. }
  831. }
  832. $this->_parts[self::COLUMNS][] = array($currentCorrelationName, $col, is_string($alias) ? $alias : null);
  833. }
  834. }
  835. /**
  836. * Internal function for creating the where clause
  837. *
  838. * @param string $condition
  839. * @param string $value optional
  840. * @param string $type optional
  841. * @param boolean $bool true = AND, false = OR
  842. * @return string clause
  843. */
  844. protected function _where($condition, $value = null, $type = null, $bool = true)
  845. {
  846. if (count($this->_parts[self::UNION])) {
  847. require_once 'Zend/Db/Select/Exception.php';
  848. throw new Zend_Db_Select_Exception("Invalid use of where clause with " . self::SQL_UNION);
  849. }
  850. if ($value !== null) {
  851. $condition = $this->_adapter->quoteInto($condition, $value, $type);
  852. }
  853. $cond = "";
  854. if ($this->_parts[self::WHERE]) {
  855. if ($bool === true) {
  856. $cond = self::SQL_AND . ' ';
  857. } else {
  858. $cond = self::SQL_OR . ' ';
  859. }
  860. }
  861. return $cond . "($condition)";
  862. }
  863. /**
  864. * @return array
  865. */
  866. protected function _getDummyTable()
  867. {
  868. return array();
  869. }
  870. /**
  871. * Return a quoted schema name
  872. *
  873. * @param string $schema The schema name OPTIONAL
  874. * @return string|null
  875. */
  876. protected function _getQuotedSchema($schema = null)
  877. {
  878. if ($schema === null) {
  879. return null;
  880. }
  881. return $this->_adapter->quoteIdentifier($schema, true) . '.';
  882. }
  883. /**
  884. * Return a quoted table name
  885. *
  886. * @param string $tableName The table name
  887. * @param string $correlationName The correlation name OPTIONAL
  888. * @return string
  889. */
  890. protected function _getQuotedTable($tableName, $correlationName = null)
  891. {
  892. return $this->_adapter->quoteTableAs($tableName, $correlationName, true);
  893. }
  894. /**
  895. * Render DISTINCT clause
  896. *
  897. * @param string $sql SQL query
  898. * @return string
  899. */
  900. protected function _renderDistinct($sql)
  901. {
  902. if ($this->_parts[self::DISTINCT]) {
  903. $sql .= ' ' . self::SQL_DISTINCT;
  904. }
  905. return $sql;
  906. }
  907. /**
  908. * Render DISTINCT clause
  909. *
  910. * @param string $sql SQL query
  911. * @return string|null
  912. */
  913. protected function _renderColumns($sql)
  914. {
  915. if (!count($this->_parts[self::COLUMNS])) {
  916. return null;
  917. }
  918. $columns = array();
  919. foreach ($this->_parts[self::COLUMNS] as $columnEntry) {
  920. list($correlationName, $column, $alias) = $columnEntry;
  921. if ($column instanceof Zend_Db_Expr) {
  922. $columns[] = $this->_adapter->quoteColumnAs($column, $alias, true);
  923. } else {
  924. if ($column == self::SQL_WILDCARD) {
  925. $column = new Zend_Db_Expr(self::SQL_WILDCARD);
  926. $alias = null;
  927. }
  928. if (empty($correlationName)) {
  929. $columns[] = $this->_adapter->quoteColumnAs($column, $alias, true);
  930. } else {
  931. $columns[] = $this->_adapter->quoteColumnAs(array($correlationName, $column), $alias, true);
  932. }
  933. }
  934. }
  935. return $sql .= ' ' . implode(', ', $columns);
  936. }
  937. /**
  938. * Render FROM clause
  939. *
  940. * @param string $sql SQL query
  941. * @return string
  942. */
  943. protected function _renderFrom($sql)
  944. {
  945. /*
  946. * If no table specified, use RDBMS-dependent solution
  947. * for table-less query. e.g. DUAL in Oracle.
  948. */
  949. if (empty($this->_parts[self::FROM])) {
  950. $this->_parts[self::FROM] = $this->_getDummyTable();
  951. }
  952. $from = array();
  953. foreach ($this->_parts[self::FROM] as $correlationName => $table) {
  954. $tmp = '';
  955. // Add join clause (if applicable)
  956. if (! empty($from)) {
  957. $tmp .= ' ' . strtoupper($table['joinType']) . ' ';
  958. }
  959. $tmp .= $this->_getQuotedSchema($table['schema']);
  960. $tmp .= $this->_getQuotedTable($table['tableName'], $correlationName);
  961. // Add join conditions (if applicable)
  962. if (!empty($from) && ! empty($table['joinCondition'])) {
  963. $tmp .= ' ' . self::SQL_ON . ' ' . $table['joinCondition'];
  964. }
  965. // Add the table name and condition add to the list
  966. $from[] = $tmp;
  967. }
  968. // Add the list of all joins
  969. if (!empty($from)) {
  970. $sql .= ' ' . self::SQL_FROM . ' ' . implode("\n", $from);
  971. }
  972. return $sql;
  973. }
  974. /**
  975. * Render UNION query
  976. *
  977. * @param string $sql SQL query
  978. * @return string
  979. */
  980. protected function _renderUnion($sql)
  981. {
  982. if ($this->_parts[self::UNION]) {
  983. $parts = count($this->_parts[self::UNION]);
  984. foreach ($this->_parts[self::UNION] as $cnt => $union) {
  985. list($target, $type) = $union;
  986. if ($target instanceof Zend_Db_Select) {
  987. $target = $target->assemble();
  988. }
  989. $sql .= $target;
  990. if ($cnt < $parts - 1) {
  991. $sql .= ' ' . $type . ' ';
  992. }
  993. }
  994. }
  995. return $sql;
  996. }
  997. /**
  998. * Render WHERE clause
  999. *
  1000. * @param string $sql SQL query
  1001. * @return string
  1002. */
  1003. protected function _renderWhere($sql)
  1004. {
  1005. if ($this->_parts[self::FROM] && $this->_parts[self::WHERE]) {
  1006. $sql .= ' ' . self::SQL_WHERE . ' ' . implode(' ', $this->_parts[self::WHERE]);
  1007. }
  1008. return $sql;
  1009. }
  1010. /**
  1011. * Render GROUP clause
  1012. *
  1013. * @param string $sql SQL query
  1014. * @return string
  1015. */
  1016. protected function _renderGroup($sql)
  1017. {
  1018. if ($this->_parts[self::FROM] && $this->_parts[self::GROUP]) {
  1019. $group = array();
  1020. foreach ($this->_parts[self::GROUP] as $term) {
  1021. $group[] = $this->_adapter->quoteIdentifier($term, true);
  1022. }
  1023. $sql .= ' ' . self::SQL_GROUP_BY . ' ' . implode(",\n\t", $group);
  1024. }
  1025. return $sql;
  1026. }
  1027. /**
  1028. * Render HAVING clause
  1029. *
  1030. * @param string $sql SQL query
  1031. * @return string
  1032. */
  1033. protected function _renderHaving($sql)
  1034. {
  1035. if ($this->_parts[self::FROM] && $this->_parts[self::HAVING]) {
  1036. $sql .= ' ' . self::SQL_HAVING . ' ' . implode(' ', $this->_parts[self::HAVING]);
  1037. }
  1038. return $sql;
  1039. }
  1040. /**
  1041. * Render ORDER clause
  1042. *
  1043. * @param string $sql SQL query
  1044. * @return string
  1045. */
  1046. protected function _renderOrder($sql)
  1047. {
  1048. if ($this->_parts[self::ORDER]) {
  1049. $order = array();
  1050. foreach ($this->_parts[self::ORDER] as $term) {
  1051. if (is_array($term)) {
  1052. $order[] = $this->_adapter->quoteIdentifier($term[0], true) . ' ' . $term[1];
  1053. } else {
  1054. $order[] = $this->_adapter->quoteIdentifier($term, true);
  1055. }
  1056. }
  1057. $sql .= ' ' . self::SQL_ORDER_BY . ' ' . implode(', ', $order);
  1058. }
  1059. return $sql;
  1060. }
  1061. /**
  1062. * Render LIMIT OFFSET clause
  1063. *
  1064. * @param string $sql SQL query
  1065. * @return string
  1066. */
  1067. protected function _renderLimitoffset($sql)
  1068. {
  1069. $count = 0;
  1070. $offset = 0;
  1071. if (!empty($this->_parts[self::LIMIT_OFFSET])) {
  1072. $offset = (int) $this->_parts[self::LIMIT_OFFSET];
  1073. // This should reduce to the max integer PHP can support
  1074. $count = intval(9223372036854775807);
  1075. }
  1076. if (!empty($this->_parts[self::LIMIT_COUNT])) {
  1077. $count = (int) $this->_parts[self::LIMIT_COUNT];
  1078. }
  1079. /*
  1080. * Add limits clause
  1081. */
  1082. if ($count > 0) {
  1083. $sql = trim($this->_adapter->limit($sql, $count, $offset));
  1084. }
  1085. return $sql;
  1086. }
  1087. /**
  1088. * Render FOR UPDATE clause
  1089. *
  1090. * @param string $sql SQL query
  1091. * @return string
  1092. */
  1093. protected function _renderForupdate($sql)
  1094. {
  1095. if ($this->_parts[self::FOR_UPDATE]) {
  1096. $sql .= ' ' . self::SQL_FOR_UPDATE;
  1097. }
  1098. return $sql;
  1099. }
  1100. /**
  1101. * Turn magic function calls into non-magic function calls
  1102. * for joinUsing syntax
  1103. *
  1104. * @param string $method
  1105. * @param array $args OPTIONAL Zend_Db_Table_Select query modifier
  1106. * @return Zend_Db_Select
  1107. * @throws Zend_Db_Select_Exception If an invalid method is called.
  1108. */
  1109. public function __call($method, array $args)
  1110. {
  1111. $matches = array();
  1112. /**
  1113. * Recognize methods for Has-Many cases:
  1114. * findParent<Class>()
  1115. * findParent<Class>By<Rule>()
  1116. * Use the non-greedy pattern repeat modifier e.g. \w+?
  1117. */
  1118. if (preg_match('/^join([a-zA-Z]*?)Using$/', $method, $matches)) {
  1119. $type = strtolower($matches[1]);
  1120. if ($type) {
  1121. $type .= ' join';
  1122. if (!in_array($type, self::$_joinTypes)) {
  1123. require_once 'Zend/Db/Select/Exception.php';
  1124. throw new Zend_Db_Select_Exception("Unrecognized method '$method()'");
  1125. }
  1126. if (in_array($type, array(self::CROSS_JOIN, self::NATURAL_JOIN))) {
  1127. require_once 'Zend/Db/Select/Exception.php';
  1128. throw new Zend_Db_Select_Exception("Cannot perform a joinUsing with method '$method()'");
  1129. }
  1130. } else {
  1131. $type = self::INNER_JOIN;
  1132. }
  1133. array_unshift($args, $type);
  1134. return call_user_func_array(array($this, '_joinUsing'), $args);
  1135. }
  1136. require_once 'Zend/Db/Select/Exception.php';
  1137. throw new Zend_Db_Select_Exception("Unrecognized method '$method()'");
  1138. }
  1139. /**
  1140. * Implements magic method.
  1141. *
  1142. * @return string This object as a SELECT string.
  1143. */
  1144. public function __toString()
  1145. {
  1146. try {
  1147. $sql = $this->assemble();
  1148. } catch (Exception $e) {
  1149. trigger_error($e->getMessage(), E_USER_WARNING);
  1150. $sql = '';
  1151. }
  1152. return (string)$sql;
  1153. }
  1154. }