Query.php 50 KB

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