Select.php 44 KB

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