Query.php 74 KB

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