Query.php 65 KB

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