Query.php 70 KB

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