Query.php 72 KB

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