Select.php 45 KB

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