Query.php 71 KB

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