Query.php 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Database;
  16. use Cake\Database\Exception;
  17. use Cake\Database\Expression\OrderByExpression;
  18. use Cake\Database\Expression\QueryExpression;
  19. use Cake\Database\Expression\ValuesExpression;
  20. use Cake\Database\Statement\CallbackStatement;
  21. use Cake\Database\ValueBinder;
  22. use IteratorAggregate;
  23. /**
  24. * This class represents a Relational database SQL Query. A query can be of
  25. * different types like select, update, insert and delete. Exposes the methods
  26. * for dynamically constructing each query part, execute it and transform it
  27. * to a specific SQL disalect.
  28. */
  29. class Query implements ExpressionInterface, IteratorAggregate {
  30. use TypeMapTrait;
  31. /**
  32. * Connection instance to be used to execute this query.
  33. *
  34. * @var \Cake\Database\Connection
  35. */
  36. protected $_connection;
  37. /**
  38. * Type of this query (select, insert, update, delete).
  39. *
  40. * @var string
  41. */
  42. protected $_type = 'select';
  43. /**
  44. * List of SQL parts that will be used to build this query.
  45. *
  46. * @var array
  47. */
  48. protected $_parts = [
  49. 'delete' => true,
  50. 'update' => [],
  51. 'set' => [],
  52. 'insert' => [],
  53. 'values' => [],
  54. 'select' => [],
  55. 'distinct' => false,
  56. 'modifier' => [],
  57. 'from' => [],
  58. 'join' => [],
  59. 'where' => null,
  60. 'group' => [],
  61. 'having' => null,
  62. 'order' => null,
  63. 'limit' => null,
  64. 'offset' => null,
  65. 'union' => [],
  66. 'epilog' => null
  67. ];
  68. /**
  69. * Indicates whether internal state of this query was changed, this is used to
  70. * discard internal cached objects such as the transformed query or the reference
  71. * to the executed statement.
  72. *
  73. * @var bool
  74. */
  75. protected $_dirty = false;
  76. /**
  77. * A list of callback functions to be called to alter each row from resulting
  78. * statement upon retrieval. Each one of the callback function will receive
  79. * the row array as first argument.
  80. *
  81. * @var array
  82. */
  83. protected $_resultDecorators = [];
  84. /**
  85. * Statement object resulting from executing this query.
  86. *
  87. * @var \Cake\Database\StatementInterface
  88. */
  89. protected $_iterator;
  90. /**
  91. * The object responsible for generating query placeholders and temporarily store values
  92. * associated to each of those.
  93. *
  94. * @var ValueBinder
  95. */
  96. protected $_valueBinder;
  97. /**
  98. * Instance of functions builder object used for generating arbitrary SQL functions.
  99. *
  100. * @var FunctionsBuilder
  101. */
  102. protected $_functionsBuilder;
  103. /**
  104. * Constructor.
  105. *
  106. * @param \Cake\Database\Connection $connection The connection
  107. * object to be used for transforming and executing this query
  108. */
  109. public function __construct($connection) {
  110. $this->connection($connection);
  111. }
  112. /**
  113. * Sets the connection instance to be used for executing and transforming this query
  114. * When called with a null argument, it will return the current connection instance.
  115. *
  116. * @param \Cake\Database\Connection $connection instance
  117. * @return $this|\Cake\Database\Connection
  118. */
  119. public function connection($connection = null) {
  120. if ($connection === null) {
  121. return $this->_connection;
  122. }
  123. $this->_dirty();
  124. $this->_connection = $connection;
  125. return $this;
  126. }
  127. /**
  128. * Compiles the SQL representation of this query and executes it using the
  129. * configured connection object. Returns the resulting statement object.
  130. *
  131. * Executing a query internally executes several steps, the first one is
  132. * letting the connection transform this object to fit its particular dialect,
  133. * this might result in generating a different Query object that will be the one
  134. * to actually be executed. Immediately after, literal values are passed to the
  135. * connection so they are bound to the query in a safe way. Finally, the resulting
  136. * statement is decorated with custom objects to execute callbacks for each row
  137. * retrieved if necessary.
  138. *
  139. * Resulting statement is traversable, so it can be used in any loop as you would
  140. * with an array.
  141. *
  142. * This method can be overridden in query subclasses to decorate behavior
  143. * around query execution.
  144. *
  145. * @return \Cake\Database\StatementInterface
  146. */
  147. public function execute() {
  148. $statement = $this->_connection->run($this);
  149. return $this->_iterator = $this->_decorateStatement($statement);
  150. }
  151. /**
  152. * Returns the SQL representation of this object.
  153. *
  154. * This function will compile this query to make it compatible
  155. * with the SQL dialect that is used by the connection, This process might
  156. * add, remove or alter any query part or internal expression to make it
  157. * executable in the target platform.
  158. *
  159. * The resulting query may have placeholders that will be replaced with the actual
  160. * values when the query is executed, hence it is most suitable to use with
  161. * prepared statements.
  162. *
  163. * @param ValueBinder $generator A placeholder object that will hold
  164. * associated values for expressions
  165. * @return string
  166. */
  167. public function sql(ValueBinder $generator = null) {
  168. $sql = '';
  169. if (!$generator) {
  170. $generator = $this->valueBinder();
  171. $generator->resetCount();
  172. }
  173. return $this->connection()->compileQuery($this, $generator);
  174. }
  175. /**
  176. * Will iterate over every specified part. Traversing functions can aggregate
  177. * results using variables in the closure or instance variables. This function
  178. * is commonly used as a way for traversing all query parts that
  179. * are going to be used for constructing a query.
  180. *
  181. * The callback will receive 2 parameters, the first one is the value of the query
  182. * part that is being iterated and the second the name of such part.
  183. *
  184. * ## Example:
  185. * {{{
  186. * $query->select(['title'])->from('articles')->traverse(function($value, $clause) {
  187. * if ($clause === 'select') {
  188. * var_dump($value);
  189. * }
  190. * }, ['select', 'from']);
  191. * }}}
  192. *
  193. * @param callable $visitor a function or callable to be executed for each part
  194. * @param array $parts the query clasuses to traverse
  195. * @return $this
  196. */
  197. public function traverse(callable $visitor, array $parts = []) {
  198. $parts = $parts ?: array_keys($this->_parts);
  199. foreach ($parts as $name) {
  200. $visitor($this->_parts[$name], $name);
  201. }
  202. return $this;
  203. }
  204. /**
  205. * Adds new fields to be returned by a SELECT statement when this query is
  206. * executed. Fields can be passed as an array of strings, array of expression
  207. * objects, a single expression or a single string.
  208. *
  209. * If an array is passed, keys will be used to alias fields using the value as the
  210. * real field to be aliased. It is possible to alias strings, Expression objects or
  211. * even other Query objects.
  212. *
  213. * By default this function will append any passed argument to the list of fields
  214. * to be selected, unless the second argument is set to true.
  215. *
  216. * ##Examples:
  217. *
  218. * {{{
  219. * $query->select(['id', 'title']); // Produces SELECT id, title
  220. * $query->select(['author' => 'author_id']); // Appends author: SELECT id, title, author_id as author
  221. * $query->select('id', true); // Resets the list: SELECT id
  222. * $query->select(['total' => $countQuery]); // SELECT id, (SELECT ...) AS total
  223. * }}}
  224. *
  225. * @param array|ExpressionInterface|string $fields fields to be added to the list
  226. * @param bool $overwrite whether to reset fields with passed list or not
  227. * @return $this
  228. */
  229. public function select($fields = [], $overwrite = false) {
  230. if (is_callable($fields)) {
  231. $fields = $fields($this);
  232. }
  233. if (!is_array($fields)) {
  234. $fields = [$fields];
  235. }
  236. if ($overwrite) {
  237. $this->_parts['select'] = $fields;
  238. } else {
  239. $this->_parts['select'] = array_merge($this->_parts['select'], $fields);
  240. }
  241. $this->_dirty();
  242. $this->_type = 'select';
  243. return $this;
  244. }
  245. /**
  246. * Adds a DISTINCT clause to the query to remove duplicates from the result set.
  247. * This clause can only be used for select statements.
  248. *
  249. * If you wish to filter duplicates based of those rows sharing a particular field
  250. * or set of fields, you may pass an array of fields to filter on. Beware that
  251. * this option might not be fully supported in all database systems.
  252. *
  253. * ##Examples:
  254. *
  255. * {{{
  256. * // Filters products with the same name and city
  257. * $query->select(['name', 'city'])->from('products')->distinct();
  258. *
  259. * // Filters products in the same city
  260. * $query->distinct(['city']);
  261. *
  262. * // Filter products with the same name
  263. * $query->distinct(['name'], true);
  264. * }}}
  265. *
  266. * @param array|ExpressionInterface $on fields to be filtered on
  267. * @param bool $overwrite whether to reset fields with passed list or not
  268. * @return $this
  269. */
  270. public function distinct($on = [], $overwrite = false) {
  271. if ($on === []) {
  272. $on = true;
  273. }
  274. if (is_array($on)) {
  275. $merge = [];
  276. if (is_array($this->_parts['distinct'])) {
  277. $merge = $this->_parts['distinct'];
  278. }
  279. $on = ($overwrite) ? array_values($on) : array_merge($merge, array_values($on));
  280. }
  281. $this->_parts['distinct'] = $on;
  282. $this->_dirty();
  283. return $this;
  284. }
  285. /**
  286. * Adds a single or multiple SELECT modifiers to be used in the SELECT.
  287. *
  288. * By default this function will append any passed argument to the list of modifiers
  289. * to be applied, unless the second argument is set to true.
  290. *
  291. * ### Example:
  292. *
  293. * {{{
  294. * // Ignore cache query in MySQL
  295. * $query->select(['name', 'city'])->from('products')->modifier('SQL_NO_CACHE');
  296. * // It will produce the SQL: SELECT SQL_NO_CACHE name, city FROM products
  297. *
  298. * // Or with multiple modifiers
  299. * $query->select(['name', 'city'])->from('products')->modifier(['HIGH_PRIORITY', 'SQL_NO_CACHE']);
  300. * // It will produce the SQL: SELECT HIGH_PRIORITY SQL_NO_CACHE name, city FROM products
  301. * }}}
  302. *
  303. * @param array|ExpressionInterface|string $modifiers modifiers to be applied to the query
  304. * @param bool $overwrite whether to reset order with field list or not
  305. * @return $this
  306. */
  307. public function modifier($modifiers, $overwrite = false) {
  308. $this->_dirty();
  309. if ($overwrite) {
  310. $this->_parts['modifier'] = [];
  311. }
  312. $this->_parts['modifier'] = array_merge($this->_parts['modifier'], (array)$modifiers);
  313. return $this;
  314. }
  315. /**
  316. * Adds a single or multiple tables to be used in the FROM clause for this query.
  317. * Tables can be passed as an array of strings, array of expression
  318. * objects, a single expression or a single string.
  319. *
  320. * If an array is passed, keys will be used to alias tables using the value as the
  321. * real field to be aliased. It is possible to alias strings, ExpressionInterface objects or
  322. * even other Query objects.
  323. *
  324. * By default this function will append any passed argument to the list of tables
  325. * to be selected from, unless the second argument is set to true.
  326. *
  327. * This method can be used for select, update and delete statements.
  328. *
  329. * ##Examples:
  330. *
  331. * {{{
  332. * $query->from(['p' => 'posts']); // Produces FROM posts p
  333. * $query->from('authors'); // Appends authors: FROM posts p, authors
  334. * $query->select(['products'], true); // Resets the list: FROM products
  335. * $query->select(['sub' => $countQuery]); // FROM (SELECT ...) sub
  336. * }}}
  337. *
  338. * @param array|ExpressionInterface|string $tables tables to be added to the list
  339. * @param bool $overwrite whether to reset tables with passed list or not
  340. * @return $this
  341. */
  342. public function from($tables = [], $overwrite = false) {
  343. if (empty($tables)) {
  344. return $this->_parts['from'];
  345. }
  346. if (is_string($tables)) {
  347. $tables = [$tables];
  348. }
  349. if ($overwrite) {
  350. $this->_parts['from'] = $tables;
  351. } else {
  352. $this->_parts['from'] = array_merge($this->_parts['from'], $tables);
  353. }
  354. $this->_dirty();
  355. return $this;
  356. }
  357. /**
  358. * Adds a single or multiple tables to be used as JOIN clauses this query.
  359. * Tables can be passed as an array of strings, an array describing the
  360. * join parts, an array with multiple join descriptions, or a single string.
  361. *
  362. * By default this function will append any passed argument to the list of tables
  363. * to be joined, unless the third argument is set to true.
  364. *
  365. * When no join type is specified an INNER JOIN is used by default:
  366. * ``$query->join(['authors'])`` Will produce INNER JOIN authors ON (1 = 1)
  367. *
  368. * It is also possible to alias joins using the array key:
  369. * ``$query->join(['a' => 'authors'])`` Will produce INNER JOIN authors a ON (1 = 1)
  370. *
  371. * A join can be fully described and aliased using the array notation:
  372. *
  373. * {{{
  374. * $query->join([
  375. * 'a' => [
  376. * 'table' => 'authors',
  377. * 'type' => 'LEFT',
  378. * 'conditions' => 'a.id = b.author_id'
  379. * ]
  380. * ]);
  381. * // Produces LEFT JOIN authors a ON (a.id = b.author_id)
  382. * }}}
  383. *
  384. * You can even specify multiple joins in an array, including the full description:
  385. *
  386. * {{{
  387. * $query->join([
  388. * 'a' => [
  389. * 'table' => 'authors',
  390. * 'type' => 'LEFT',
  391. * 'conditions' => 'a.id = b.author_id'
  392. * ],
  393. * 'p' => [
  394. * 'table' => 'products',
  395. * 'type' => 'INNER',
  396. * 'conditions' => 'a.owner_id = p.id
  397. * ]
  398. * ]);
  399. * // LEFT JOIN authors a ON (a.id = b.author_id)
  400. * // INNER JOIN products p (a.owner_id = p.id)
  401. * }}}
  402. *
  403. * ## Using conditions and types
  404. *
  405. * Conditions can be expressed, as in the examples above, using a string for comparing
  406. * columns, or string with already quoted literal values. Additionally it is
  407. * possible to using conditions expressed in arrays or expression objects.
  408. *
  409. * When using arrays for expressing conditions, it is often desirable to convert
  410. * the literal values to the correct database representation. This is achieved
  411. * using the second parameter of this function.
  412. *
  413. * {{{
  414. * $query->join(['a' => [
  415. * 'table' => 'articles',
  416. * 'conditions' => [
  417. * 'a.posted >=' => new DateTime('-3 days'),
  418. * 'a.published' => true
  419. * 'a.author_id = authors.id'
  420. * ]
  421. * ]], ['a.posted' => 'datetime', 'a.published' => 'boolean'])
  422. * }}}
  423. *
  424. * ## Overwriting joins
  425. *
  426. * When creating aliased joins using the array notation, you can override
  427. * previous join definitions by using the same alias in consequent
  428. * calls to this function or you can replace all previously defined joins
  429. * with another list if the third parameter for this function is set to true.
  430. *
  431. * {{{
  432. * $query->join(['alias' => 'table']); // joins table with as alias
  433. * $query->join(['alias' => 'another_table']); // joins another_table with as alias
  434. * $query->join(['something' => 'different_table'], [], true); // resets joins list
  435. * }}}
  436. *
  437. * @param array|string $tables list of tables to be joined in the query
  438. * @param array $types associative array of type names used to bind values to query
  439. * @param bool $overwrite whether to reset joins with passed list or not
  440. * @see \Cake\Database\Type
  441. * @return $this
  442. */
  443. public function join($tables = null, $types = [], $overwrite = false) {
  444. if ($tables === null) {
  445. return $this->_parts['join'];
  446. }
  447. if (is_string($tables) || isset($tables['table'])) {
  448. $tables = [$tables];
  449. }
  450. $joins = [];
  451. $i = count($this->_parts['join']);
  452. foreach ($tables as $alias => $t) {
  453. if (!is_array($t)) {
  454. $t = ['table' => $t, 'conditions' => $this->newExpr()];
  455. }
  456. if (is_callable($t['conditions'])) {
  457. $t['conditions'] = $t['conditions']($this->newExpr(), $this);
  458. }
  459. if (!($t['conditions'] instanceof ExpressionInterface)) {
  460. $t['conditions'] = $this->newExpr()->add($t['conditions'], $types);
  461. }
  462. $alias = is_string($alias) ? $alias : null;
  463. $joins[$alias ?: $i++] = $t + ['type' => 'INNER', 'alias' => $alias];
  464. }
  465. if ($overwrite) {
  466. $this->_parts['join'] = $joins;
  467. } else {
  468. $this->_parts['join'] = array_merge($this->_parts['join'], $joins);
  469. }
  470. $this->_dirty();
  471. return $this;
  472. }
  473. /**
  474. * Adds a single LEFT JOIN clause to the query.
  475. *
  476. * {{{
  477. * // LEFT JOIN authors ON posts.author_id' = authors.id
  478. * $query->leftJoin('authors', ['posts.author_id' = authors.id']);
  479. * }}}
  480. *
  481. * You can pass an array in the first parameter if you need to alias
  482. * the table for the join:
  483. *
  484. * {{{
  485. * // LEFT JOIN authors a ON posts.author_id' = a.id
  486. * $query->leftJoin(['a' => 'authors'], ['posts.author_id' = 'a.id']);
  487. * }}}
  488. *
  489. * @param string|array $table The table to join with
  490. * @param string|array|\Cake\Database\ExpressionInterface $conditions The conditions
  491. * to use for joining.
  492. * @param array $types a list of types associated to the conditions used for converting
  493. * values to the corresponding database representation.
  494. * @return $this
  495. */
  496. public function leftJoin($table, $conditions = [], $types = []) {
  497. return $this->join($this->_makeJoin($table, $conditions, 'LEFT'), $types);
  498. }
  499. /**
  500. * Adds a single RIGHT JOIN clause to the query.
  501. *
  502. * {{{
  503. * // RIGHT JOIN authors ON posts.author_id' = authors.id
  504. * $query->rightJoin('authors', ['posts.author_id' = authors.id']);
  505. * }}}
  506. *
  507. * You can pass an array in the first parameter if you need to alias
  508. * the table for the join:
  509. *
  510. * {{{
  511. * // RIGHT JOIN authors a ON posts.author_id' = a.id
  512. * $query->righJoin(['a' => 'authors'], ['posts.author_id' = 'a.id']);
  513. * }}}
  514. *
  515. * @param string|array $table The table to join with
  516. * @param string|array|\Cake\Database\ExpressionInterface $conditions The conditions
  517. * to use for joining.
  518. * @param array $types a list of types associated to the conditions used for converting
  519. * values to the corresponding database representation.
  520. * @return $this
  521. */
  522. public function rightJoin($table, $conditions = [], $types = []) {
  523. return $this->join($this->_makeJoin($table, $conditions, 'RIGHT'), $types);
  524. }
  525. /**
  526. * Adds a single INNER JOIN clause to the query.
  527. *
  528. * {{{
  529. * // INNER JOIN authors ON posts.author_id' = authors.id
  530. * $query->innerJoin('authors', ['posts.author_id' = authors.id']);
  531. * }}}
  532. *
  533. * You can pass an array in the first parameter if you need to alias
  534. * the table for the join:
  535. *
  536. * {{{
  537. * // INNER JOIN authors a ON posts.author_id' = a.id
  538. * $query->innerJoin(['a' => 'authors'], ['posts.author_id' = 'a.id']);
  539. * }}}
  540. *
  541. * @param string|array $table The table to join with
  542. * @param string|array|\Cake\Database\ExpressionInterface $conditions The conditions
  543. * to use for joining.
  544. * @param array $types a list of types associated to the conditions used for converting
  545. * values to the corresponding database representation.
  546. * @return $this
  547. */
  548. public function innerJoin($table, $conditions = [], $types = []) {
  549. return $this->join($this->_makeJoin($table, $conditions, 'INNER'), $types);
  550. }
  551. /**
  552. * Returns an array that can be passed to the join method describing a single join clause
  553. *
  554. * @param string|array $table The table to join with
  555. * @param string|array|\Cake\Database\ExpressionInterface $conditions The conditions
  556. * to use for joining.
  557. * @param string $type the join type to use
  558. * @return array
  559. */
  560. protected function _makeJoin($table, $conditions, $type) {
  561. $alias = $table;
  562. if (is_array($table)) {
  563. $alias = key($table);
  564. $table = current($table);
  565. }
  566. return [
  567. $alias => [
  568. 'table' => $table,
  569. 'conditions' => $conditions,
  570. 'type' => $type
  571. ]
  572. ];
  573. }
  574. /**
  575. * Adds a condition or set of conditions to be used in the WHERE clause for this
  576. * query. Conditions can be expressed as an array of fields as keys with
  577. * comparison operators in it, the values for the array will be used for comparing
  578. * the field to such literal. Finally, conditions can be expressed as a single
  579. * string or an array of strings.
  580. *
  581. * When using arrays, each entry will be joined to the rest of the conditions using
  582. * an AND operator. Consecutive calls to this function will also join the new
  583. * conditions specified using the AND operator. Additionally, values can be
  584. * expressed using expression objects which can include other query objects.
  585. *
  586. * Any conditions created with this methods can be used with any SELECT, UPDATE
  587. * and DELETE type of queries.
  588. *
  589. * ## Conditions using operators:
  590. *
  591. * {{{
  592. * $query->where([
  593. * 'posted >=' => new DateTime('3 days ago'),
  594. * 'title LIKE' => 'Hello W%',
  595. * 'author_id' => 1,
  596. * ], ['posted' => 'datetime']);
  597. * }}}
  598. *
  599. * The previous example produces:
  600. *
  601. * ``WHERE posted >= 2012-01-27 AND title LIKE 'Hello W%' AND author_id = 1``
  602. *
  603. * Second parameter is used to specify what type is expected for each passed
  604. * key. Valid types can be used from the mapped with Database\Type class.
  605. *
  606. * ## Nesting conditions with conjunctions:
  607. *
  608. * {{{
  609. * $query->where([
  610. * 'author_id !=' => 1,
  611. * 'OR' => ['published' => true, 'posted <' => new DateTime('now')],
  612. * 'NOT' => ['title' => 'Hello']
  613. * ], ['published' => boolean, 'posted' => 'datetime']
  614. * }}}
  615. *
  616. * The previous example produces:
  617. *
  618. * ``WHERE author_id = 1 AND (published = 1 OR posted < '2012-02-01') AND NOT (title = 'Hello')``
  619. *
  620. * You can nest conditions using conjunctions as much as you like. Sometimes, you
  621. * may want to define 2 different options for the same key, in that case, you can
  622. * wrap each condition inside a new array:
  623. *
  624. * ``$query->where(['OR' => [['published' => false], ['published' => true]])``
  625. *
  626. * Keep in mind that every time you call where() with the third param set to false
  627. * (default), it will join the passed conditions to the previous stored list using
  628. * the AND operator. Also, using the same array key twice in consecutive calls to
  629. * this method will not override the previous value.
  630. *
  631. * ## Using expressions objects:
  632. *
  633. * {{{
  634. * $exp = $query->newExpr()->add(['id !=' => 100, 'author_id' != 1])->type('OR');
  635. * $query->where(['published' => true], ['published' => 'boolean'])->where($exp);
  636. * }}}
  637. *
  638. * The previous example produces:
  639. *
  640. * ``WHERE (id != 100 OR author_id != 1) AND published = 1``
  641. *
  642. * Other Query objects that be used as conditions for any field.
  643. *
  644. * ## Adding conditions in multiple steps:
  645. *
  646. * You can use callable functions to construct complex expressions, functions
  647. * receive as first argument a new QueryExpression object and this query instance
  648. * as second argument. Functions must return an expression object, that will be
  649. * added the list of conditions for the query using th AND operator.
  650. *
  651. * {{{
  652. * $query
  653. * ->where(['title !=' => 'Hello World'])
  654. * ->where(function($exp, $query) {
  655. * $or = $exp->or_(['id' => 1]);
  656. * $and = $exp->and_(['id >' => 2, 'id <' => 10]);
  657. * return $or->add($and);
  658. * });
  659. * }}}
  660. *
  661. * * The previous example produces:
  662. *
  663. * ``WHERE title != 'Hello World' AND (id = 1 OR (id > 2 AND id < 10))``
  664. *
  665. * ## Conditions as strings:
  666. *
  667. * {{{
  668. * $query->where(['articles.author_id = authors.id', 'modified IS NULL']);
  669. * }}}
  670. *
  671. * The previous example produces:
  672. *
  673. * ``WHERE articles.author_id = authors.id AND modified IS NULL``
  674. *
  675. * Please note that when using the array notation or the expression objects, all
  676. * values will be correctly quoted and transformed to the correspondent database
  677. * data type automatically for you, thus securing your application from SQL injections.
  678. * If you use string conditions make sure that your values are correctly quoted.
  679. * The safest thing you can do is to never use string conditions.
  680. *
  681. * @param string|array|ExpressionInterface|callback $conditions The conditions to filter on.
  682. * @param array $types associative array of type names used to bind values to query
  683. * @param bool $overwrite whether to reset conditions with passed list or not
  684. * @see \Cake\Database\Type
  685. * @see \Cake\Database\QueryExpression
  686. * @return $this
  687. */
  688. public function where($conditions = null, $types = [], $overwrite = false) {
  689. if ($overwrite) {
  690. $this->_parts['where'] = $this->newExpr();
  691. }
  692. $this->_conjugate('where', $conditions, 'AND', $types);
  693. return $this;
  694. }
  695. /**
  696. * Connects any previously defined set of conditions to the provided list
  697. * using the AND operator. This function accepts the conditions list in the same
  698. * format as the method `where` does, hence you can use arrays, expression objects
  699. * callback functions or strings.
  700. *
  701. * It is important to notice that when calling this function, any previous set
  702. * of conditions defined for this query will be treated as a single argument for
  703. * the AND operator. This function will not only operate the most recently defined
  704. * condition, but all the conditions as a whole.
  705. *
  706. * When using an array for defining conditions, creating constraints form each
  707. * array entry will use the same logic as with the `where()` function. This means
  708. * that each array entry will be joined to the other using the AND operator, unless
  709. * you nest the conditions in the array using other operator.
  710. *
  711. * ##Examples:
  712. *
  713. * {{{
  714. * $query->where(['title' => 'Hello World')->andWhere(['author_id' => 1]);
  715. * }}}
  716. *
  717. * Will produce:
  718. *
  719. * ``WHERE title = 'Hello World' AND author_id = 1``
  720. *
  721. * {{{
  722. * $query
  723. * ->where(['OR' => ['published' => false, 'published is NULL']])
  724. * ->andWhere(['author_id' => 1, 'comments_count >' => 10])
  725. * }}}
  726. *
  727. * Produces:
  728. *
  729. * ``WHERE (published = 0 OR published IS NULL) AND author_id = 1 AND comments_count > 10``
  730. *
  731. * {{{
  732. * $query
  733. * ->where(['title' => 'Foo'])
  734. * ->andWhere(function($exp, $query) {
  735. * return $exp
  736. * ->add(['author_id' => 1])
  737. * ->or_(['author_id' => 2]);
  738. * });
  739. * }}}
  740. *
  741. * Generates the following conditions:
  742. *
  743. * ``WHERE (title = 'Foo') AND (author_id = 1 OR author_id = 2)``
  744. *
  745. * @param string|array|ExpressionInterface|callback $conditions The conditions to add with AND.
  746. * @param array $types associative array of type names used to bind values to query
  747. * @see \Cake\Database\Query::where()
  748. * @see \Cake\Database\Type
  749. * @return $this
  750. */
  751. public function andWhere($conditions, $types = []) {
  752. $this->_conjugate('where', $conditions, 'AND', $types);
  753. return $this;
  754. }
  755. /**
  756. * Connects any previously defined set of conditions to the provided list
  757. * using the OR operator. This function accepts the conditions list in the same
  758. * format as the method `where` does, hence you can use arrays, expression objects
  759. * callback functions or strings.
  760. *
  761. * It is important to notice that when calling this function, any previous set
  762. * of conditions defined for this query will be treated as a single argument for
  763. * the OR operator. This function will not only operate the most recently defined
  764. * condition, but all the conditions as a whole.
  765. *
  766. * When using an array for defining conditions, creating constraints form each
  767. * array entry will use the same logic as with the `where()` function. This means
  768. * that each array entry will be joined to the other using the OR operator, unless
  769. * you nest the conditions in the array using other operator.
  770. *
  771. * ##Examples:
  772. *
  773. * {{{
  774. * $query->where(['title' => 'Hello World')->orWhere(['title' => 'Foo']);
  775. * }}}
  776. *
  777. * Will produce:
  778. *
  779. * ``WHERE title = 'Hello World' OR title = 'Foo'``
  780. *
  781. * {{{
  782. * $query
  783. * ->where(['OR' => ['published' => false, 'published is NULL']])
  784. * ->orWhere(['author_id' => 1, 'comments_count >' => 10])
  785. * }}}
  786. *
  787. * Produces:
  788. *
  789. * ``WHERE (published = 0 OR published IS NULL) OR (author_id = 1 AND comments_count > 10)``
  790. *
  791. * {{{
  792. * $query
  793. * ->where(['title' => 'Foo'])
  794. * ->orWhere(function($exp, $query) {
  795. * return $exp
  796. * ->add(['author_id' => 1])
  797. * ->or_(['author_id' => 2]);
  798. * });
  799. * }}}
  800. *
  801. * Generates the following conditions:
  802. *
  803. * ``WHERE (title = 'Foo') OR (author_id = 1 OR author_id = 2)``
  804. *
  805. * @param string|array|ExpressionInterface|callback $conditions The conditions to add with OR.
  806. * @param array $types associative array of type names used to bind values to query
  807. * @see \Cake\Database\Query::where()
  808. * @see \Cake\Database\Type
  809. * @return $this
  810. */
  811. public function orWhere($conditions, $types = []) {
  812. $this->_conjugate('where', $conditions, 'OR', $types);
  813. return $this;
  814. }
  815. /**
  816. * Adds a single or multiple fields to be used in the ORDER clause for this query.
  817. * Fields can be passed as an array of strings, array of expression
  818. * objects, a single expression or a single string.
  819. *
  820. * If an array is passed, keys will be used as the field itself and the value will
  821. * represent the order in which such field should be ordered. When called multiple
  822. * times with the same fields as key, the last order definition will prevail over
  823. * the others.
  824. *
  825. * By default this function will append any passed argument to the list of fields
  826. * to be selected, unless the second argument is set to true.
  827. *
  828. * ##Examples:
  829. *
  830. * {{{
  831. * $query->order(['title' => 'DESC', 'author_id' => 'ASC']);
  832. * }}}
  833. *
  834. * Produces:
  835. *
  836. * ``ORDER BY title DESC, author_id ASC``
  837. *
  838. * {{{
  839. * $query->order(['title' => 'DESC NULLS FIRST'])->order('author_id');
  840. * }}}
  841. *
  842. * Will generate:
  843. *
  844. * ``ORDER BY title DESC NULLS FIRST, author_id``
  845. *
  846. * {{{
  847. * $expression = $query->newExpr()->add(['id % 2 = 0']);
  848. * $query->order($expression)->order(['title' => 'ASC']);
  849. * }}}
  850. *
  851. * Will become:
  852. *
  853. * ``ORDER BY (id %2 = 0), title ASC``
  854. *
  855. * @param array|\Cake\Database\ExpressionInterface|string $fields fields to be added to the list
  856. * @param bool $overwrite whether to reset order with field list or not
  857. * @return $this
  858. */
  859. public function order($fields, $overwrite = false) {
  860. if ($overwrite) {
  861. $this->_parts['order'] = null;
  862. }
  863. if (!$fields) {
  864. return $this;
  865. }
  866. if (!$this->_parts['order']) {
  867. $this->_parts['order'] = new OrderByExpression;
  868. }
  869. $this->_conjugate('order', $fields, '', []);
  870. return $this;
  871. }
  872. /**
  873. * Adds a single or multiple fields to be used in the GROUP BY clause for this query.
  874. * Fields can be passed as an array of strings, array of expression
  875. * objects, a single expression or a single string.
  876. *
  877. * By default this function will append any passed argument to the list of fields
  878. * to be grouped, unless the second argument is set to true.
  879. *
  880. * ##Examples:
  881. *
  882. * {{{
  883. * // Produces GROUP BY id, title
  884. * $query->group(['id', 'title']);
  885. *
  886. * // Produces GROUP BY title
  887. * $query->group('title');
  888. * }}}
  889. *
  890. * @param array|ExpressionInterface|string $fields fields to be added to the list
  891. * @param bool $overwrite whether to reset fields with passed list or not
  892. * @return $this
  893. */
  894. public function group($fields, $overwrite = false) {
  895. if ($overwrite) {
  896. $this->_parts['group'] = [];
  897. }
  898. if (!is_array($fields)) {
  899. $fields = [$fields];
  900. }
  901. $this->_parts['group'] = array_merge($this->_parts['group'], array_values($fields));
  902. $this->_dirty();
  903. return $this;
  904. }
  905. /**
  906. * Adds a condition or set of conditions to be used in the HAVING clause for this
  907. * query. This method operates in exactly the same way as the method `where()`
  908. * does. Please refer to its documentation for an insight on how to using each
  909. * parameter.
  910. *
  911. * @param string|array|ExpressionInterface|callback $conditions The having conditions.
  912. * @param array $types associative array of type names used to bind values to query
  913. * @param bool $overwrite whether to reset conditions with passed list or not
  914. * @see \Cake\Database\Query::where()
  915. * @return $this
  916. */
  917. public function having($conditions = null, $types = [], $overwrite = false) {
  918. if ($overwrite) {
  919. $this->_parts['having'] = $this->newExpr();
  920. }
  921. $this->_conjugate('having', $conditions, 'AND', $types);
  922. return $this;
  923. }
  924. /**
  925. * Connects any previously defined set of conditions to the provided list
  926. * using the AND operator in the HAVING clause. This method operates in exactly
  927. * the same way as the method ``andWhere()`` does. Please refer to its
  928. * documentation for an insight on how to using each parameter.
  929. *
  930. * @param string|array|ExpressionInterface|callback $conditions The AND conditions for HAVING.
  931. * @param array $types associative array of type names used to bind values to query
  932. * @see \Cake\Database\Query::andWhere()
  933. * @return $this
  934. */
  935. public function andHaving($conditions, $types = []) {
  936. $this->_conjugate('having', $conditions, 'AND', $types);
  937. return $this;
  938. }
  939. /**
  940. * Connects any previously defined set of conditions to the provided list
  941. * using the OR operator in the HAVING clause. This method operates in exactly
  942. * the same way as the method ``orWhere()`` does. Please refer to its
  943. * documentation for an insight on how to using each parameter.
  944. *
  945. * @param string|array|ExpressionInterface|callback $conditions The OR conditions for HAVING.
  946. * @param array $types associative array of type names used to bind values to query.
  947. * @see \Cake\Database\Query::orWhere()
  948. * @return $this
  949. */
  950. public function orHaving($conditions, $types = []) {
  951. $this->_conjugate('having', $conditions, 'OR', $types);
  952. return $this;
  953. }
  954. /**
  955. * Set the page of results you want.
  956. *
  957. * This method provides an easier to use interface to set the limit + offset
  958. * in the record set you want as results. If empty the limit will default to
  959. * the existing limit clause, and if that too is empty, then `25` will be used.
  960. *
  961. * Pages should start at 1.
  962. *
  963. * @param int $num The page number you want.
  964. * @return $this
  965. */
  966. public function page($num) {
  967. $limit = $this->clause('limit');
  968. if ($limit === null) {
  969. $limit = 25;
  970. $this->limit($limit);
  971. }
  972. $offset = ($num - 1) * $limit;
  973. if (PHP_INT_MAX <= $offset) {
  974. $offset = PHP_INT_MAX;
  975. }
  976. $this->offset((int)$offset);
  977. return $this;
  978. }
  979. /**
  980. * Sets the number of records that should be retrieved from database,
  981. * accepts an integer or an expression object that evaluates to an integer.
  982. * In some databases, this operation might not be supported or will require
  983. * the query to be transformed in order to limit the result set size.
  984. *
  985. * ## Examples
  986. *
  987. * {{{
  988. * $query->limit(10) // generates LIMIT 10
  989. * $query->limit($query->newExpr()->add(['1 + 1'])); // LIMIT (1 + 1)
  990. * }}}
  991. *
  992. * @param int|ExpressionInterface $num number of records to be returned
  993. * @return $this
  994. */
  995. public function limit($num) {
  996. $this->_dirty();
  997. if ($num !== null && !is_object($num)) {
  998. $num = (int)$num;
  999. }
  1000. $this->_parts['limit'] = $num;
  1001. return $this;
  1002. }
  1003. /**
  1004. * Sets the number of records that should be skipped from the original result set
  1005. * This is commonly used for paginating large results. Accepts an integer or an
  1006. * expression object that evaluates to an integer.
  1007. *
  1008. * In some databases, this operation might not be supported or will require
  1009. * the query to be transformed in order to limit the result set size.
  1010. *
  1011. * ## Examples
  1012. *
  1013. * {{{
  1014. * $query->offset(10) // generates OFFSET 10
  1015. * $query->limit($query->newExpr()->add(['1 + 1'])); // OFFSET (1 + 1)
  1016. * }}}
  1017. *
  1018. * @param int|ExpressionInterface $num number of records to be skipped
  1019. * @return $this
  1020. */
  1021. public function offset($num) {
  1022. if ($num !== null && !is_object($num)) {
  1023. $num = (int)$num;
  1024. }
  1025. $this->_parts['offset'] = $num;
  1026. return $this;
  1027. }
  1028. /**
  1029. * Adds a complete query to be used in conjunction with an UNION operator with
  1030. * this query. This is used to combine the result set of this query with the one
  1031. * that will be returned by the passed query. You can add as many queries as you
  1032. * required by calling multiple times this method with different queries.
  1033. *
  1034. * By default, the UNION operator will remove duplicate rows, if you wish to include
  1035. * every row for all queries, use unionAll().
  1036. *
  1037. * ## Examples
  1038. *
  1039. * {{{
  1040. * $union = (new Query($conn))->select(['id', 'title'])->from(['a' => 'articles']);
  1041. * $query->select(['id', 'name'])->from(['d' => 'things'])->union($union);
  1042. * }}}
  1043. *
  1044. * Will produce:
  1045. *
  1046. * ``SELECT id, name FROM things d UNION SELECT id, title FROM articles a``
  1047. *
  1048. * @param string|Query $query full SQL query to be used in UNION operator
  1049. * @param bool $overwrite whether to reset the list of queries to be operated or not
  1050. * @return $this
  1051. */
  1052. public function union($query, $overwrite = false) {
  1053. if ($overwrite) {
  1054. $this->_parts['union'] = [];
  1055. }
  1056. $this->_parts['union'][] = [
  1057. 'all' => false,
  1058. 'query' => $query
  1059. ];
  1060. $this->_dirty();
  1061. return $this;
  1062. }
  1063. /**
  1064. * Adds a complete query to be used in conjunction with the UNION ALL operator with
  1065. * this query. This is used to combine the result set of this query with the one
  1066. * that will be returned by the passed query. You can add as many queries as you
  1067. * required by calling multiple times this method with different queries.
  1068. *
  1069. * Unlike UNION, UNION ALL will not remove duplicate rows.
  1070. *
  1071. * {{{
  1072. * $union = (new Query($conn))->select(['id', 'title'])->from(['a' => 'articles']);
  1073. * $query->select(['id', 'name'])->from(['d' => 'things'])->unionAll($union);
  1074. * }}}
  1075. *
  1076. * Will produce:
  1077. *
  1078. * ``SELECT id, name FROM things d UNION ALL SELECT id, title FROM articles a``
  1079. *
  1080. * @param string|Query $query full SQL query to be used in UNION operator
  1081. * @param bool $overwrite whether to reset the list of queries to be operated or not
  1082. * @return $this
  1083. */
  1084. public function unionAll($query, $overwrite = false) {
  1085. if ($overwrite) {
  1086. $this->_parts['union'] = [];
  1087. }
  1088. $this->_parts['union'][] = [
  1089. 'all' => true,
  1090. 'query' => $query
  1091. ];
  1092. $this->_dirty();
  1093. return $this;
  1094. }
  1095. /**
  1096. * Create an insert query.
  1097. *
  1098. * Note calling this method will reset any data previously set
  1099. * with Query::values().
  1100. *
  1101. * @param array $columns The columns to insert into.
  1102. * @param array $types A map between columns & their datatypes.
  1103. * @return $this
  1104. * @throws \RuntimeException When there are 0 columns.
  1105. */
  1106. public function insert(array $columns, array $types = []) {
  1107. if (empty($columns)) {
  1108. throw new \RuntimeException('At least 1 column is required to perform an insert.');
  1109. }
  1110. $this->_dirty();
  1111. $this->_type = 'insert';
  1112. $this->_parts['insert'][1] = $columns;
  1113. if (!$this->_parts['values']) {
  1114. $this->_parts['values'] = new ValuesExpression($columns, $this->typeMap()->types($types));
  1115. }
  1116. return $this;
  1117. }
  1118. /**
  1119. * Set the table name for insert queries.
  1120. *
  1121. * @param string $table The table name to insert into.
  1122. * @return $this
  1123. */
  1124. public function into($table) {
  1125. $this->_dirty();
  1126. $this->_type = 'insert';
  1127. $this->_parts['insert'][0] = $table;
  1128. return $this;
  1129. }
  1130. /**
  1131. * Set the values for an insert query.
  1132. *
  1133. * Multi inserts can be performed by calling values() more than one time,
  1134. * or by providing an array of value sets. Additionally $data can be a Query
  1135. * instance to insert data from another SELECT statement.
  1136. *
  1137. * @param array|Query $data The data to insert.
  1138. * @return $this
  1139. * @throws \Cake\Database\Exception if you try to set values before declaring columns.
  1140. * Or if you try to set values on non-insert queries.
  1141. */
  1142. public function values($data) {
  1143. if ($this->_type !== 'insert') {
  1144. throw new Exception(
  1145. 'You cannot add values before defining columns to use.'
  1146. );
  1147. }
  1148. if (empty($this->_parts['insert'])) {
  1149. throw new Exception(
  1150. 'You cannot add values before defining columns to use.'
  1151. );
  1152. }
  1153. $this->_dirty();
  1154. if ($data instanceof ValuesExpression) {
  1155. $this->_parts['values'] = $data;
  1156. return $this;
  1157. }
  1158. $this->_parts['values']->add($data);
  1159. return $this;
  1160. }
  1161. /**
  1162. * Create an update query.
  1163. *
  1164. * Can be combined with set() and where() methods to create update queries.
  1165. *
  1166. * @param string $table The table you want to update.
  1167. * @return $this
  1168. */
  1169. public function update($table) {
  1170. $this->_dirty();
  1171. $this->_type = 'update';
  1172. $this->_parts['update'][0] = $table;
  1173. return $this;
  1174. }
  1175. /**
  1176. * Set one or many fields to update.
  1177. *
  1178. * @param string|array|QueryExpression $key The column name or array of keys
  1179. * + values to set. This can also be a QueryExpression containing a SQL fragment.
  1180. * @param mixed $value The value to update $key to. Can be null if $key is an
  1181. * array or QueryExpression. When $key is an array, this parameter will be
  1182. * used as $types instead.
  1183. * @param array $types The column types to treat data as.
  1184. * @return $this
  1185. */
  1186. public function set($key, $value = null, $types = []) {
  1187. if (empty($this->_parts['set'])) {
  1188. $this->_parts['set'] = $this->newExpr()->type(',');
  1189. }
  1190. if (is_array($key) || $key instanceof ExpressionInterface) {
  1191. $types = (array)$value;
  1192. $this->_parts['set']->add($key, $types);
  1193. return $this;
  1194. }
  1195. if (is_string($types) && is_string($key)) {
  1196. $types = [$key => $types];
  1197. }
  1198. $this->_parts['set']->eq($key, $value, $types);
  1199. return $this;
  1200. }
  1201. /**
  1202. * Create a delete query.
  1203. *
  1204. * Can be combined with from(), where() and other methods to
  1205. * create delete queries with specific conditions.
  1206. *
  1207. * @param string $table The table to use when deleting. This
  1208. * @return $this
  1209. */
  1210. public function delete($table = null) {
  1211. $this->_dirty();
  1212. $this->_type = 'delete';
  1213. if ($table) {
  1214. $this->from($table);
  1215. }
  1216. return $this;
  1217. }
  1218. /**
  1219. * A string or expression that will be appended to the generated query
  1220. *
  1221. * ### Examples:
  1222. * {{{
  1223. * $query->select('id')->where(['author_id' => 1])->epilog('FOR UPDATE');
  1224. * $query
  1225. * ->insert('articles', ['title'])
  1226. * ->values(['author_id' => 1])
  1227. * ->epilog('RETURNING id');
  1228. * }}}
  1229. *
  1230. * @param string|\Cake\Database\QueryExpression $expression The expression to be appended
  1231. * @return $this
  1232. */
  1233. public function epilog($expression = null) {
  1234. $this->_dirty();
  1235. $this->_parts['epilog'] = $expression;
  1236. return $this;
  1237. }
  1238. /**
  1239. * Returns the type of this query (select, insert, update, delete)
  1240. *
  1241. * @return string
  1242. */
  1243. public function type() {
  1244. return $this->_type;
  1245. }
  1246. /**
  1247. * Returns a new QueryExpression object. This is a handy function when
  1248. * building complex queries using a fluent interface. You can also override
  1249. * this function in subclasses to use a more specialized QueryExpression class
  1250. * if required.
  1251. *
  1252. * You can optionally pass a single raw SQL string or an array or expressions in
  1253. * any format accepted by \Cake\Database\QueryExpression:
  1254. *
  1255. * {{{
  1256. *
  1257. * $expression = $query->newExpression(); // Returns an empty expression object
  1258. * $expression = $query->newExpression('Table.column = Table2.column'); // Return a raw SQL expression
  1259. * }}}
  1260. *
  1261. * @param mixed $rawExpression A string, array or anything you want wrapped in a expression object
  1262. * @return \Cake\Database\QueryExpression
  1263. */
  1264. public function newExpr($rawExpression = null) {
  1265. $expression = new QueryExpression([], $this->typeMap());
  1266. if ($rawExpression !== null) {
  1267. $expression->add($rawExpression);
  1268. }
  1269. return $expression;
  1270. }
  1271. /**
  1272. * Returns an instance of a functions builder object that can be used for
  1273. * generating arbitrary SQL functions.
  1274. *
  1275. * ### Example:
  1276. *
  1277. * {{{
  1278. * $query->func()->count('*');
  1279. * $query->func()->dateDiff(['2012-01-05', '2012-01-02'])
  1280. * }}}
  1281. *
  1282. * @return \Cake\Database\FunctionsBuilder
  1283. */
  1284. public function func() {
  1285. if (empty($this->_functionsBuilder)) {
  1286. $this->_functionsBuilder = new FunctionsBuilder;
  1287. }
  1288. return $this->_functionsBuilder;
  1289. }
  1290. /**
  1291. * Executes this query and returns a results iterator. This function is required
  1292. * for implementing the IteratorAggregate interface and allows the query to be
  1293. * iterated without having to call execute() manually, thus making it look like
  1294. * a result set instead of the query itself.
  1295. *
  1296. * @return \Iterator
  1297. */
  1298. public function getIterator() {
  1299. if (empty($this->_iterator) || $this->_dirty) {
  1300. $this->_iterator = $this->execute();
  1301. }
  1302. return $this->_iterator;
  1303. }
  1304. /**
  1305. * Returns any data that was stored in the specified clause. This is useful for
  1306. * modifying any internal part of the query and it is used by the SQL dialects
  1307. * to transform the query accordingly before it is executed. The valid clauses that
  1308. * can be retrieved are: delete, update, set, insert, values, select, distinct,
  1309. * from, join, set, where, group, having, order, limit, offset and union.
  1310. *
  1311. * The return value for each of those parts may vary. Some clauses use QueryExpression
  1312. * to internally store their state, some use arrays and others may use booleans or
  1313. * integers. This is summary of the return types for each clause.
  1314. *
  1315. * - update: string The name of the table to update
  1316. * - set: QueryExpression
  1317. * - insert: array, will return an array containing the table + columns.
  1318. * - values: ValuesExpression
  1319. * - select: array, will return empty array when no fields are set
  1320. * - distinct: boolean
  1321. * - from: array of tables
  1322. * - join: array
  1323. * - set: array
  1324. * - where: QueryExpression, returns null when not set
  1325. * - group: array
  1326. * - having: QueryExpression, returns null when not set
  1327. * - order: OrderByExpression, returns null when not set
  1328. * - limit: integer or QueryExpression, null when not set
  1329. * - offset: integer or QueryExpression, null when not set
  1330. * - union: array
  1331. *
  1332. * @param string $name name of the clause to be returned
  1333. * @return mixed
  1334. */
  1335. public function clause($name) {
  1336. return $this->_parts[$name];
  1337. }
  1338. /**
  1339. * Registers a callback to be executed for each result that is fetched from the
  1340. * result set, the callback function will receive as first parameter an array with
  1341. * the raw data from the database for every row that is fetched and must return the
  1342. * row with any possible modifications.
  1343. *
  1344. * Callbacks will be executed lazily, if only 3 rows are fetched for database it will
  1345. * called 3 times, event though there might be more rows to be fetched in the cursor.
  1346. *
  1347. * Callbacks are stacked in the order they are registered, if you wish to reset the stack
  1348. * the call this function with the second parameter set to true.
  1349. *
  1350. * If you wish to remove all decorators from the stack, set the first parameter
  1351. * to null and the second to true.
  1352. *
  1353. * ## Example
  1354. *
  1355. * {{{
  1356. * $query->decorateResults(function($row) {
  1357. * $row['order_total'] = $row['subtotal'] + ($row['subtotal'] * $row['tax']);
  1358. * return $row;
  1359. * });
  1360. * }}}
  1361. *
  1362. * @param null|callable $callback The callback to invoke when results are fetched.
  1363. * @param bool $overwrite Whether or not this should append or replace all existing decorators.
  1364. * @return $this
  1365. */
  1366. public function decorateResults($callback, $overwrite = false) {
  1367. if ($overwrite) {
  1368. $this->_resultDecorators = [];
  1369. }
  1370. if ($callback !== null) {
  1371. $this->_resultDecorators[] = $callback;
  1372. }
  1373. return $this;
  1374. }
  1375. /**
  1376. * This function works similar to the traverse() function, with the difference
  1377. * that it does a full depth traversal of the entire expression tree. This will execute
  1378. * the provided callback function for each ExpressionInterface object that is
  1379. * stored inside this query at any nesting depth in any part of the query.
  1380. *
  1381. * Callback will receive as first parameter the currently visited expression.
  1382. *
  1383. * @param callable $callback the function to be executed for each ExpressionInterface
  1384. * found inside this query.
  1385. * @return $this
  1386. */
  1387. public function traverseExpressions(callable $callback) {
  1388. $visitor = function($expression) use (&$visitor, $callback) {
  1389. if (is_array($expression)) {
  1390. foreach ($expression as $e) {
  1391. $visitor($e);
  1392. }
  1393. return;
  1394. }
  1395. if ($expression instanceof ExpressionInterface) {
  1396. $expression->traverse($visitor);
  1397. if (!($expression instanceof self)) {
  1398. $callback($expression);
  1399. }
  1400. }
  1401. };
  1402. return $this->traverse($visitor);
  1403. }
  1404. /**
  1405. * Associates a query placeholder to a value and a type.
  1406. *
  1407. * If type is expressed as "atype[]" (note braces) then it will cause the
  1408. * placeholder to be re-written dynamically so if the value is an array, it
  1409. * will create as many placeholders as values are in it. For example "string[]"
  1410. * will create several placeholders of type string.
  1411. *
  1412. * @param string|int $param placeholder to be replaced with quoted version
  1413. * of $value
  1414. * @param mixed $value The value to be bound
  1415. * @param string|int $type the mapped type name, used for casting when sending
  1416. * to database
  1417. * @return $this
  1418. */
  1419. public function bind($param, $value, $type = 'string') {
  1420. $this->valueBinder()->bind($param, $value, $type);
  1421. return $this;
  1422. }
  1423. /**
  1424. * Returns the currently used ValueBinder instance. If a value is passed,
  1425. * it will be set as the new instance to be used.
  1426. *
  1427. * A ValueBinder is responsible for generating query placeholders and temporarily
  1428. * associate values to those placeholders so that they can be passed correctly
  1429. * statement object.
  1430. *
  1431. * @param \Cake\Database\ValueBinder $binder new instance to be set. If no value is passed the
  1432. * default one will be returned
  1433. * @return $this|\Cake\Database\ValueBinder
  1434. */
  1435. public function valueBinder($binder = null) {
  1436. if ($binder === null) {
  1437. if ($this->_valueBinder === null) {
  1438. $this->_valueBinder = new ValueBinder;
  1439. }
  1440. return $this->_valueBinder;
  1441. }
  1442. $this->_valueBinder = $binder;
  1443. return $this;
  1444. }
  1445. /**
  1446. * Auxiliary function used to wrap the original statement from the driver with
  1447. * any registered callbacks.
  1448. *
  1449. * @param \Cake\Database\StatementInterface $statement to be decorated
  1450. * @return \Cake\Database\Statement\CallbackStatement
  1451. */
  1452. protected function _decorateStatement($statement) {
  1453. foreach ($this->_resultDecorators as $f) {
  1454. $statement = new CallbackStatement($statement, $this->connection()->driver(), $f);
  1455. }
  1456. return $statement;
  1457. }
  1458. /**
  1459. * Helper function used to build conditions by composing QueryExpression objects.
  1460. *
  1461. * @param string $part Name of the query part to append the new part to
  1462. * @param string|array|ExpressionInterface|callback $append Expression or builder function to append.
  1463. * @param string $conjunction type of conjunction to be used to operate part
  1464. * @param array $types associative array of type names used to bind values to query
  1465. * @return void
  1466. */
  1467. protected function _conjugate($part, $append, $conjunction, $types) {
  1468. $expression = $this->_parts[$part] ?: $this->newExpr();
  1469. if (is_callable($append)) {
  1470. $append = $append($this->newExpr(), $this);
  1471. }
  1472. if ($expression->type() === $conjunction) {
  1473. $expression->add($append, $types);
  1474. } else {
  1475. $expression = $this->newExpr()
  1476. ->type($conjunction)
  1477. ->add([$append, $expression], $types);
  1478. }
  1479. $this->_parts[$part] = $expression;
  1480. $this->_dirty();
  1481. }
  1482. /**
  1483. * Marks a query as dirty, removing any preprocessed information
  1484. * from in memory caching.
  1485. *
  1486. * @return void
  1487. */
  1488. protected function _dirty() {
  1489. $this->_dirty = true;
  1490. $this->_transformedQuery = null;
  1491. if ($this->_valueBinder) {
  1492. $this->valueBinder()->reset();
  1493. }
  1494. }
  1495. /**
  1496. * Returns string representation of this query (complete SQL statement).
  1497. *
  1498. * @return string
  1499. */
  1500. public function __toString() {
  1501. return $this->sql();
  1502. }
  1503. /**
  1504. * Returns an array that can be used to describe the internal state of this
  1505. * object.
  1506. *
  1507. * @return array
  1508. */
  1509. public function __debugInfo() {
  1510. return [
  1511. 'sql' => $this->sql(),
  1512. 'params' => $this->valueBinder()->bindings(),
  1513. 'defaultTypes' => $this->defaultTypes(),
  1514. 'decorators' => count($this->_resultDecorators),
  1515. 'executed' => $this->_iterator ? true : false
  1516. ];
  1517. }
  1518. }