Select.php 42 KB

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