Query.php 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226
  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 Closure;
  24. use InvalidArgumentException;
  25. use IteratorAggregate;
  26. use RuntimeException;
  27. /**
  28. * This class represents a Relational database SQL Query. A query can be of
  29. * different types like select, update, insert and delete. Exposes the methods
  30. * for dynamically constructing each query part, execute it and transform it
  31. * to a specific SQL dialect.
  32. */
  33. class Query implements ExpressionInterface, IteratorAggregate
  34. {
  35. use TypeMapTrait;
  36. public const JOIN_TYPE_INNER = 'INNER';
  37. public const JOIN_TYPE_LEFT = 'LEFT';
  38. public const JOIN_TYPE_RIGHT = 'RIGHT';
  39. /**
  40. * Connection instance to be used to execute this query.
  41. *
  42. * @var \Cake\Database\Connection
  43. */
  44. protected $_connection;
  45. /**
  46. * Type of this query (select, insert, update, delete).
  47. *
  48. * @var string
  49. */
  50. protected $_type = 'select';
  51. /**
  52. * List of SQL parts that will be used to build this query.
  53. *
  54. * @var array
  55. */
  56. protected $_parts = [
  57. 'delete' => true,
  58. 'update' => [],
  59. 'set' => [],
  60. 'insert' => [],
  61. 'values' => [],
  62. 'select' => [],
  63. 'distinct' => false,
  64. 'modifier' => [],
  65. 'from' => [],
  66. 'join' => [],
  67. 'where' => null,
  68. 'group' => [],
  69. 'having' => null,
  70. 'order' => null,
  71. 'limit' => null,
  72. 'offset' => null,
  73. 'union' => [],
  74. 'epilog' => null,
  75. ];
  76. /**
  77. * The list of query clauses to traverse for generating a SELECT statement
  78. *
  79. * @var string[]
  80. */
  81. protected $_selectParts = [
  82. 'select', 'from', 'join', 'where', 'group', 'having', 'order', 'limit',
  83. 'offset', 'union', 'epilog',
  84. ];
  85. /**
  86. * The list of query clauses to traverse for generating an UPDATE statement
  87. *
  88. * @var string[]
  89. */
  90. protected $_updateParts = ['update', 'set', 'where', 'epilog'];
  91. /**
  92. * The list of query clauses to traverse for generating a DELETE statement
  93. *
  94. * @var string[]
  95. */
  96. protected $_deleteParts = ['delete', 'modifier', 'from', 'where', 'epilog'];
  97. /**
  98. * The list of query clauses to traverse for generating an INSERT statement
  99. *
  100. * @var string[]
  101. */
  102. protected $_insertParts = ['insert', 'values', 'epilog'];
  103. /**
  104. * Indicates whether internal state of this query was changed, this is used to
  105. * discard internal cached objects such as the transformed query or the reference
  106. * to the executed statement.
  107. *
  108. * @var bool
  109. */
  110. protected $_dirty = false;
  111. /**
  112. * A list of callback functions to be called to alter each row from resulting
  113. * statement upon retrieval. Each one of the callback function will receive
  114. * the row array as first argument.
  115. *
  116. * @var callable[]
  117. */
  118. protected $_resultDecorators = [];
  119. /**
  120. * Statement object resulting from executing this query.
  121. *
  122. * @var \Cake\Database\StatementInterface|null
  123. */
  124. protected $_iterator;
  125. /**
  126. * The object responsible for generating query placeholders and temporarily store values
  127. * associated to each of those.
  128. *
  129. * @var \Cake\Database\ValueBinder|null
  130. */
  131. protected $_valueBinder;
  132. /**
  133. * Instance of functions builder object used for generating arbitrary SQL functions.
  134. *
  135. * @var \Cake\Database\FunctionsBuilder|null
  136. */
  137. protected $_functionsBuilder;
  138. /**
  139. * Boolean for tracking whether or not buffered results
  140. * are enabled.
  141. *
  142. * @var bool
  143. */
  144. protected $_useBufferedResults = true;
  145. /**
  146. * The Type map for fields in the select clause
  147. *
  148. * @var \Cake\Database\TypeMap
  149. */
  150. protected $_selectTypeMap;
  151. /**
  152. * Tracking flag to disable casting
  153. *
  154. * @var bool
  155. */
  156. protected $typeCastEnabled = true;
  157. /**
  158. * Constructor.
  159. *
  160. * @param \Cake\Database\Connection $connection The connection
  161. * object to be used for transforming and executing this query
  162. */
  163. public function __construct(Connection $connection)
  164. {
  165. $this->setConnection($connection);
  166. }
  167. /**
  168. * Sets the connection instance to be used for executing and transforming this query.
  169. *
  170. * @param \Cake\Database\Connection $connection Connection instance
  171. * @return $this
  172. */
  173. public function setConnection(Connection $connection)
  174. {
  175. $this->_dirty();
  176. $this->_connection = $connection;
  177. return $this;
  178. }
  179. /**
  180. * Gets the connection instance to be used for executing and transforming this query.
  181. *
  182. * @return \Cake\Database\Connection
  183. */
  184. public function getConnection(): Connection
  185. {
  186. return $this->_connection;
  187. }
  188. /**
  189. * Compiles the SQL representation of this query and executes it using the
  190. * configured connection object. Returns the resulting statement object.
  191. *
  192. * Executing a query internally executes several steps, the first one is
  193. * letting the connection transform this object to fit its particular dialect,
  194. * this might result in generating a different Query object that will be the one
  195. * to actually be executed. Immediately after, literal values are passed to the
  196. * connection so they are bound to the query in a safe way. Finally, the resulting
  197. * statement is decorated with custom objects to execute callbacks for each row
  198. * retrieved if necessary.
  199. *
  200. * Resulting statement is traversable, so it can be used in any loop as you would
  201. * with an array.
  202. *
  203. * This method can be overridden in query subclasses to decorate behavior
  204. * around query execution.
  205. *
  206. * @return \Cake\Database\StatementInterface
  207. */
  208. public function execute(): StatementInterface
  209. {
  210. $statement = $this->_connection->run($this);
  211. $this->_iterator = $this->_decorateStatement($statement);
  212. $this->_dirty = false;
  213. return $this->_iterator;
  214. }
  215. /**
  216. * Executes the SQL of this query and immediately closes the statement before returning the row count of records
  217. * changed.
  218. *
  219. * This method can be used with UPDATE and DELETE queries, but is not recommended for SELECT queries and is not
  220. * used to count records.
  221. *
  222. * ## Example
  223. *
  224. * ```
  225. * $rowCount = $query->update('articles')
  226. * ->set(['published'=>true])
  227. * ->where(['published'=>false])
  228. * ->rowCountAndClose();
  229. * ```
  230. *
  231. * The above example will change the published column to true for all false records, and return the number of
  232. * records that were updated.
  233. *
  234. * @return int
  235. */
  236. public function rowCountAndClose(): int
  237. {
  238. $statement = $this->execute();
  239. try {
  240. return $statement->rowCount();
  241. } finally {
  242. $statement->closeCursor();
  243. }
  244. }
  245. /**
  246. * Returns the SQL representation of this object.
  247. *
  248. * This function will compile this query to make it compatible
  249. * with the SQL dialect that is used by the connection, This process might
  250. * add, remove or alter any query part or internal expression to make it
  251. * executable in the target platform.
  252. *
  253. * The resulting query may have placeholders that will be replaced with the actual
  254. * values when the query is executed, hence it is most suitable to use with
  255. * prepared statements.
  256. *
  257. * @param \Cake\Database\ValueBinder|null $generator A placeholder object that will hold
  258. * associated values for expressions
  259. * @return string
  260. */
  261. public function sql(?ValueBinder $generator = null): string
  262. {
  263. if (!$generator) {
  264. $generator = $this->getValueBinder();
  265. $generator->resetCount();
  266. }
  267. return $this->getConnection()->compileQuery($this, $generator);
  268. }
  269. /**
  270. * Will iterate over every specified part. Traversing functions can aggregate
  271. * results using variables in the closure or instance variables. This function
  272. * is commonly used as a way for traversing all query parts that
  273. * are going to be used for constructing a query.
  274. *
  275. * The callback will receive 2 parameters, the first one is the value of the query
  276. * part that is being iterated and the second the name of such part.
  277. *
  278. * ### Example
  279. * ```
  280. * $query->select(['title'])->from('articles')->traverse(function ($value, $clause) {
  281. * if ($clause === 'select') {
  282. * var_dump($value);
  283. * }
  284. * });
  285. * ```
  286. *
  287. * @param callable $visitor A function or callable to be executed for each part
  288. * @return $this
  289. */
  290. public function traverse($visitor)
  291. {
  292. $parts = array_keys($this->_parts);
  293. foreach ($parts as $name) {
  294. $visitor($this->_parts[$name], $name);
  295. }
  296. return $this;
  297. }
  298. /**
  299. * Will iterate over the provided parts.
  300. *
  301. * Traversing functions can aggregate results using variables in the closure
  302. * or instance variables. This method can be used to traverse a subset of
  303. * query parts in order to render a SQL query.
  304. *
  305. * The callback will receive 2 parameters, the first one is the value of the query
  306. * part that is being iterated and the second the name of such part.
  307. *
  308. * ### Example
  309. *
  310. * ```
  311. * $query->select(['title'])->from('articles')->traverse(function ($value, $clause) {
  312. * if ($clause === 'select') {
  313. * var_dump($value);
  314. * }
  315. * }, ['select', 'from']);
  316. * ```
  317. *
  318. * @param callable $visitor A function or callable to be executed for each part
  319. * @param string[] $parts The list of query parts to traverse
  320. * @return $this
  321. */
  322. public function traverseParts(callable $visitor, array $parts)
  323. {
  324. foreach ($parts as $name) {
  325. $visitor($this->_parts[$name], $name);
  326. }
  327. return $this;
  328. }
  329. /**
  330. * Adds new fields to be returned by a `SELECT` statement when this query is
  331. * executed. Fields can be passed as an array of strings, array of expression
  332. * objects, a single expression or a single string.
  333. *
  334. * If an array is passed, keys will be used to alias fields using the value as the
  335. * real field to be aliased. It is possible to alias strings, Expression objects or
  336. * even other Query objects.
  337. *
  338. * If a callable function is passed, the returning array of the function will
  339. * be used as the list of fields.
  340. *
  341. * By default this function will append any passed argument to the list of fields
  342. * to be selected, unless the second argument is set to true.
  343. *
  344. * ### Examples:
  345. *
  346. * ```
  347. * $query->select(['id', 'title']); // Produces SELECT id, title
  348. * $query->select(['author' => 'author_id']); // Appends author: SELECT id, title, author_id as author
  349. * $query->select('id', true); // Resets the list: SELECT id
  350. * $query->select(['total' => $countQuery]); // SELECT id, (SELECT ...) AS total
  351. * $query->select(function ($query) {
  352. * return ['article_id', 'total' => $query->count('*')];
  353. * })
  354. * ```
  355. *
  356. * By default no fields are selected, if you have an instance of `Cake\ORM\Query` and try to append
  357. * fields you should also call `Cake\ORM\Query::enableAutoFields()` to select the default fields
  358. * from the table.
  359. *
  360. * @param array|\Cake\Database\ExpressionInterface|string|callable $fields fields to be added to the list.
  361. * @param bool $overwrite whether to reset fields with passed list or not
  362. * @return $this
  363. */
  364. public function select($fields = [], bool $overwrite = false)
  365. {
  366. if (!is_string($fields) && is_callable($fields)) {
  367. $fields = $fields($this);
  368. }
  369. if (!is_array($fields)) {
  370. $fields = [$fields];
  371. }
  372. if ($overwrite) {
  373. $this->_parts['select'] = $fields;
  374. } else {
  375. $this->_parts['select'] = array_merge($this->_parts['select'], $fields);
  376. }
  377. $this->_dirty();
  378. $this->_type = 'select';
  379. return $this;
  380. }
  381. /**
  382. * Adds a `DISTINCT` clause to the query to remove duplicates from the result set.
  383. * This clause can only be used for select statements.
  384. *
  385. * If you wish to filter duplicates based of those rows sharing a particular field
  386. * or set of fields, you may pass an array of fields to filter on. Beware that
  387. * this option might not be fully supported in all database systems.
  388. *
  389. * ### Examples:
  390. *
  391. * ```
  392. * // Filters products with the same name and city
  393. * $query->select(['name', 'city'])->from('products')->distinct();
  394. *
  395. * // Filters products in the same city
  396. * $query->distinct(['city']);
  397. * $query->distinct('city');
  398. *
  399. * // Filter products with the same name
  400. * $query->distinct(['name'], true);
  401. * $query->distinct('name', true);
  402. * ```
  403. *
  404. * @param array|\Cake\Database\ExpressionInterface|string|bool $on Enable/disable distinct class
  405. * or list of fields to be filtered on
  406. * @param bool $overwrite whether to reset fields with passed list or not
  407. * @return $this
  408. */
  409. public function distinct($on = [], $overwrite = false)
  410. {
  411. if ($on === []) {
  412. $on = true;
  413. } elseif (is_string($on)) {
  414. $on = [$on];
  415. }
  416. if (is_array($on)) {
  417. $merge = [];
  418. if (is_array($this->_parts['distinct'])) {
  419. $merge = $this->_parts['distinct'];
  420. }
  421. $on = $overwrite ? array_values($on) : array_merge($merge, array_values($on));
  422. }
  423. $this->_parts['distinct'] = $on;
  424. $this->_dirty();
  425. return $this;
  426. }
  427. /**
  428. * Adds a single or multiple `SELECT` modifiers to be used in the `SELECT`.
  429. *
  430. * By default this function will append any passed argument to the list of modifiers
  431. * to be applied, unless the second argument is set to true.
  432. *
  433. * ### Example:
  434. *
  435. * ```
  436. * // Ignore cache query in MySQL
  437. * $query->select(['name', 'city'])->from('products')->modifier('SQL_NO_CACHE');
  438. * // It will produce the SQL: SELECT SQL_NO_CACHE name, city FROM products
  439. *
  440. * // Or with multiple modifiers
  441. * $query->select(['name', 'city'])->from('products')->modifier(['HIGH_PRIORITY', 'SQL_NO_CACHE']);
  442. * // It will produce the SQL: SELECT HIGH_PRIORITY SQL_NO_CACHE name, city FROM products
  443. * ```
  444. *
  445. * @param array|\Cake\Database\ExpressionInterface|string $modifiers modifiers to be applied to the query
  446. * @param bool $overwrite whether to reset order with field list or not
  447. * @return $this
  448. */
  449. public function modifier($modifiers, $overwrite = false)
  450. {
  451. $this->_dirty();
  452. if ($overwrite) {
  453. $this->_parts['modifier'] = [];
  454. }
  455. $this->_parts['modifier'] = array_merge($this->_parts['modifier'], (array)$modifiers);
  456. return $this;
  457. }
  458. /**
  459. * Adds a single or multiple tables to be used in the FROM clause for this query.
  460. * Tables can be passed as an array of strings, array of expression
  461. * objects, a single expression or a single string.
  462. *
  463. * If an array is passed, keys will be used to alias tables using the value as the
  464. * real field to be aliased. It is possible to alias strings, ExpressionInterface objects or
  465. * even other Query objects.
  466. *
  467. * By default this function will append any passed argument to the list of tables
  468. * to be selected from, unless the second argument is set to true.
  469. *
  470. * This method can be used for select, update and delete statements.
  471. *
  472. * ### Examples:
  473. *
  474. * ```
  475. * $query->from(['p' => 'posts']); // Produces FROM posts p
  476. * $query->from('authors'); // Appends authors: FROM posts p, authors
  477. * $query->from(['products'], true); // Resets the list: FROM products
  478. * $query->from(['sub' => $countQuery]); // FROM (SELECT ...) sub
  479. * ```
  480. *
  481. * @param array|string $tables tables to be added to the list. This argument, can be
  482. * passed as an array of strings, array of expression objects, or a single string. See
  483. * the examples above for the valid call types.
  484. * @param bool $overwrite whether to reset tables with passed list or not
  485. * @return $this
  486. */
  487. public function from($tables = [], $overwrite = false)
  488. {
  489. $tables = (array)$tables;
  490. if ($overwrite) {
  491. $this->_parts['from'] = $tables;
  492. } else {
  493. $this->_parts['from'] = array_merge($this->_parts['from'], $tables);
  494. }
  495. $this->_dirty();
  496. return $this;
  497. }
  498. /**
  499. * Adds a single or multiple tables to be used as JOIN clauses to this query.
  500. * Tables can be passed as an array of strings, an array describing the
  501. * join parts, an array with multiple join descriptions, or a single string.
  502. *
  503. * By default this function will append any passed argument to the list of tables
  504. * to be joined, unless the third argument is set to true.
  505. *
  506. * When no join type is specified an `INNER JOIN` is used by default:
  507. * `$query->join(['authors'])` will produce `INNER JOIN authors ON 1 = 1`
  508. *
  509. * It is also possible to alias joins using the array key:
  510. * `$query->join(['a' => 'authors'])` will produce `INNER JOIN authors a ON 1 = 1`
  511. *
  512. * A join can be fully described and aliased using the array notation:
  513. *
  514. * ```
  515. * $query->join([
  516. * 'a' => [
  517. * 'table' => 'authors',
  518. * 'type' => 'LEFT',
  519. * 'conditions' => 'a.id = b.author_id'
  520. * ]
  521. * ]);
  522. * // Produces LEFT JOIN authors a ON a.id = b.author_id
  523. * ```
  524. *
  525. * You can even specify multiple joins in an array, including the full description:
  526. *
  527. * ```
  528. * $query->join([
  529. * 'a' => [
  530. * 'table' => 'authors',
  531. * 'type' => 'LEFT',
  532. * 'conditions' => 'a.id = b.author_id'
  533. * ],
  534. * 'p' => [
  535. * 'table' => 'publishers',
  536. * 'type' => 'INNER',
  537. * 'conditions' => 'p.id = b.publisher_id AND p.name = "Cake Software Foundation"'
  538. * ]
  539. * ]);
  540. * // LEFT JOIN authors a ON a.id = b.author_id
  541. * // INNER JOIN publishers p ON p.id = b.publisher_id AND p.name = "Cake Software Foundation"
  542. * ```
  543. *
  544. * ### Using conditions and types
  545. *
  546. * Conditions can be expressed, as in the examples above, using a string for comparing
  547. * columns, or string with already quoted literal values. Additionally it is
  548. * possible to use conditions expressed in arrays or expression objects.
  549. *
  550. * When using arrays for expressing conditions, it is often desirable to convert
  551. * the literal values to the correct database representation. This is achieved
  552. * using the second parameter of this function.
  553. *
  554. * ```
  555. * $query->join(['a' => [
  556. * 'table' => 'articles',
  557. * 'conditions' => [
  558. * 'a.posted >=' => new DateTime('-3 days'),
  559. * 'a.published' => true,
  560. * 'a.author_id = authors.id'
  561. * ]
  562. * ]], ['a.posted' => 'datetime', 'a.published' => 'boolean'])
  563. * ```
  564. *
  565. * ### Overwriting joins
  566. *
  567. * When creating aliased joins using the array notation, you can override
  568. * previous join definitions by using the same alias in consequent
  569. * calls to this function or you can replace all previously defined joins
  570. * with another list if the third parameter for this function is set to true.
  571. *
  572. * ```
  573. * $query->join(['alias' => 'table']); // joins table with as alias
  574. * $query->join(['alias' => 'another_table']); // joins another_table with as alias
  575. * $query->join(['something' => 'different_table'], [], true); // resets joins list
  576. * ```
  577. *
  578. * @param array|string $tables list of tables to be joined in the query
  579. * @param array $types associative array of type names used to bind values to query
  580. * @param bool $overwrite whether to reset joins with passed list or not
  581. * @see \Cake\Database\Type
  582. * @return $this
  583. */
  584. public function join($tables, $types = [], $overwrite = false)
  585. {
  586. if (is_string($tables) || isset($tables['table'])) {
  587. $tables = [$tables];
  588. }
  589. $joins = [];
  590. $i = count($this->_parts['join']);
  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|\Closure|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|\Closure $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|\Closure|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|\Closure|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|\Closure $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. * @psalm-suppress MoreSpecificImplementedParamType
  1269. */
  1270. public function limit($num)
  1271. {
  1272. $this->_dirty();
  1273. if ($num !== null && !is_object($num)) {
  1274. $num = (int)$num;
  1275. }
  1276. $this->_parts['limit'] = $num;
  1277. return $this;
  1278. }
  1279. /**
  1280. * Sets the number of records that should be skipped from the original result set
  1281. * This is commonly used for paginating large results. Accepts an integer or an
  1282. * expression object that evaluates to an integer.
  1283. *
  1284. * In some databases, this operation might not be supported or will require
  1285. * the query to be transformed in order to limit the result set size.
  1286. *
  1287. * ### Examples
  1288. *
  1289. * ```
  1290. * $query->offset(10) // generates OFFSET 10
  1291. * $query->offset($query->newExpr()->add(['1 + 1'])); // OFFSET (1 + 1)
  1292. * ```
  1293. *
  1294. * @param int|\Cake\Database\ExpressionInterface|null $num number of records to be skipped
  1295. * @return $this
  1296. * @psalm-suppress MoreSpecificImplementedParamType
  1297. */
  1298. public function offset($num)
  1299. {
  1300. $this->_dirty();
  1301. if ($num !== null && !is_object($num)) {
  1302. $num = (int)$num;
  1303. }
  1304. $this->_parts['offset'] = $num;
  1305. return $this;
  1306. }
  1307. /**
  1308. * Adds a complete query to be used in conjunction with an UNION operator with
  1309. * this query. This is used to combine the result set of this query with the one
  1310. * that will be returned by the passed query. You can add as many queries as you
  1311. * required by calling multiple times this method with different queries.
  1312. *
  1313. * By default, the UNION operator will remove duplicate rows, if you wish to include
  1314. * every row for all queries, use unionAll().
  1315. *
  1316. * ### Examples
  1317. *
  1318. * ```
  1319. * $union = (new Query($conn))->select(['id', 'title'])->from(['a' => 'articles']);
  1320. * $query->select(['id', 'name'])->from(['d' => 'things'])->union($union);
  1321. * ```
  1322. *
  1323. * Will produce:
  1324. *
  1325. * `SELECT id, name FROM things d UNION SELECT id, title FROM articles a`
  1326. *
  1327. * @param string|\Cake\Database\Query $query full SQL query to be used in UNION operator
  1328. * @param bool $overwrite whether to reset the list of queries to be operated or not
  1329. * @return $this
  1330. */
  1331. public function union($query, $overwrite = false)
  1332. {
  1333. if ($overwrite) {
  1334. $this->_parts['union'] = [];
  1335. }
  1336. $this->_parts['union'][] = [
  1337. 'all' => false,
  1338. 'query' => $query,
  1339. ];
  1340. $this->_dirty();
  1341. return $this;
  1342. }
  1343. /**
  1344. * Adds a complete query to be used in conjunction with the UNION ALL operator with
  1345. * this query. This is used to combine the result set of this query with the one
  1346. * that will be returned by the passed query. You can add as many queries as you
  1347. * required by calling multiple times this method with different queries.
  1348. *
  1349. * Unlike UNION, UNION ALL will not remove duplicate rows.
  1350. *
  1351. * ```
  1352. * $union = (new Query($conn))->select(['id', 'title'])->from(['a' => 'articles']);
  1353. * $query->select(['id', 'name'])->from(['d' => 'things'])->unionAll($union);
  1354. * ```
  1355. *
  1356. * Will produce:
  1357. *
  1358. * `SELECT id, name FROM things d UNION ALL SELECT id, title FROM articles a`
  1359. *
  1360. * @param string|\Cake\Database\Query $query full SQL query to be used in UNION operator
  1361. * @param bool $overwrite whether to reset the list of queries to be operated or not
  1362. * @return $this
  1363. */
  1364. public function unionAll($query, $overwrite = false)
  1365. {
  1366. if ($overwrite) {
  1367. $this->_parts['union'] = [];
  1368. }
  1369. $this->_parts['union'][] = [
  1370. 'all' => true,
  1371. 'query' => $query,
  1372. ];
  1373. $this->_dirty();
  1374. return $this;
  1375. }
  1376. /**
  1377. * Create an insert query.
  1378. *
  1379. * Note calling this method will reset any data previously set
  1380. * with Query::values().
  1381. *
  1382. * @param array $columns The columns to insert into.
  1383. * @param string[] $types A map between columns & their datatypes.
  1384. * @return $this
  1385. * @throws \RuntimeException When there are 0 columns.
  1386. */
  1387. public function insert(array $columns, array $types = [])
  1388. {
  1389. if (empty($columns)) {
  1390. throw new RuntimeException('At least 1 column is required to perform an insert.');
  1391. }
  1392. $this->_dirty();
  1393. $this->_type = 'insert';
  1394. $this->_parts['insert'][1] = $columns;
  1395. if (!$this->_parts['values']) {
  1396. $this->_parts['values'] = new ValuesExpression($columns, $this->getTypeMap()->setTypes($types));
  1397. } else {
  1398. $this->_parts['values']->setColumns($columns);
  1399. }
  1400. return $this;
  1401. }
  1402. /**
  1403. * Set the table name for insert queries.
  1404. *
  1405. * @param string $table The table name to insert into.
  1406. * @return $this
  1407. */
  1408. public function into(string $table)
  1409. {
  1410. $this->_dirty();
  1411. $this->_type = 'insert';
  1412. $this->_parts['insert'][0] = $table;
  1413. return $this;
  1414. }
  1415. /**
  1416. * Creates an expression that refers to an identifier. Identifiers are used to refer to field names and allow
  1417. * the SQL compiler to apply quotes or escape the identifier.
  1418. *
  1419. * The value is used as is, and you might be required to use aliases or include the table reference in
  1420. * the identifier. Do not use this method to inject SQL methods or logical statements.
  1421. *
  1422. * ### Example
  1423. *
  1424. * ```
  1425. * $query->newExpr()->lte('count', $query->identifier('total'));
  1426. * ```
  1427. *
  1428. * @param string $identifier The identifier for an expression
  1429. * @return \Cake\Database\ExpressionInterface
  1430. */
  1431. public function identifier(string $identifier): ExpressionInterface
  1432. {
  1433. return new IdentifierExpression($identifier);
  1434. }
  1435. /**
  1436. * Set the values for an insert query.
  1437. *
  1438. * Multi inserts can be performed by calling values() more than one time,
  1439. * or by providing an array of value sets. Additionally $data can be a Query
  1440. * instance to insert data from another SELECT statement.
  1441. *
  1442. * @param array|\Cake\Database\Query|\Cake\Database\Expression\ValuesExpression $data The data to insert.
  1443. * @return $this
  1444. * @throws \Cake\Database\Exception if you try to set values before declaring columns.
  1445. * Or if you try to set values on non-insert queries.
  1446. */
  1447. public function values($data)
  1448. {
  1449. if ($this->_type !== 'insert') {
  1450. throw new Exception(
  1451. 'You cannot add values before defining columns to use.'
  1452. );
  1453. }
  1454. if (empty($this->_parts['insert'])) {
  1455. throw new Exception(
  1456. 'You cannot add values before defining columns to use.'
  1457. );
  1458. }
  1459. $this->_dirty();
  1460. if ($data instanceof ValuesExpression) {
  1461. $this->_parts['values'] = $data;
  1462. return $this;
  1463. }
  1464. $this->_parts['values']->add($data);
  1465. return $this;
  1466. }
  1467. /**
  1468. * Create an update query.
  1469. *
  1470. * Can be combined with set() and where() methods to create update queries.
  1471. *
  1472. * @param string|\Cake\Database\ExpressionInterface $table The table you want to update.
  1473. * @return $this
  1474. */
  1475. public function update($table)
  1476. {
  1477. if (!is_string($table) && !($table instanceof ExpressionInterface)) {
  1478. $text = 'Table must be of type string or "%s", got "%s"';
  1479. $message = sprintf($text, ExpressionInterface::class, gettype($table));
  1480. throw new InvalidArgumentException($message);
  1481. }
  1482. $this->_dirty();
  1483. $this->_type = 'update';
  1484. $this->_parts['update'][0] = $table;
  1485. return $this;
  1486. }
  1487. /**
  1488. * Set one or many fields to update.
  1489. *
  1490. * ### Examples
  1491. *
  1492. * Passing a string:
  1493. *
  1494. * ```
  1495. * $query->update('articles')->set('title', 'The Title');
  1496. * ```
  1497. *
  1498. * Passing an array:
  1499. *
  1500. * ```
  1501. * $query->update('articles')->set(['title' => 'The Title'], ['title' => 'string']);
  1502. * ```
  1503. *
  1504. * Passing a callable:
  1505. *
  1506. * ```
  1507. * $query->update('articles')->set(function ($exp) {
  1508. * return $exp->eq('title', 'The title', 'string');
  1509. * });
  1510. * ```
  1511. *
  1512. * @param string|array|\Closure|\Cake\Database\Expression\QueryExpression $key The column name or array of keys
  1513. * + values to set. This can also be a QueryExpression containing a SQL fragment.
  1514. * It can also be a Closure, that is required to return an expression object.
  1515. * @param mixed $value The value to update $key to. Can be null if $key is an
  1516. * array or QueryExpression. When $key is an array, this parameter will be
  1517. * used as $types instead.
  1518. * @param array|string $types The column types to treat data as.
  1519. * @return $this
  1520. */
  1521. public function set($key, $value = null, $types = [])
  1522. {
  1523. if (empty($this->_parts['set'])) {
  1524. $this->_parts['set'] = $this->newExpr()->setConjunction(',');
  1525. }
  1526. if ($key instanceof Closure) {
  1527. $exp = $this->newExpr()->setConjunction(',');
  1528. $this->_parts['set']->add($key($exp));
  1529. return $this;
  1530. }
  1531. if (is_array($key) || $key instanceof ExpressionInterface) {
  1532. $types = (array)$value;
  1533. $this->_parts['set']->add($key, $types);
  1534. return $this;
  1535. }
  1536. if (!is_string($types)) {
  1537. $types = null;
  1538. }
  1539. $this->_parts['set']->eq($key, $value, $types);
  1540. return $this;
  1541. }
  1542. /**
  1543. * Create a delete query.
  1544. *
  1545. * Can be combined with from(), where() and other methods to
  1546. * create delete queries with specific conditions.
  1547. *
  1548. * @param string|null $table The table to use when deleting.
  1549. * @return $this
  1550. */
  1551. public function delete(?string $table = null)
  1552. {
  1553. $this->_dirty();
  1554. $this->_type = 'delete';
  1555. if ($table !== null) {
  1556. $this->from($table);
  1557. }
  1558. return $this;
  1559. }
  1560. /**
  1561. * A string or expression that will be appended to the generated query
  1562. *
  1563. * ### Examples:
  1564. * ```
  1565. * $query->select('id')->where(['author_id' => 1])->epilog('FOR UPDATE');
  1566. * $query
  1567. * ->insert('articles', ['title'])
  1568. * ->values(['author_id' => 1])
  1569. * ->epilog('RETURNING id');
  1570. * ```
  1571. *
  1572. * Epliog content is raw SQL and not suitable for use with user supplied data.
  1573. *
  1574. * @param string|\Cake\Database\Expression\QueryExpression|null $expression The expression to be appended
  1575. * @return $this
  1576. */
  1577. public function epilog($expression = null)
  1578. {
  1579. $this->_dirty();
  1580. $this->_parts['epilog'] = $expression;
  1581. return $this;
  1582. }
  1583. /**
  1584. * Returns the type of this query (select, insert, update, delete)
  1585. *
  1586. * @return string
  1587. */
  1588. public function type(): string
  1589. {
  1590. return $this->_type;
  1591. }
  1592. /**
  1593. * Returns a new QueryExpression object. This is a handy function when
  1594. * building complex queries using a fluent interface. You can also override
  1595. * this function in subclasses to use a more specialized QueryExpression class
  1596. * if required.
  1597. *
  1598. * You can optionally pass a single raw SQL string or an array or expressions in
  1599. * any format accepted by \Cake\Database\Expression\QueryExpression:
  1600. *
  1601. * ```
  1602. * $expression = $query->newExpr(); // Returns an empty expression object
  1603. * $expression = $query->newExpr('Table.column = Table2.column'); // Return a raw SQL expression
  1604. * ```
  1605. *
  1606. * @param mixed $rawExpression A string, array or anything you want wrapped in an expression object
  1607. * @return \Cake\Database\Expression\QueryExpression
  1608. */
  1609. public function newExpr($rawExpression = null): QueryExpression
  1610. {
  1611. $expression = new QueryExpression([], $this->getTypeMap());
  1612. if ($rawExpression !== null) {
  1613. $expression->add($rawExpression);
  1614. }
  1615. return $expression;
  1616. }
  1617. /**
  1618. * Returns an instance of a functions builder object that can be used for
  1619. * generating arbitrary SQL functions.
  1620. *
  1621. * ### Example:
  1622. *
  1623. * ```
  1624. * $query->func()->count('*');
  1625. * $query->func()->dateDiff(['2012-01-05', '2012-01-02'])
  1626. * ```
  1627. *
  1628. * @return \Cake\Database\FunctionsBuilder
  1629. */
  1630. public function func(): FunctionsBuilder
  1631. {
  1632. if ($this->_functionsBuilder === null) {
  1633. $this->_functionsBuilder = new FunctionsBuilder();
  1634. }
  1635. return $this->_functionsBuilder;
  1636. }
  1637. /**
  1638. * Executes this query and returns a results iterator. This function is required
  1639. * for implementing the IteratorAggregate interface and allows the query to be
  1640. * iterated without having to call execute() manually, thus making it look like
  1641. * a result set instead of the query itself.
  1642. *
  1643. * @return \Cake\Database\StatementInterface
  1644. * @psalm-suppress ImplementedReturnTypeMismatch
  1645. */
  1646. public function getIterator()
  1647. {
  1648. if ($this->_iterator === null || $this->_dirty) {
  1649. $this->_iterator = $this->execute();
  1650. }
  1651. return $this->_iterator;
  1652. }
  1653. /**
  1654. * Returns any data that was stored in the specified clause. This is useful for
  1655. * modifying any internal part of the query and it is used by the SQL dialects
  1656. * to transform the query accordingly before it is executed. The valid clauses that
  1657. * can be retrieved are: delete, update, set, insert, values, select, distinct,
  1658. * from, join, set, where, group, having, order, limit, offset and union.
  1659. *
  1660. * The return value for each of those parts may vary. Some clauses use QueryExpression
  1661. * to internally store their state, some use arrays and others may use booleans or
  1662. * integers. This is summary of the return types for each clause.
  1663. *
  1664. * - update: string The name of the table to update
  1665. * - set: QueryExpression
  1666. * - insert: array, will return an array containing the table + columns.
  1667. * - values: ValuesExpression
  1668. * - select: array, will return empty array when no fields are set
  1669. * - distinct: boolean
  1670. * - from: array of tables
  1671. * - join: array
  1672. * - set: array
  1673. * - where: QueryExpression, returns null when not set
  1674. * - group: array
  1675. * - having: QueryExpression, returns null when not set
  1676. * - order: OrderByExpression, returns null when not set
  1677. * - limit: integer or QueryExpression, null when not set
  1678. * - offset: integer or QueryExpression, null when not set
  1679. * - union: array
  1680. *
  1681. * @param string $name name of the clause to be returned
  1682. * @return mixed
  1683. * @throws \InvalidArgumentException When the named clause does not exist.
  1684. */
  1685. public function clause(string $name)
  1686. {
  1687. if (!array_key_exists($name, $this->_parts)) {
  1688. $clauses = implode(', ', array_keys($this->_parts));
  1689. throw new InvalidArgumentException("The '$name' clause is not defined. Valid clauses are: $clauses");
  1690. }
  1691. return $this->_parts[$name];
  1692. }
  1693. /**
  1694. * Registers a callback to be executed for each result that is fetched from the
  1695. * result set, the callback function will receive as first parameter an array with
  1696. * the raw data from the database for every row that is fetched and must return the
  1697. * row with any possible modifications.
  1698. *
  1699. * Callbacks will be executed lazily, if only 3 rows are fetched for database it will
  1700. * called 3 times, event though there might be more rows to be fetched in the cursor.
  1701. *
  1702. * Callbacks are stacked in the order they are registered, if you wish to reset the stack
  1703. * the call this function with the second parameter set to true.
  1704. *
  1705. * If you wish to remove all decorators from the stack, set the first parameter
  1706. * to null and the second to true.
  1707. *
  1708. * ### Example
  1709. *
  1710. * ```
  1711. * $query->decorateResults(function ($row) {
  1712. * $row['order_total'] = $row['subtotal'] + ($row['subtotal'] * $row['tax']);
  1713. * return $row;
  1714. * });
  1715. * ```
  1716. *
  1717. * @param callable|null $callback The callback to invoke when results are fetched.
  1718. * @param bool $overwrite Whether or not this should append or replace all existing decorators.
  1719. * @return $this
  1720. */
  1721. public function decorateResults(?callable $callback, bool $overwrite = false)
  1722. {
  1723. if ($overwrite) {
  1724. $this->_resultDecorators = [];
  1725. }
  1726. if ($callback !== null) {
  1727. $this->_resultDecorators[] = $callback;
  1728. }
  1729. return $this;
  1730. }
  1731. /**
  1732. * This function works similar to the traverse() function, with the difference
  1733. * that it does a full depth traversal of the entire expression tree. This will execute
  1734. * the provided callback function for each ExpressionInterface object that is
  1735. * stored inside this query at any nesting depth in any part of the query.
  1736. *
  1737. * Callback will receive as first parameter the currently visited expression.
  1738. *
  1739. * @param callable $callback the function to be executed for each ExpressionInterface
  1740. * found inside this query.
  1741. * @return $this
  1742. */
  1743. public function traverseExpressions(callable $callback)
  1744. {
  1745. $visitor = function ($expression) use (&$visitor, $callback) {
  1746. if (is_array($expression)) {
  1747. foreach ($expression as $e) {
  1748. $visitor($e);
  1749. }
  1750. return null;
  1751. }
  1752. if ($expression instanceof ExpressionInterface) {
  1753. $expression->traverse($visitor);
  1754. if (!($expression instanceof self)) {
  1755. $callback($expression);
  1756. }
  1757. }
  1758. };
  1759. return $this->traverse($visitor);
  1760. }
  1761. /**
  1762. * Associates a query placeholder to a value and a type.
  1763. *
  1764. * ```
  1765. * $query->bind(':id', 1, 'integer');
  1766. * ```
  1767. *
  1768. * @param string|int $param placeholder to be replaced with quoted version
  1769. * of $value
  1770. * @param mixed $value The value to be bound
  1771. * @param string|int|null $type the mapped type name, used for casting when sending
  1772. * to database
  1773. * @return $this
  1774. */
  1775. public function bind($param, $value, $type = null)
  1776. {
  1777. $this->getValueBinder()->bind($param, $value, $type);
  1778. return $this;
  1779. }
  1780. /**
  1781. * Returns the currently used ValueBinder instance.
  1782. *
  1783. * A ValueBinder is responsible for generating query placeholders and temporarily
  1784. * associate values to those placeholders so that they can be passed correctly
  1785. * to the statement object.
  1786. *
  1787. * @return \Cake\Database\ValueBinder
  1788. */
  1789. public function getValueBinder(): ValueBinder
  1790. {
  1791. if ($this->_valueBinder === null) {
  1792. $this->_valueBinder = new ValueBinder();
  1793. }
  1794. return $this->_valueBinder;
  1795. }
  1796. /**
  1797. * Overwrite the current value binder
  1798. *
  1799. * A ValueBinder is responsible for generating query placeholders and temporarily
  1800. * associate values to those placeholders so that they can be passed correctly
  1801. * to the statement object.
  1802. *
  1803. * @param \Cake\Database\ValueBinder|null $binder The binder or null to disable binding.
  1804. * @return $this
  1805. */
  1806. public function setValueBinder(?ValueBinder $binder)
  1807. {
  1808. $this->_valueBinder = $binder;
  1809. return $this;
  1810. }
  1811. /**
  1812. * Enables/Disables buffered results.
  1813. *
  1814. * When enabled the results returned by this Query will be
  1815. * buffered. This enables you to iterate a result set multiple times, or
  1816. * both cache and iterate it.
  1817. *
  1818. * When disabled it will consume less memory as fetched results are not
  1819. * remembered for future iterations.
  1820. *
  1821. * @param bool $enable Whether or not to enable buffering
  1822. * @return $this
  1823. */
  1824. public function enableBufferedResults(bool $enable = true)
  1825. {
  1826. $this->_dirty();
  1827. $this->_useBufferedResults = (bool)$enable;
  1828. return $this;
  1829. }
  1830. /**
  1831. * Disables buffered results.
  1832. *
  1833. * Disabling buffering will consume less memory as fetched results are not
  1834. * remembered for future iterations.
  1835. *
  1836. * @return $this
  1837. */
  1838. public function disableBufferedResults()
  1839. {
  1840. $this->_dirty();
  1841. $this->_useBufferedResults = false;
  1842. return $this;
  1843. }
  1844. /**
  1845. * Returns whether buffered results are enabled/disabled.
  1846. *
  1847. * When enabled the results returned by this Query will be
  1848. * buffered. This enables you to iterate a result set multiple times, or
  1849. * both cache and iterate it.
  1850. *
  1851. * When disabled it will consume less memory as fetched results are not
  1852. * remembered for future iterations.
  1853. *
  1854. * @return bool
  1855. */
  1856. public function isBufferedResultsEnabled(): bool
  1857. {
  1858. return $this->_useBufferedResults;
  1859. }
  1860. /**
  1861. * Sets the TypeMap class where the types for each of the fields in the
  1862. * select clause are stored.
  1863. *
  1864. * @param \Cake\Database\TypeMap $typeMap The map object to use
  1865. * @return $this
  1866. */
  1867. public function setSelectTypeMap(TypeMap $typeMap)
  1868. {
  1869. $this->_selectTypeMap = $typeMap;
  1870. $this->_dirty();
  1871. return $this;
  1872. }
  1873. /**
  1874. * Gets the TypeMap class where the types for each of the fields in the
  1875. * select clause are stored.
  1876. *
  1877. * @return \Cake\Database\TypeMap
  1878. */
  1879. public function getSelectTypeMap(): TypeMap
  1880. {
  1881. if ($this->_selectTypeMap === null) {
  1882. $this->_selectTypeMap = new TypeMap();
  1883. }
  1884. return $this->_selectTypeMap;
  1885. }
  1886. /**
  1887. * Disables the automatic casting of fields to their corresponding PHP data type
  1888. *
  1889. * @return $this
  1890. */
  1891. public function disableResultsCasting()
  1892. {
  1893. $this->typeCastEnabled = false;
  1894. return $this;
  1895. }
  1896. /**
  1897. * Enables the automatic casting of fields to their corresponding type
  1898. *
  1899. * @return $this
  1900. */
  1901. public function enableResultsCasting()
  1902. {
  1903. $this->typeCastEnabled = true;
  1904. return $this;
  1905. }
  1906. /**
  1907. * Auxiliary function used to wrap the original statement from the driver with
  1908. * any registered callbacks.
  1909. *
  1910. * @param \Cake\Database\StatementInterface $statement to be decorated
  1911. * @return \Cake\Database\Statement\CallbackStatement|\Cake\Database\StatementInterface
  1912. */
  1913. protected function _decorateStatement(StatementInterface $statement)
  1914. {
  1915. $typeMap = $this->getSelectTypeMap();
  1916. $driver = $this->getConnection()->getDriver();
  1917. if ($this->typeCastEnabled && $typeMap->toArray()) {
  1918. $statement = new CallbackStatement($statement, $driver, new FieldTypeConverter($typeMap, $driver));
  1919. }
  1920. foreach ($this->_resultDecorators as $f) {
  1921. $statement = new CallbackStatement($statement, $driver, $f);
  1922. }
  1923. return $statement;
  1924. }
  1925. /**
  1926. * Helper function used to build conditions by composing QueryExpression objects.
  1927. *
  1928. * @param string $part Name of the query part to append the new part to
  1929. * @param string|array|\Cake\Database\ExpressionInterface|\Closure|null $append Expression or builder function to append.
  1930. * to append.
  1931. * @param string $conjunction type of conjunction to be used to operate part
  1932. * @param array $types associative array of type names used to bind values to query
  1933. * @return void
  1934. */
  1935. protected function _conjugate(string $part, $append, $conjunction, array $types): void
  1936. {
  1937. $expression = $this->_parts[$part] ?: $this->newExpr();
  1938. if (empty($append)) {
  1939. $this->_parts[$part] = $expression;
  1940. return;
  1941. }
  1942. if ($append instanceof Closure) {
  1943. $append = $append($this->newExpr(), $this);
  1944. }
  1945. if ($expression->getConjunction() === $conjunction) {
  1946. $expression->add($append, $types);
  1947. } else {
  1948. $expression = $this->newExpr()
  1949. ->setConjunction($conjunction)
  1950. ->add([$expression, $append], $types);
  1951. }
  1952. $this->_parts[$part] = $expression;
  1953. $this->_dirty();
  1954. }
  1955. /**
  1956. * Marks a query as dirty, removing any preprocessed information
  1957. * from in memory caching.
  1958. *
  1959. * @return void
  1960. */
  1961. protected function _dirty(): void
  1962. {
  1963. $this->_dirty = true;
  1964. if ($this->_iterator && $this->_valueBinder) {
  1965. $this->getValueBinder()->reset();
  1966. }
  1967. }
  1968. /**
  1969. * Do a deep clone on this object.
  1970. *
  1971. * Will clone all of the expression objects used in
  1972. * each of the clauses, as well as the valueBinder.
  1973. *
  1974. * @return void
  1975. */
  1976. public function __clone()
  1977. {
  1978. $this->_iterator = null;
  1979. if ($this->_valueBinder !== null) {
  1980. $this->_valueBinder = clone $this->_valueBinder;
  1981. }
  1982. if ($this->_selectTypeMap !== null) {
  1983. $this->_selectTypeMap = clone $this->_selectTypeMap;
  1984. }
  1985. foreach ($this->_parts as $name => $part) {
  1986. if (empty($part)) {
  1987. continue;
  1988. }
  1989. if (is_array($part)) {
  1990. foreach ($part as $i => $piece) {
  1991. if ($piece instanceof ExpressionInterface) {
  1992. $this->_parts[$name][$i] = clone $piece;
  1993. }
  1994. }
  1995. }
  1996. if ($part instanceof ExpressionInterface) {
  1997. $this->_parts[$name] = clone $part;
  1998. }
  1999. }
  2000. }
  2001. /**
  2002. * Returns string representation of this query (complete SQL statement).
  2003. *
  2004. * @return string
  2005. */
  2006. public function __toString(): string
  2007. {
  2008. return $this->sql();
  2009. }
  2010. /**
  2011. * Returns an array that can be used to describe the internal state of this
  2012. * object.
  2013. *
  2014. * @return array
  2015. */
  2016. public function __debugInfo(): array
  2017. {
  2018. try {
  2019. set_error_handler(function ($errno, $errstr) {
  2020. throw new RuntimeException($errstr, $errno);
  2021. }, E_ALL);
  2022. $sql = $this->sql();
  2023. $params = $this->getValueBinder()->bindings();
  2024. } catch (RuntimeException $e) {
  2025. $sql = 'SQL could not be generated for this query as it is incomplete.';
  2026. $params = [];
  2027. } finally {
  2028. restore_error_handler();
  2029. }
  2030. return [
  2031. '(help)' => 'This is a Query object, to get the results execute or iterate it.',
  2032. 'sql' => $sql,
  2033. 'params' => $params,
  2034. 'defaultTypes' => $this->getDefaultTypes(),
  2035. 'decorators' => count($this->_resultDecorators),
  2036. 'executed' => $this->_iterator ? true : false,
  2037. ];
  2038. }
  2039. }