Query.php 72 KB

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