Query.php 60 KB

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