Query.php 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110
  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 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\Datasource\ConnectionInterface $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\Datasource\ConnectionInterface $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\Datasource\ConnectionInterface|null $connection Connection instance
  161. * @return $this|\Cake\Datasource\ConnectionInterface
  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. $driver = $this->_connection->driver();
  194. $typeMap = $this->getSelectTypeMap();
  195. if ($typeMap->toArray() && $this->_typeCastAttached === false) {
  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::autoFields()` 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. * If you use string conditions make sure that your values are correctly quoted.
  799. * The safest thing you can do is to never use string conditions.
  800. *
  801. * @param string|array|\Cake\Database\ExpressionInterface|callable|null $conditions The conditions to filter on.
  802. * @param array $types associative array of type names used to bind values to query
  803. * @param bool $overwrite whether to reset conditions with passed list or not
  804. * @see \Cake\Database\Type
  805. * @see \Cake\Database\Expression\QueryExpression
  806. * @return $this
  807. */
  808. public function where($conditions = null, $types = [], $overwrite = false)
  809. {
  810. if ($overwrite) {
  811. $this->_parts['where'] = $this->newExpr();
  812. }
  813. $this->_conjugate('where', $conditions, 'AND', $types);
  814. return $this;
  815. }
  816. /**
  817. * Connects any previously defined set of conditions to the provided list
  818. * using the AND operator. This function accepts the conditions list in the same
  819. * format as the method `where` does, hence you can use arrays, expression objects
  820. * callback functions or strings.
  821. *
  822. * It is important to notice that when calling this function, any previous set
  823. * of conditions defined for this query will be treated as a single argument for
  824. * the AND operator. This function will not only operate the most recently defined
  825. * condition, but all the conditions as a whole.
  826. *
  827. * When using an array for defining conditions, creating constraints form each
  828. * array entry will use the same logic as with the `where()` function. This means
  829. * that each array entry will be joined to the other using the AND operator, unless
  830. * you nest the conditions in the array using other operator.
  831. *
  832. * ### Examples:
  833. *
  834. * ```
  835. * $query->where(['title' => 'Hello World')->andWhere(['author_id' => 1]);
  836. * ```
  837. *
  838. * Will produce:
  839. *
  840. * `WHERE title = 'Hello World' AND author_id = 1`
  841. *
  842. * ```
  843. * $query
  844. * ->where(['OR' => ['published' => false, 'published is NULL']])
  845. * ->andWhere(['author_id' => 1, 'comments_count >' => 10])
  846. * ```
  847. *
  848. * Produces:
  849. *
  850. * `WHERE (published = 0 OR published IS NULL) AND author_id = 1 AND comments_count > 10`
  851. *
  852. * ```
  853. * $query
  854. * ->where(['title' => 'Foo'])
  855. * ->andWhere(function ($exp, $query) {
  856. * return $exp
  857. * ->or_(['author_id' => 1])
  858. * ->add(['author_id' => 2]);
  859. * });
  860. * ```
  861. *
  862. * Generates the following conditions:
  863. *
  864. * `WHERE (title = 'Foo') AND (author_id = 1 OR author_id = 2)`
  865. *
  866. * @param string|array|\Cake\Database\ExpressionInterface|callable $conditions The conditions to add with AND.
  867. * @param array $types associative array of type names used to bind values to query
  868. * @see \Cake\Database\Query::where()
  869. * @see \Cake\Database\Type
  870. * @return $this
  871. */
  872. public function andWhere($conditions, $types = [])
  873. {
  874. $this->_conjugate('where', $conditions, 'AND', $types);
  875. return $this;
  876. }
  877. /**
  878. * Connects any previously defined set of conditions to the provided list
  879. * using the OR operator. This function accepts the conditions list in the same
  880. * format as the method `where` does, hence you can use arrays, expression objects
  881. * callback functions or strings.
  882. *
  883. * It is important to notice that when calling this function, any previous set
  884. * of conditions defined for this query will be treated as a single argument for
  885. * the OR operator. This function will not only operate the most recently defined
  886. * condition, but all the conditions as a whole.
  887. *
  888. * When using an array for defining conditions, creating constraints form each
  889. * array entry will use the same logic as with the `where()` function. This means
  890. * that each array entry will be joined to the other using the OR operator, unless
  891. * you nest the conditions in the array using other operator.
  892. *
  893. * ### Examples:
  894. *
  895. * ```
  896. * $query->where(['title' => 'Hello World')->orWhere(['title' => 'Foo']);
  897. * ```
  898. *
  899. * Will produce:
  900. *
  901. * `WHERE title = 'Hello World' OR title = 'Foo'`
  902. *
  903. * ```
  904. * $query
  905. * ->where(['OR' => ['published' => false, 'published is NULL']])
  906. * ->orWhere(['author_id' => 1, 'comments_count >' => 10])
  907. * ```
  908. *
  909. * Produces:
  910. *
  911. * `WHERE (published = 0 OR published IS NULL) OR (author_id = 1 AND comments_count > 10)`
  912. *
  913. * ```
  914. * $query
  915. * ->where(['title' => 'Foo'])
  916. * ->orWhere(function ($exp, $query) {
  917. * return $exp
  918. * ->or_(['author_id' => 1])
  919. * ->add(['author_id' => 2]);
  920. * });
  921. * ```
  922. *
  923. * Generates the following conditions:
  924. *
  925. * `WHERE (title = 'Foo') OR (author_id = 1 OR author_id = 2)`
  926. *
  927. * @param string|array|\Cake\Database\ExpressionInterface|callable $conditions The conditions to add with OR.
  928. * @param array $types associative array of type names used to bind values to query
  929. * @see \Cake\Database\Query::where()
  930. * @see \Cake\Database\Type
  931. * @return $this
  932. */
  933. public function orWhere($conditions, $types = [])
  934. {
  935. $this->_conjugate('where', $conditions, 'OR', $types);
  936. return $this;
  937. }
  938. /**
  939. * Adds a single or multiple fields to be used in the ORDER clause for this query.
  940. * Fields can be passed as an array of strings, array of expression
  941. * objects, a single expression or a single string.
  942. *
  943. * If an array is passed, keys will be used as the field itself and the value will
  944. * represent the order in which such field should be ordered. When called multiple
  945. * times with the same fields as key, the last order definition will prevail over
  946. * the others.
  947. *
  948. * By default this function will append any passed argument to the list of fields
  949. * to be selected, unless the second argument is set to true.
  950. *
  951. * ### Examples:
  952. *
  953. * ```
  954. * $query->order(['title' => 'DESC', 'author_id' => 'ASC']);
  955. * ```
  956. *
  957. * Produces:
  958. *
  959. * `ORDER BY title DESC, author_id ASC`
  960. *
  961. * ```
  962. * $query->order(['title' => 'DESC NULLS FIRST'])->order('author_id');
  963. * ```
  964. *
  965. * Will generate:
  966. *
  967. * `ORDER BY title DESC NULLS FIRST, author_id`
  968. *
  969. * ```
  970. * $expression = $query->newExpr()->add(['id % 2 = 0']);
  971. * $query->order($expression)->order(['title' => 'ASC']);
  972. * ```
  973. *
  974. * Will become:
  975. *
  976. * `ORDER BY (id %2 = 0), title ASC`
  977. *
  978. * If you need to set complex expressions as order conditions, you
  979. * should use `orderAsc()` or `orderDesc()`.
  980. *
  981. * @param array|\Cake\Database\ExpressionInterface|string $fields fields to be added to the list
  982. * @param bool $overwrite whether to reset order with field list or not
  983. * @return $this
  984. */
  985. public function order($fields, $overwrite = false)
  986. {
  987. if ($overwrite) {
  988. $this->_parts['order'] = null;
  989. }
  990. if (!$fields) {
  991. return $this;
  992. }
  993. if (!$this->_parts['order']) {
  994. $this->_parts['order'] = new OrderByExpression();
  995. }
  996. $this->_conjugate('order', $fields, '', []);
  997. return $this;
  998. }
  999. /**
  1000. * Add an ORDER BY clause with an ASC direction.
  1001. *
  1002. * This method allows you to set complex expressions
  1003. * as order conditions unlike order()
  1004. *
  1005. * @param string|\Cake\Database\Expression\QueryExpression $field The field to order on.
  1006. * @param bool $overwrite Whether or not to reset the order clauses.
  1007. * @return $this
  1008. */
  1009. public function orderAsc($field, $overwrite = false)
  1010. {
  1011. if ($overwrite) {
  1012. $this->_parts['order'] = null;
  1013. }
  1014. if (!$field) {
  1015. return $this;
  1016. }
  1017. if (!$this->_parts['order']) {
  1018. $this->_parts['order'] = new OrderByExpression();
  1019. }
  1020. $this->_parts['order']->add(new OrderClauseExpression($field, 'ASC'));
  1021. return $this;
  1022. }
  1023. /**
  1024. * Add an ORDER BY clause with a DESC direction.
  1025. *
  1026. * This method allows you to set complex expressions
  1027. * as order conditions unlike order()
  1028. *
  1029. * @param string|\Cake\Database\Expression\QueryExpression $field The field to order on.
  1030. * @param bool $overwrite Whether or not to reset the order clauses.
  1031. * @return $this
  1032. */
  1033. public function orderDesc($field, $overwrite = false)
  1034. {
  1035. if ($overwrite) {
  1036. $this->_parts['order'] = null;
  1037. }
  1038. if (!$field) {
  1039. return $this;
  1040. }
  1041. if (!$this->_parts['order']) {
  1042. $this->_parts['order'] = new OrderByExpression();
  1043. }
  1044. $this->_parts['order']->add(new OrderClauseExpression($field, 'DESC'));
  1045. return $this;
  1046. }
  1047. /**
  1048. * Adds a single or multiple fields to be used in the GROUP BY clause for this query.
  1049. * Fields can be passed as an array of strings, array of expression
  1050. * objects, a single expression or a single string.
  1051. *
  1052. * By default this function will append any passed argument to the list of fields
  1053. * to be grouped, unless the second argument is set to true.
  1054. *
  1055. * ### Examples:
  1056. *
  1057. * ```
  1058. * // Produces GROUP BY id, title
  1059. * $query->group(['id', 'title']);
  1060. *
  1061. * // Produces GROUP BY title
  1062. * $query->group('title');
  1063. * ```
  1064. *
  1065. * @param array|\Cake\Database\ExpressionInterface|string $fields fields to be added to the list
  1066. * @param bool $overwrite whether to reset fields with passed list or not
  1067. * @return $this
  1068. */
  1069. public function group($fields, $overwrite = false)
  1070. {
  1071. if ($overwrite) {
  1072. $this->_parts['group'] = [];
  1073. }
  1074. if (!is_array($fields)) {
  1075. $fields = [$fields];
  1076. }
  1077. $this->_parts['group'] = array_merge($this->_parts['group'], array_values($fields));
  1078. $this->_dirty();
  1079. return $this;
  1080. }
  1081. /**
  1082. * Adds a condition or set of conditions to be used in the HAVING clause for this
  1083. * query. This method operates in exactly the same way as the method `where()`
  1084. * does. Please refer to its documentation for an insight on how to using each
  1085. * parameter.
  1086. *
  1087. * @param string|array|\Cake\Database\ExpressionInterface|callable|null $conditions The having conditions.
  1088. * @param array $types associative array of type names used to bind values to query
  1089. * @param bool $overwrite whether to reset conditions with passed list or not
  1090. * @see \Cake\Database\Query::where()
  1091. * @return $this
  1092. */
  1093. public function having($conditions = null, $types = [], $overwrite = false)
  1094. {
  1095. if ($overwrite) {
  1096. $this->_parts['having'] = $this->newExpr();
  1097. }
  1098. $this->_conjugate('having', $conditions, 'AND', $types);
  1099. return $this;
  1100. }
  1101. /**
  1102. * Connects any previously defined set of conditions to the provided list
  1103. * using the AND operator in the HAVING clause. This method operates in exactly
  1104. * the same way as the method `andWhere()` does. Please refer to its
  1105. * documentation for an insight on how to using each parameter.
  1106. *
  1107. * @param string|array|\Cake\Database\ExpressionInterface|callable $conditions The AND conditions for HAVING.
  1108. * @param array $types associative array of type names used to bind values to query
  1109. * @see \Cake\Database\Query::andWhere()
  1110. * @return $this
  1111. */
  1112. public function andHaving($conditions, $types = [])
  1113. {
  1114. $this->_conjugate('having', $conditions, 'AND', $types);
  1115. return $this;
  1116. }
  1117. /**
  1118. * Connects any previously defined set of conditions to the provided list
  1119. * using the OR operator in the HAVING clause. This method operates in exactly
  1120. * the same way as the method `orWhere()` does. Please refer to its
  1121. * documentation for an insight on how to using each parameter.
  1122. *
  1123. * @param string|array|\Cake\Database\ExpressionInterface|callable $conditions The OR conditions for HAVING.
  1124. * @param array $types associative array of type names used to bind values to query.
  1125. * @see \Cake\Database\Query::orWhere()
  1126. * @return $this
  1127. */
  1128. public function orHaving($conditions, $types = [])
  1129. {
  1130. $this->_conjugate('having', $conditions, 'OR', $types);
  1131. return $this;
  1132. }
  1133. /**
  1134. * Set the page of results you want.
  1135. *
  1136. * This method provides an easier to use interface to set the limit + offset
  1137. * in the record set you want as results. If empty the limit will default to
  1138. * the existing limit clause, and if that too is empty, then `25` will be used.
  1139. *
  1140. * Pages should start at 1.
  1141. *
  1142. * @param int $num The page number you want.
  1143. * @param int|null $limit The number of rows you want in the page. If null
  1144. * the current limit clause will be used.
  1145. * @return $this
  1146. */
  1147. public function page($num, $limit = null)
  1148. {
  1149. if ($limit !== null) {
  1150. $this->limit($limit);
  1151. }
  1152. $limit = $this->clause('limit');
  1153. if ($limit === null) {
  1154. $limit = 25;
  1155. $this->limit($limit);
  1156. }
  1157. $offset = ($num - 1) * $limit;
  1158. if (PHP_INT_MAX <= $offset) {
  1159. $offset = PHP_INT_MAX;
  1160. }
  1161. $this->offset((int)$offset);
  1162. return $this;
  1163. }
  1164. /**
  1165. * Sets the number of records that should be retrieved from database,
  1166. * accepts an integer or an expression object that evaluates to an integer.
  1167. * In some databases, this operation might not be supported or will require
  1168. * the query to be transformed in order to limit the result set size.
  1169. *
  1170. * ### Examples
  1171. *
  1172. * ```
  1173. * $query->limit(10) // generates LIMIT 10
  1174. * $query->limit($query->newExpr()->add(['1 + 1'])); // LIMIT (1 + 1)
  1175. * ```
  1176. *
  1177. * @param int|\Cake\Database\ExpressionInterface $num number of records to be returned
  1178. * @return $this
  1179. */
  1180. public function limit($num)
  1181. {
  1182. $this->_dirty();
  1183. if ($num !== null && !is_object($num)) {
  1184. $num = (int)$num;
  1185. }
  1186. $this->_parts['limit'] = $num;
  1187. return $this;
  1188. }
  1189. /**
  1190. * Sets the number of records that should be skipped from the original result set
  1191. * This is commonly used for paginating large results. Accepts an integer or an
  1192. * expression object that evaluates to an integer.
  1193. *
  1194. * In some databases, this operation might not be supported or will require
  1195. * the query to be transformed in order to limit the result set size.
  1196. *
  1197. * ### Examples
  1198. *
  1199. * ```
  1200. * $query->offset(10) // generates OFFSET 10
  1201. * $query->offset($query->newExpr()->add(['1 + 1'])); // OFFSET (1 + 1)
  1202. * ```
  1203. *
  1204. * @param int|\Cake\Database\ExpressionInterface $num number of records to be skipped
  1205. * @return $this
  1206. */
  1207. public function offset($num)
  1208. {
  1209. $this->_dirty();
  1210. if ($num !== null && !is_object($num)) {
  1211. $num = (int)$num;
  1212. }
  1213. $this->_parts['offset'] = $num;
  1214. return $this;
  1215. }
  1216. /**
  1217. * Adds a complete query to be used in conjunction with an UNION operator with
  1218. * this query. This is used to combine the result set of this query with the one
  1219. * that will be returned by the passed query. You can add as many queries as you
  1220. * required by calling multiple times this method with different queries.
  1221. *
  1222. * By default, the UNION operator will remove duplicate rows, if you wish to include
  1223. * every row for all queries, use unionAll().
  1224. *
  1225. * ### Examples
  1226. *
  1227. * ```
  1228. * $union = (new Query($conn))->select(['id', 'title'])->from(['a' => 'articles']);
  1229. * $query->select(['id', 'name'])->from(['d' => 'things'])->union($union);
  1230. * ```
  1231. *
  1232. * Will produce:
  1233. *
  1234. * `SELECT id, name FROM things d UNION SELECT id, title FROM articles a`
  1235. *
  1236. * @param string|\Cake\Database\Query $query full SQL query to be used in UNION operator
  1237. * @param bool $overwrite whether to reset the list of queries to be operated or not
  1238. * @return $this
  1239. */
  1240. public function union($query, $overwrite = false)
  1241. {
  1242. if ($overwrite) {
  1243. $this->_parts['union'] = [];
  1244. }
  1245. $this->_parts['union'][] = [
  1246. 'all' => false,
  1247. 'query' => $query
  1248. ];
  1249. $this->_dirty();
  1250. return $this;
  1251. }
  1252. /**
  1253. * Adds a complete query to be used in conjunction with the UNION ALL operator with
  1254. * this query. This is used to combine the result set of this query with the one
  1255. * that will be returned by the passed query. You can add as many queries as you
  1256. * required by calling multiple times this method with different queries.
  1257. *
  1258. * Unlike UNION, UNION ALL will not remove duplicate rows.
  1259. *
  1260. * ```
  1261. * $union = (new Query($conn))->select(['id', 'title'])->from(['a' => 'articles']);
  1262. * $query->select(['id', 'name'])->from(['d' => 'things'])->unionAll($union);
  1263. * ```
  1264. *
  1265. * Will produce:
  1266. *
  1267. * `SELECT id, name FROM things d UNION ALL SELECT id, title FROM articles a`
  1268. *
  1269. * @param string|\Cake\Database\Query $query full SQL query to be used in UNION operator
  1270. * @param bool $overwrite whether to reset the list of queries to be operated or not
  1271. * @return $this
  1272. */
  1273. public function unionAll($query, $overwrite = false)
  1274. {
  1275. if ($overwrite) {
  1276. $this->_parts['union'] = [];
  1277. }
  1278. $this->_parts['union'][] = [
  1279. 'all' => true,
  1280. 'query' => $query
  1281. ];
  1282. $this->_dirty();
  1283. return $this;
  1284. }
  1285. /**
  1286. * Create an insert query.
  1287. *
  1288. * Note calling this method will reset any data previously set
  1289. * with Query::values().
  1290. *
  1291. * @param array $columns The columns to insert into.
  1292. * @param array $types A map between columns & their datatypes.
  1293. * @return $this
  1294. * @throws \RuntimeException When there are 0 columns.
  1295. */
  1296. public function insert(array $columns, array $types = [])
  1297. {
  1298. if (empty($columns)) {
  1299. throw new RuntimeException('At least 1 column is required to perform an insert.');
  1300. }
  1301. $this->_dirty();
  1302. $this->_type = 'insert';
  1303. $this->_parts['insert'][1] = $columns;
  1304. if (!$this->_parts['values']) {
  1305. $this->_parts['values'] = new ValuesExpression($columns, $this->getTypeMap()->setTypes($types));
  1306. } else {
  1307. $this->_parts['values']->setColumns($columns);
  1308. }
  1309. return $this;
  1310. }
  1311. /**
  1312. * Set the table name for insert queries.
  1313. *
  1314. * @param string $table The table name to insert into.
  1315. * @return $this
  1316. */
  1317. public function into($table)
  1318. {
  1319. $this->_dirty();
  1320. $this->_type = 'insert';
  1321. $this->_parts['insert'][0] = $table;
  1322. return $this;
  1323. }
  1324. /**
  1325. * Set the values for an insert query.
  1326. *
  1327. * Multi inserts can be performed by calling values() more than one time,
  1328. * or by providing an array of value sets. Additionally $data can be a Query
  1329. * instance to insert data from another SELECT statement.
  1330. *
  1331. * @param array|\Cake\Database\Query $data The data to insert.
  1332. * @return $this
  1333. * @throws \Cake\Database\Exception if you try to set values before declaring columns.
  1334. * Or if you try to set values on non-insert queries.
  1335. */
  1336. public function values($data)
  1337. {
  1338. if ($this->_type !== 'insert') {
  1339. throw new Exception(
  1340. 'You cannot add values before defining columns to use.'
  1341. );
  1342. }
  1343. if (empty($this->_parts['insert'])) {
  1344. throw new Exception(
  1345. 'You cannot add values before defining columns to use.'
  1346. );
  1347. }
  1348. $this->_dirty();
  1349. if ($data instanceof ValuesExpression) {
  1350. $this->_parts['values'] = $data;
  1351. return $this;
  1352. }
  1353. $this->_parts['values']->add($data);
  1354. return $this;
  1355. }
  1356. /**
  1357. * Create an update query.
  1358. *
  1359. * Can be combined with set() and where() methods to create update queries.
  1360. *
  1361. * @param string|\Cake\Database\ExpressionInterface $table The table you want to update.
  1362. * @return $this
  1363. */
  1364. public function update($table)
  1365. {
  1366. if (!is_string($table) && !($table instanceof ExpressionInterface)) {
  1367. $text = 'Table must be of type string or "%s", got "%s"';
  1368. $message = sprintf($text, ExpressionInterface::class, gettype($table));
  1369. throw new InvalidArgumentException($message);
  1370. }
  1371. $this->_dirty();
  1372. $this->_type = 'update';
  1373. $this->_parts['update'][0] = $table;
  1374. return $this;
  1375. }
  1376. /**
  1377. * Set one or many fields to update.
  1378. *
  1379. * ### Examples
  1380. *
  1381. * Passing a string:
  1382. *
  1383. * ```
  1384. * $query->update('articles')->set('title', 'The Title');
  1385. * ```
  1386. *
  1387. * Passing an array:
  1388. *
  1389. * ```
  1390. * $query->update('articles')->set(['title' => 'The Title'], ['title' => 'string']);
  1391. * ```
  1392. *
  1393. * Passing a callable:
  1394. *
  1395. * ```
  1396. * $query->update('articles')->set(function ($exp) {
  1397. * return $exp->eq('title', 'The title', 'string');
  1398. * });
  1399. * ```
  1400. *
  1401. * @param string|array|callable|\Cake\Database\Expression\QueryExpression $key The column name or array of keys
  1402. * + values to set. This can also be a QueryExpression containing a SQL fragment.
  1403. * It can also be a callable, that is required to return an expression object.
  1404. * @param mixed $value The value to update $key to. Can be null if $key is an
  1405. * array or QueryExpression. When $key is an array, this parameter will be
  1406. * used as $types instead.
  1407. * @param array $types The column types to treat data as.
  1408. * @return $this
  1409. */
  1410. public function set($key, $value = null, $types = [])
  1411. {
  1412. if (empty($this->_parts['set'])) {
  1413. $this->_parts['set'] = $this->newExpr()->setConjunction(',');
  1414. }
  1415. if ($this->_parts['set']->isCallable($key)) {
  1416. $exp = $this->newExpr()->setConjunction(',');
  1417. $this->_parts['set']->add($key($exp));
  1418. return $this;
  1419. }
  1420. if (is_array($key) || $key instanceof ExpressionInterface) {
  1421. $types = (array)$value;
  1422. $this->_parts['set']->add($key, $types);
  1423. return $this;
  1424. }
  1425. if (is_string($types) && is_string($key)) {
  1426. $types = [$key => $types];
  1427. }
  1428. $this->_parts['set']->eq($key, $value, $types);
  1429. return $this;
  1430. }
  1431. /**
  1432. * Create a delete query.
  1433. *
  1434. * Can be combined with from(), where() and other methods to
  1435. * create delete queries with specific conditions.
  1436. *
  1437. * @param string|null $table The table to use when deleting.
  1438. * @return $this
  1439. */
  1440. public function delete($table = null)
  1441. {
  1442. $this->_dirty();
  1443. $this->_type = 'delete';
  1444. if ($table !== null) {
  1445. $this->from($table);
  1446. }
  1447. return $this;
  1448. }
  1449. /**
  1450. * A string or expression that will be appended to the generated query
  1451. *
  1452. * ### Examples:
  1453. * ```
  1454. * $query->select('id')->where(['author_id' => 1])->epilog('FOR UPDATE');
  1455. * $query
  1456. * ->insert('articles', ['title'])
  1457. * ->values(['author_id' => 1])
  1458. * ->epilog('RETURNING id');
  1459. * ```
  1460. *
  1461. * @param string|\Cake\Database\Expression\QueryExpression|null $expression The expression to be appended
  1462. * @return $this
  1463. */
  1464. public function epilog($expression = null)
  1465. {
  1466. $this->_dirty();
  1467. $this->_parts['epilog'] = $expression;
  1468. return $this;
  1469. }
  1470. /**
  1471. * Returns the type of this query (select, insert, update, delete)
  1472. *
  1473. * @return string
  1474. */
  1475. public function type()
  1476. {
  1477. return $this->_type;
  1478. }
  1479. /**
  1480. * Returns a new QueryExpression object. This is a handy function when
  1481. * building complex queries using a fluent interface. You can also override
  1482. * this function in subclasses to use a more specialized QueryExpression class
  1483. * if required.
  1484. *
  1485. * You can optionally pass a single raw SQL string or an array or expressions in
  1486. * any format accepted by \Cake\Database\Expression\QueryExpression:
  1487. *
  1488. * ```
  1489. * $expression = $query->newExpr(); // Returns an empty expression object
  1490. * $expression = $query->newExpr('Table.column = Table2.column'); // Return a raw SQL expression
  1491. * ```
  1492. *
  1493. * @param mixed $rawExpression A string, array or anything you want wrapped in an expression object
  1494. * @return \Cake\Database\Expression\QueryExpression
  1495. */
  1496. public function newExpr($rawExpression = null)
  1497. {
  1498. $expression = new QueryExpression([], $this->getTypeMap());
  1499. if ($rawExpression !== null) {
  1500. $expression->add($rawExpression);
  1501. }
  1502. return $expression;
  1503. }
  1504. /**
  1505. * Returns an instance of a functions builder object that can be used for
  1506. * generating arbitrary SQL functions.
  1507. *
  1508. * ### Example:
  1509. *
  1510. * ```
  1511. * $query->func()->count('*');
  1512. * $query->func()->dateDiff(['2012-01-05', '2012-01-02'])
  1513. * ```
  1514. *
  1515. * @return \Cake\Database\FunctionsBuilder
  1516. */
  1517. public function func()
  1518. {
  1519. if ($this->_functionsBuilder === null) {
  1520. $this->_functionsBuilder = new FunctionsBuilder();
  1521. }
  1522. return $this->_functionsBuilder;
  1523. }
  1524. /**
  1525. * Executes this query and returns a results iterator. This function is required
  1526. * for implementing the IteratorAggregate interface and allows the query to be
  1527. * iterated without having to call execute() manually, thus making it look like
  1528. * a result set instead of the query itself.
  1529. *
  1530. * @return \Cake\Database\StatementInterface|null
  1531. */
  1532. public function getIterator()
  1533. {
  1534. if ($this->_iterator === null || $this->_dirty) {
  1535. $this->_iterator = $this->execute();
  1536. }
  1537. return $this->_iterator;
  1538. }
  1539. /**
  1540. * Returns any data that was stored in the specified clause. This is useful for
  1541. * modifying any internal part of the query and it is used by the SQL dialects
  1542. * to transform the query accordingly before it is executed. The valid clauses that
  1543. * can be retrieved are: delete, update, set, insert, values, select, distinct,
  1544. * from, join, set, where, group, having, order, limit, offset and union.
  1545. *
  1546. * The return value for each of those parts may vary. Some clauses use QueryExpression
  1547. * to internally store their state, some use arrays and others may use booleans or
  1548. * integers. This is summary of the return types for each clause.
  1549. *
  1550. * - update: string The name of the table to update
  1551. * - set: QueryExpression
  1552. * - insert: array, will return an array containing the table + columns.
  1553. * - values: ValuesExpression
  1554. * - select: array, will return empty array when no fields are set
  1555. * - distinct: boolean
  1556. * - from: array of tables
  1557. * - join: array
  1558. * - set: array
  1559. * - where: QueryExpression, returns null when not set
  1560. * - group: array
  1561. * - having: QueryExpression, returns null when not set
  1562. * - order: OrderByExpression, returns null when not set
  1563. * - limit: integer or QueryExpression, null when not set
  1564. * - offset: integer or QueryExpression, null when not set
  1565. * - union: array
  1566. *
  1567. * @param string $name name of the clause to be returned
  1568. * @return mixed
  1569. * @throws InvalidArgumentException When the named clause does not exist.
  1570. */
  1571. public function clause($name)
  1572. {
  1573. if (!array_key_exists($name, $this->_parts)) {
  1574. $clauses = implode(', ', array_keys($this->_parts));
  1575. throw new InvalidArgumentException("The '$name' clause is not defined. Valid clauses are: $clauses");
  1576. }
  1577. return $this->_parts[$name];
  1578. }
  1579. /**
  1580. * Registers a callback to be executed for each result that is fetched from the
  1581. * result set, the callback function will receive as first parameter an array with
  1582. * the raw data from the database for every row that is fetched and must return the
  1583. * row with any possible modifications.
  1584. *
  1585. * Callbacks will be executed lazily, if only 3 rows are fetched for database it will
  1586. * called 3 times, event though there might be more rows to be fetched in the cursor.
  1587. *
  1588. * Callbacks are stacked in the order they are registered, if you wish to reset the stack
  1589. * the call this function with the second parameter set to true.
  1590. *
  1591. * If you wish to remove all decorators from the stack, set the first parameter
  1592. * to null and the second to true.
  1593. *
  1594. * ### Example
  1595. *
  1596. * ```
  1597. * $query->decorateResults(function ($row) {
  1598. * $row['order_total'] = $row['subtotal'] + ($row['subtotal'] * $row['tax']);
  1599. * return $row;
  1600. * });
  1601. * ```
  1602. *
  1603. * @param callable|null $callback The callback to invoke when results are fetched.
  1604. * @param bool $overwrite Whether or not this should append or replace all existing decorators.
  1605. * @return $this
  1606. */
  1607. public function decorateResults($callback, $overwrite = false)
  1608. {
  1609. if ($overwrite) {
  1610. $this->_resultDecorators = [];
  1611. $this->_typeCastAttached = false;
  1612. }
  1613. if ($callback !== null) {
  1614. $this->_resultDecorators[] = $callback;
  1615. }
  1616. return $this;
  1617. }
  1618. /**
  1619. * This function works similar to the traverse() function, with the difference
  1620. * that it does a full depth traversal of the entire expression tree. This will execute
  1621. * the provided callback function for each ExpressionInterface object that is
  1622. * stored inside this query at any nesting depth in any part of the query.
  1623. *
  1624. * Callback will receive as first parameter the currently visited expression.
  1625. *
  1626. * @param callable $callback the function to be executed for each ExpressionInterface
  1627. * found inside this query.
  1628. * @return $this|null
  1629. */
  1630. public function traverseExpressions(callable $callback)
  1631. {
  1632. $visitor = function ($expression) use (&$visitor, $callback) {
  1633. if (is_array($expression)) {
  1634. foreach ($expression as $e) {
  1635. $visitor($e);
  1636. }
  1637. return null;
  1638. }
  1639. if ($expression instanceof ExpressionInterface) {
  1640. $expression->traverse($visitor);
  1641. if (!($expression instanceof self)) {
  1642. $callback($expression);
  1643. }
  1644. }
  1645. };
  1646. return $this->traverse($visitor);
  1647. }
  1648. /**
  1649. * Associates a query placeholder to a value and a type.
  1650. *
  1651. * If type is expressed as "atype[]" (note braces) then it will cause the
  1652. * placeholder to be re-written dynamically so if the value is an array, it
  1653. * will create as many placeholders as values are in it. For example:
  1654. *
  1655. * ```
  1656. * $query->bind(':id', [1, 2, 3], 'int[]');
  1657. * ```
  1658. *
  1659. * Will create 3 int placeholders. When using named placeholders, this method
  1660. * requires that the placeholders include `:` e.g. `:value`.
  1661. *
  1662. * @param string|int $param placeholder to be replaced with quoted version
  1663. * of $value
  1664. * @param mixed $value The value to be bound
  1665. * @param string|int $type the mapped type name, used for casting when sending
  1666. * to database
  1667. * @return $this
  1668. */
  1669. public function bind($param, $value, $type = 'string')
  1670. {
  1671. $this->getValueBinder()->bind($param, $value, $type);
  1672. return $this;
  1673. }
  1674. /**
  1675. * Returns the currently used ValueBinder instance.
  1676. *
  1677. * A ValueBinder is responsible for generating query placeholders and temporarily
  1678. * associate values to those placeholders so that they can be passed correctly
  1679. * to the statement object.
  1680. *
  1681. * @return \Cake\Database\ValueBinder
  1682. */
  1683. public function getValueBinder()
  1684. {
  1685. if ($this->_valueBinder === null) {
  1686. $this->_valueBinder = new ValueBinder();
  1687. }
  1688. return $this->_valueBinder;
  1689. }
  1690. /**
  1691. * Returns the currently used ValueBinder instance. If a value is passed,
  1692. * it will be set as the new instance to be used.
  1693. *
  1694. * A ValueBinder is responsible for generating query placeholders and temporarily
  1695. * associate values to those placeholders so that they can be passed correctly
  1696. * to the statement object.
  1697. *
  1698. * @deprecated 3.5.0 Use getValueBinder() for the getter part instead.
  1699. * @param \Cake\Database\ValueBinder|null $binder new instance to be set. If no value is passed the
  1700. * default one will be returned
  1701. * @return $this|\Cake\Database\ValueBinder
  1702. */
  1703. public function valueBinder($binder = null)
  1704. {
  1705. if ($binder === null) {
  1706. if ($this->_valueBinder === null) {
  1707. $this->_valueBinder = new ValueBinder();
  1708. }
  1709. return $this->_valueBinder;
  1710. }
  1711. $this->_valueBinder = $binder;
  1712. return $this;
  1713. }
  1714. /**
  1715. * Enables/Disables buffered results.
  1716. *
  1717. * When enabled the results returned by this Query will be
  1718. * buffered. This enables you to iterate a result set multiple times, or
  1719. * both cache and iterate it.
  1720. *
  1721. * When disabled it will consume less memory as fetched results are not
  1722. * remembered for future iterations.
  1723. *
  1724. * @param bool $enable Whether or not to enable buffering
  1725. * @return $this
  1726. */
  1727. public function enableBufferedResults($enable = true)
  1728. {
  1729. $this->_dirty();
  1730. $this->_useBufferedResults = (bool)$enable;
  1731. return $this;
  1732. }
  1733. /**
  1734. * Returns whether buffered results are enabled/disabled.
  1735. *
  1736. * When enabled the results returned by this Query will be
  1737. * buffered. This enables you to iterate a result set multiple times, or
  1738. * both cache and iterate it.
  1739. *
  1740. * When disabled it will consume less memory as fetched results are not
  1741. * remembered for future iterations.
  1742. *
  1743. * @return bool
  1744. */
  1745. public function isBufferedResultsEnabled()
  1746. {
  1747. return $this->_useBufferedResults;
  1748. }
  1749. /**
  1750. * Enable/Disable buffered results.
  1751. *
  1752. * When enabled the results returned by this Query will be
  1753. * buffered. This enables you to iterate a result set multiple times, or
  1754. * both cache and iterate it.
  1755. *
  1756. * When disabled it will consume less memory as fetched results are not
  1757. * remembered for future iterations.
  1758. *
  1759. * If called with no arguments, it will return whether or not buffering is
  1760. * enabled.
  1761. *
  1762. * @deprecated 3.4.0 Use enableBufferedResults()/isBufferedResultsEnabled() instead.
  1763. * @param bool|null $enable Whether or not to enable buffering
  1764. * @return bool|$this
  1765. */
  1766. public function bufferResults($enable = null)
  1767. {
  1768. if ($enable !== null) {
  1769. return $this->enableBufferedResults($enable);
  1770. }
  1771. return $this->isBufferedResultsEnabled();
  1772. }
  1773. /**
  1774. * Sets the TypeMap class where the types for each of the fields in the
  1775. * select clause are stored.
  1776. *
  1777. * @param \Cake\Database\TypeMap $typeMap The map object to use
  1778. * @return $this
  1779. */
  1780. public function setSelectTypeMap(TypeMap $typeMap)
  1781. {
  1782. $this->_selectTypeMap = $typeMap;
  1783. return $this;
  1784. }
  1785. /**
  1786. * Gets the TypeMap class where the types for each of the fields in the
  1787. * select clause are stored.
  1788. *
  1789. * @return \Cake\Database\TypeMap
  1790. */
  1791. public function getSelectTypeMap()
  1792. {
  1793. if ($this->_selectTypeMap === null) {
  1794. $this->_selectTypeMap = new TypeMap();
  1795. }
  1796. return $this->_selectTypeMap;
  1797. }
  1798. /**
  1799. * Sets the TypeMap class where the types for each of the fields in the
  1800. * select clause are stored.
  1801. *
  1802. * When called with no arguments, the current TypeMap object is returned.
  1803. *
  1804. * @deprecated 3.4.0 Use setSelectTypeMap()/getSelectTypeMap() instead.
  1805. * @param \Cake\Database\TypeMap|null $typeMap The map object to use
  1806. * @return $this|\Cake\Database\TypeMap
  1807. */
  1808. public function selectTypeMap(TypeMap $typeMap = null)
  1809. {
  1810. if ($typeMap !== null) {
  1811. return $this->setSelectTypeMap($typeMap);
  1812. }
  1813. return $this->getSelectTypeMap();
  1814. }
  1815. /**
  1816. * Auxiliary function used to wrap the original statement from the driver with
  1817. * any registered callbacks.
  1818. *
  1819. * @param \Cake\Database\StatementInterface $statement to be decorated
  1820. * @return \Cake\Database\Statement\CallbackStatement
  1821. */
  1822. protected function _decorateStatement($statement)
  1823. {
  1824. foreach ($this->_resultDecorators as $f) {
  1825. $statement = new CallbackStatement($statement, $this->getConnection()->driver(), $f);
  1826. }
  1827. return $statement;
  1828. }
  1829. /**
  1830. * Helper function used to build conditions by composing QueryExpression objects.
  1831. *
  1832. * @param string $part Name of the query part to append the new part to
  1833. * @param string|null|array|\Cake\Database\ExpressionInterface|callable $append Expression or builder function to append.
  1834. * @param string $conjunction type of conjunction to be used to operate part
  1835. * @param array $types associative array of type names used to bind values to query
  1836. * @return void
  1837. */
  1838. protected function _conjugate($part, $append, $conjunction, $types)
  1839. {
  1840. $expression = $this->_parts[$part] ?: $this->newExpr();
  1841. if (empty($append)) {
  1842. $this->_parts[$part] = $expression;
  1843. return;
  1844. }
  1845. if ($expression->isCallable($append)) {
  1846. $append = $append($this->newExpr(), $this);
  1847. }
  1848. if ($expression->getConjunction() === $conjunction) {
  1849. $expression->add($append, $types);
  1850. } else {
  1851. $expression = $this->newExpr()
  1852. ->setConjunction($conjunction)
  1853. ->add([$expression, $append], $types);
  1854. }
  1855. $this->_parts[$part] = $expression;
  1856. $this->_dirty();
  1857. }
  1858. /**
  1859. * Marks a query as dirty, removing any preprocessed information
  1860. * from in memory caching.
  1861. *
  1862. * @return void
  1863. */
  1864. protected function _dirty()
  1865. {
  1866. $this->_dirty = true;
  1867. if ($this->_iterator && $this->_valueBinder) {
  1868. $this->getValueBinder()->reset();
  1869. }
  1870. }
  1871. /**
  1872. * Do a deep clone on this object.
  1873. *
  1874. * Will clone all of the expression objects used in
  1875. * each of the clauses, as well as the valueBinder.
  1876. *
  1877. * @return void
  1878. */
  1879. public function __clone()
  1880. {
  1881. $this->_iterator = null;
  1882. if ($this->_valueBinder !== null) {
  1883. $this->_valueBinder = clone $this->_valueBinder;
  1884. }
  1885. if ($this->_selectTypeMap !== null) {
  1886. $this->_selectTypeMap = clone $this->_selectTypeMap;
  1887. }
  1888. foreach ($this->_parts as $name => $part) {
  1889. if (empty($part)) {
  1890. continue;
  1891. }
  1892. if (is_array($part)) {
  1893. foreach ($part as $i => $piece) {
  1894. if ($piece instanceof ExpressionInterface) {
  1895. $this->_parts[$name][$i] = clone $piece;
  1896. }
  1897. }
  1898. }
  1899. if ($part instanceof ExpressionInterface) {
  1900. $this->_parts[$name] = clone $part;
  1901. }
  1902. }
  1903. }
  1904. /**
  1905. * Returns string representation of this query (complete SQL statement).
  1906. *
  1907. * @return string
  1908. */
  1909. public function __toString()
  1910. {
  1911. return $this->sql();
  1912. }
  1913. /**
  1914. * Returns an array that can be used to describe the internal state of this
  1915. * object.
  1916. *
  1917. * @return array
  1918. */
  1919. public function __debugInfo()
  1920. {
  1921. try {
  1922. set_error_handler(function ($errno, $errstr) {
  1923. throw new RuntimeException($errstr, $errno);
  1924. }, E_ALL);
  1925. $sql = $this->sql();
  1926. $params = $this->getValueBinder()->bindings();
  1927. } catch (RuntimeException $e) {
  1928. $sql = 'SQL could not be generated for this query as it is incomplete.';
  1929. $params = [];
  1930. } finally {
  1931. restore_error_handler();
  1932. }
  1933. return [
  1934. '(help)' => 'This is a Query object, to get the results execute or iterate it.',
  1935. 'sql' => $sql,
  1936. 'params' => $params,
  1937. 'defaultTypes' => $this->getDefaultTypes(),
  1938. 'decorators' => count($this->_resultDecorators),
  1939. 'executed' => $this->_iterator ? true : false
  1940. ];
  1941. }
  1942. }