Query.php 56 KB

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