Query.php 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359
  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 disable casting
  122. *
  123. * @var bool
  124. */
  125. protected $typeCastEnabled = true;
  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. $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 string[] $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. deprecationWarning('Using Query::from() to read state is deprecated. Use clause("from") instead.');
  449. return $this->_parts['from'];
  450. }
  451. $tables = (array)$tables;
  452. if ($overwrite) {
  453. $this->_parts['from'] = $tables;
  454. } else {
  455. $this->_parts['from'] = array_merge($this->_parts['from'], $tables);
  456. }
  457. $this->_dirty();
  458. return $this;
  459. }
  460. /**
  461. * Adds a single or multiple tables to be used as JOIN clauses to this query.
  462. * Tables can be passed as an array of strings, an array describing the
  463. * join parts, an array with multiple join descriptions, or a single string.
  464. *
  465. * By default this function will append any passed argument to the list of tables
  466. * to be joined, unless the third argument is set to true.
  467. *
  468. * When no join type is specified an `INNER JOIN` is used by default:
  469. * `$query->join(['authors'])` will produce `INNER JOIN authors ON 1 = 1`
  470. *
  471. * It is also possible to alias joins using the array key:
  472. * `$query->join(['a' => 'authors'])` will produce `INNER JOIN authors a ON 1 = 1`
  473. *
  474. * A join can be fully described and aliased using the array notation:
  475. *
  476. * ```
  477. * $query->join([
  478. * 'a' => [
  479. * 'table' => 'authors',
  480. * 'type' => 'LEFT',
  481. * 'conditions' => 'a.id = b.author_id'
  482. * ]
  483. * ]);
  484. * // Produces LEFT JOIN authors a ON a.id = b.author_id
  485. * ```
  486. *
  487. * You can even specify multiple joins in an array, including the full description:
  488. *
  489. * ```
  490. * $query->join([
  491. * 'a' => [
  492. * 'table' => 'authors',
  493. * 'type' => 'LEFT',
  494. * 'conditions' => 'a.id = b.author_id'
  495. * ],
  496. * 'p' => [
  497. * 'table' => 'publishers',
  498. * 'type' => 'INNER',
  499. * 'conditions' => 'p.id = b.publisher_id AND p.name = "Cake Software Foundation"'
  500. * ]
  501. * ]);
  502. * // LEFT JOIN authors a ON a.id = b.author_id
  503. * // INNER JOIN publishers p ON p.id = b.publisher_id AND p.name = "Cake Software Foundation"
  504. * ```
  505. *
  506. * ### Using conditions and types
  507. *
  508. * Conditions can be expressed, as in the examples above, using a string for comparing
  509. * columns, or string with already quoted literal values. Additionally it is
  510. * possible to use conditions expressed in arrays or expression objects.
  511. *
  512. * When using arrays for expressing conditions, it is often desirable to convert
  513. * the literal values to the correct database representation. This is achieved
  514. * using the second parameter of this function.
  515. *
  516. * ```
  517. * $query->join(['a' => [
  518. * 'table' => 'articles',
  519. * 'conditions' => [
  520. * 'a.posted >=' => new DateTime('-3 days'),
  521. * 'a.published' => true,
  522. * 'a.author_id = authors.id'
  523. * ]
  524. * ]], ['a.posted' => 'datetime', 'a.published' => 'boolean'])
  525. * ```
  526. *
  527. * ### Overwriting joins
  528. *
  529. * When creating aliased joins using the array notation, you can override
  530. * previous join definitions by using the same alias in consequent
  531. * calls to this function or you can replace all previously defined joins
  532. * with another list if the third parameter for this function is set to true.
  533. *
  534. * ```
  535. * $query->join(['alias' => 'table']); // joins table with as alias
  536. * $query->join(['alias' => 'another_table']); // joins another_table with as alias
  537. * $query->join(['something' => 'different_table'], [], true); // resets joins list
  538. * ```
  539. *
  540. * @param array|string|null $tables list of tables to be joined in the query
  541. * @param array $types associative array of type names used to bind values to query
  542. * @param bool $overwrite whether to reset joins with passed list or not
  543. * @see \Cake\Database\Type
  544. * @return $this|array
  545. */
  546. public function join($tables = null, $types = [], $overwrite = false)
  547. {
  548. if ($tables === null) {
  549. deprecationWarning('Using Query::join() to read state is deprecated. Use clause("join") instead.');
  550. return $this->_parts['join'];
  551. }
  552. if (is_string($tables) || isset($tables['table'])) {
  553. $tables = [$tables];
  554. }
  555. $joins = [];
  556. $i = count($this->_parts['join']);
  557. foreach ($tables as $alias => $t) {
  558. if (!is_array($t)) {
  559. $t = ['table' => $t, 'conditions' => $this->newExpr()];
  560. }
  561. if (!is_string($t['conditions']) && is_callable($t['conditions'])) {
  562. $t['conditions'] = $t['conditions']($this->newExpr(), $this);
  563. }
  564. if (!($t['conditions'] instanceof ExpressionInterface)) {
  565. $t['conditions'] = $this->newExpr()->add($t['conditions'], $types);
  566. }
  567. $alias = is_string($alias) ? $alias : null;
  568. $joins[$alias ?: $i++] = $t + ['type' => QueryInterface::JOIN_TYPE_INNER, 'alias' => $alias];
  569. }
  570. if ($overwrite) {
  571. $this->_parts['join'] = $joins;
  572. } else {
  573. $this->_parts['join'] = array_merge($this->_parts['join'], $joins);
  574. }
  575. $this->_dirty();
  576. return $this;
  577. }
  578. /**
  579. * Remove a join if it has been defined.
  580. *
  581. * Useful when you are redefining joins or want to re-order
  582. * the join clauses.
  583. *
  584. * @param string $name The alias/name of the join to remove.
  585. * @return $this
  586. */
  587. public function removeJoin($name)
  588. {
  589. unset($this->_parts['join'][$name]);
  590. $this->_dirty();
  591. return $this;
  592. }
  593. /**
  594. * Adds a single `LEFT JOIN` clause to the query.
  595. *
  596. * This is a shorthand method for building joins via `join()`.
  597. *
  598. * The table name can be passed as a string, or as an array in case it needs to
  599. * be aliased:
  600. *
  601. * ```
  602. * // LEFT JOIN authors ON authors.id = posts.author_id
  603. * $query->leftJoin('authors', 'authors.id = posts.author_id');
  604. *
  605. * // LEFT JOIN authors a ON a.id = posts.author_id
  606. * $query->leftJoin(['a' => 'authors'], 'a.id = posts.author_id');
  607. * ```
  608. *
  609. * Conditions can be passed as strings, arrays, or expression objects. When
  610. * using arrays it is possible to combine them with the `$types` parameter
  611. * in order to define how to convert the values:
  612. *
  613. * ```
  614. * $query->leftJoin(['a' => 'articles'], [
  615. * 'a.posted >=' => new DateTime('-3 days'),
  616. * 'a.published' => true,
  617. * 'a.author_id = authors.id'
  618. * ], ['a.posted' => 'datetime', 'a.published' => 'boolean']);
  619. * ```
  620. *
  621. * See `join()` for further details on conditions and types.
  622. *
  623. * @param string|array $table The table to join with
  624. * @param string|array|\Cake\Database\ExpressionInterface $conditions The conditions
  625. * to use for joining.
  626. * @param array $types a list of types associated to the conditions used for converting
  627. * values to the corresponding database representation.
  628. * @return $this
  629. */
  630. public function leftJoin($table, $conditions = [], $types = [])
  631. {
  632. return $this->join($this->_makeJoin($table, $conditions, QueryInterface::JOIN_TYPE_LEFT), $types);
  633. }
  634. /**
  635. * Adds a single `RIGHT JOIN` clause to the query.
  636. *
  637. * This is a shorthand method for building joins via `join()`.
  638. *
  639. * The arguments of this method are identical to the `leftJoin()` shorthand, please refer
  640. * to that methods description for further details.
  641. *
  642. * @param string|array $table The table to join with
  643. * @param string|array|\Cake\Database\ExpressionInterface $conditions The conditions
  644. * to use for joining.
  645. * @param array $types a list of types associated to the conditions used for converting
  646. * values to the corresponding database representation.
  647. * @return $this
  648. */
  649. public function rightJoin($table, $conditions = [], $types = [])
  650. {
  651. return $this->join($this->_makeJoin($table, $conditions, QueryInterface::JOIN_TYPE_RIGHT), $types);
  652. }
  653. /**
  654. * Adds a single `INNER JOIN` clause to the query.
  655. *
  656. * This is a shorthand method for building joins via `join()`.
  657. *
  658. * The arguments of this method are identical to the `leftJoin()` shorthand, please refer
  659. * to that methods description for further details.
  660. *
  661. * @param string|array $table The table to join with
  662. * @param string|array|\Cake\Database\ExpressionInterface $conditions The conditions
  663. * to use for joining.
  664. * @param array $types a list of types associated to the conditions used for converting
  665. * values to the corresponding database representation.
  666. * @return $this
  667. */
  668. public function innerJoin($table, $conditions = [], $types = [])
  669. {
  670. return $this->join($this->_makeJoin($table, $conditions, QueryInterface::JOIN_TYPE_INNER), $types);
  671. }
  672. /**
  673. * Returns an array that can be passed to the join method describing a single join clause
  674. *
  675. * @param string|array $table The table to join with
  676. * @param string|array|\Cake\Database\ExpressionInterface $conditions The conditions
  677. * to use for joining.
  678. * @param string $type the join type to use
  679. * @return array
  680. */
  681. protected function _makeJoin($table, $conditions, $type)
  682. {
  683. $alias = $table;
  684. if (is_array($table)) {
  685. $alias = key($table);
  686. $table = current($table);
  687. }
  688. return [
  689. $alias => [
  690. 'table' => $table,
  691. 'conditions' => $conditions,
  692. 'type' => $type
  693. ]
  694. ];
  695. }
  696. /**
  697. * Adds a condition or set of conditions to be used in the WHERE clause for this
  698. * query. Conditions can be expressed as an array of fields as keys with
  699. * comparison operators in it, the values for the array will be used for comparing
  700. * the field to such literal. Finally, conditions can be expressed as a single
  701. * string or an array of strings.
  702. *
  703. * When using arrays, each entry will be joined to the rest of the conditions using
  704. * an `AND` operator. Consecutive calls to this function will also join the new
  705. * conditions specified using the AND operator. Additionally, values can be
  706. * expressed using expression objects which can include other query objects.
  707. *
  708. * Any conditions created with this methods can be used with any `SELECT`, `UPDATE`
  709. * and `DELETE` type of queries.
  710. *
  711. * ### Conditions using operators:
  712. *
  713. * ```
  714. * $query->where([
  715. * 'posted >=' => new DateTime('3 days ago'),
  716. * 'title LIKE' => 'Hello W%',
  717. * 'author_id' => 1,
  718. * ], ['posted' => 'datetime']);
  719. * ```
  720. *
  721. * The previous example produces:
  722. *
  723. * `WHERE posted >= 2012-01-27 AND title LIKE 'Hello W%' AND author_id = 1`
  724. *
  725. * Second parameter is used to specify what type is expected for each passed
  726. * key. Valid types can be used from the mapped with Database\Type class.
  727. *
  728. * ### Nesting conditions with conjunctions:
  729. *
  730. * ```
  731. * $query->where([
  732. * 'author_id !=' => 1,
  733. * 'OR' => ['published' => true, 'posted <' => new DateTime('now')],
  734. * 'NOT' => ['title' => 'Hello']
  735. * ], ['published' => boolean, 'posted' => 'datetime']
  736. * ```
  737. *
  738. * The previous example produces:
  739. *
  740. * `WHERE author_id = 1 AND (published = 1 OR posted < '2012-02-01') AND NOT (title = 'Hello')`
  741. *
  742. * You can nest conditions using conjunctions as much as you like. Sometimes, you
  743. * may want to define 2 different options for the same key, in that case, you can
  744. * wrap each condition inside a new array:
  745. *
  746. * `$query->where(['OR' => [['published' => false], ['published' => true]])`
  747. *
  748. * Would result in:
  749. *
  750. * `WHERE (published = false) OR (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. * Convenience method that adds a NOT NULL condition to the query
  826. *
  827. * @param array|string|\Cake\Database\ExpressionInterface $fields A single field or expressions or a list of them that should be not null
  828. * @return $this
  829. */
  830. public function whereNotNull($fields)
  831. {
  832. if (!is_array($fields)) {
  833. $fields = [$fields];
  834. }
  835. $exp = $this->newExpr();
  836. foreach ($fields as $field) {
  837. $exp->isNotNull($field);
  838. }
  839. return $this->where($exp);
  840. }
  841. /**
  842. * Convenience method that adds a IS NULL condition to the query
  843. *
  844. * @param array|string|\Cake\Database\ExpressionInterface $fields A single field or expressions or a list of them that should be null
  845. * @return $this
  846. */
  847. public function whereNull($fields)
  848. {
  849. if (!is_array($fields)) {
  850. $fields = [$fields];
  851. }
  852. $exp = $this->newExpr();
  853. foreach ($fields as $field) {
  854. $exp->isNull($field);
  855. }
  856. return $this->where($exp);
  857. }
  858. /**
  859. * Adds an IN condition or set of conditions to be used in the WHERE clause for this
  860. * query.
  861. *
  862. * This method does allow empty inputs in contrast to where() if you set
  863. * 'allowEmpty' to true.
  864. * Be careful about using it without proper sanity checks.
  865. *
  866. * Options:
  867. * - `types` - Associative array of type names used to bind values to query
  868. * - `allowEmpty` - Allow empty array.
  869. *
  870. * @param string $field Field
  871. * @param array $values Array of values
  872. * @param array $options Options
  873. * @return $this
  874. */
  875. public function whereInList($field, array $values, array $options = [])
  876. {
  877. $options += [
  878. 'types' => [],
  879. 'allowEmpty' => false,
  880. ];
  881. if ($options['allowEmpty'] && !$values) {
  882. return $this->where('1=0');
  883. }
  884. return $this->where([$field . ' IN' => $values], $options['types']);
  885. }
  886. /**
  887. * Adds a NOT IN condition or set of conditions to be used in the WHERE clause for this
  888. * query.
  889. *
  890. * This method does allow empty inputs in contrast to where() if you set
  891. * 'allowEmpty' to true.
  892. * Be careful about using it without proper sanity checks.
  893. *
  894. * @param string $field Field
  895. * @param array $values Array of values
  896. * @param array $options Options
  897. * @return $this
  898. */
  899. public function whereNotInList($field, array $values, array $options = [])
  900. {
  901. $options += [
  902. 'types' => [],
  903. 'allowEmpty' => false,
  904. ];
  905. if ($options['allowEmpty'] && !$values) {
  906. return $this->where([$field . ' IS NOT' => null]);
  907. }
  908. return $this->where([$field . ' NOT IN' => $values], $options['types']);
  909. }
  910. /**
  911. * Connects any previously defined set of conditions to the provided list
  912. * using the AND operator. This function accepts the conditions list in the same
  913. * format as the method `where` does, hence you can use arrays, expression objects
  914. * callback functions or strings.
  915. *
  916. * It is important to notice that when calling this function, any previous set
  917. * of conditions defined for this query will be treated as a single argument for
  918. * the AND operator. This function will not only operate the most recently defined
  919. * condition, but all the conditions as a whole.
  920. *
  921. * When using an array for defining conditions, creating constraints form each
  922. * array entry will use the same logic as with the `where()` function. This means
  923. * that each array entry will be joined to the other using the AND operator, unless
  924. * you nest the conditions in the array using other operator.
  925. *
  926. * ### Examples:
  927. *
  928. * ```
  929. * $query->where(['title' => 'Hello World')->andWhere(['author_id' => 1]);
  930. * ```
  931. *
  932. * Will produce:
  933. *
  934. * `WHERE title = 'Hello World' AND author_id = 1`
  935. *
  936. * ```
  937. * $query
  938. * ->where(['OR' => ['published' => false, 'published is NULL']])
  939. * ->andWhere(['author_id' => 1, 'comments_count >' => 10])
  940. * ```
  941. *
  942. * Produces:
  943. *
  944. * `WHERE (published = 0 OR published IS NULL) AND author_id = 1 AND comments_count > 10`
  945. *
  946. * ```
  947. * $query
  948. * ->where(['title' => 'Foo'])
  949. * ->andWhere(function ($exp, $query) {
  950. * return $exp
  951. * ->or_(['author_id' => 1])
  952. * ->add(['author_id' => 2]);
  953. * });
  954. * ```
  955. *
  956. * Generates the following conditions:
  957. *
  958. * `WHERE (title = 'Foo') AND (author_id = 1 OR author_id = 2)`
  959. *
  960. * @param string|array|\Cake\Database\ExpressionInterface|callable $conditions The conditions to add with AND.
  961. * @param array $types associative array of type names used to bind values to query
  962. * @see \Cake\Database\Query::where()
  963. * @see \Cake\Database\Type
  964. * @return $this
  965. */
  966. public function andWhere($conditions, $types = [])
  967. {
  968. $this->_conjugate('where', $conditions, 'AND', $types);
  969. return $this;
  970. }
  971. /**
  972. * Connects any previously defined set of conditions to the provided list
  973. * using the OR operator. This function accepts the conditions list in the same
  974. * format as the method `where` does, hence you can use arrays, expression objects
  975. * callback functions or strings.
  976. *
  977. * It is important to notice that when calling this function, any previous set
  978. * of conditions defined for this query will be treated as a single argument for
  979. * the OR operator. This function will not only operate the most recently defined
  980. * condition, but all the conditions as a whole.
  981. *
  982. * When using an array for defining conditions, creating constraints form each
  983. * array entry will use the same logic as with the `where()` function. This means
  984. * that each array entry will be joined to the other using the OR operator, unless
  985. * you nest the conditions in the array using other operator.
  986. *
  987. * ### Examples:
  988. *
  989. * ```
  990. * $query->where(['title' => 'Hello World')->orWhere(['title' => 'Foo']);
  991. * ```
  992. *
  993. * Will produce:
  994. *
  995. * `WHERE title = 'Hello World' OR title = 'Foo'`
  996. *
  997. * ```
  998. * $query
  999. * ->where(['OR' => ['published' => false, 'published is NULL']])
  1000. * ->orWhere(['author_id' => 1, 'comments_count >' => 10])
  1001. * ```
  1002. *
  1003. * Produces:
  1004. *
  1005. * `WHERE (published = 0 OR published IS NULL) OR (author_id = 1 AND comments_count > 10)`
  1006. *
  1007. * ```
  1008. * $query
  1009. * ->where(['title' => 'Foo'])
  1010. * ->orWhere(function ($exp, $query) {
  1011. * return $exp
  1012. * ->or_(['author_id' => 1])
  1013. * ->add(['author_id' => 2]);
  1014. * });
  1015. * ```
  1016. *
  1017. * Generates the following conditions:
  1018. *
  1019. * `WHERE (title = 'Foo') OR (author_id = 1 OR author_id = 2)`
  1020. *
  1021. * @param string|array|\Cake\Database\ExpressionInterface|callable $conditions The conditions to add with OR.
  1022. * @param array $types associative array of type names used to bind values to query
  1023. * @see \Cake\Database\Query::where()
  1024. * @see \Cake\Database\Type
  1025. * @return $this
  1026. * @deprecated 3.5.0 This method creates hard to predict SQL based on the current query state.
  1027. * Use `Query::where()` instead as it has more predicatable and easier to understand behavior.
  1028. */
  1029. public function orWhere($conditions, $types = [])
  1030. {
  1031. deprecationWarning(
  1032. 'Query::orWhere() is deprecated as it creates hard to predict SQL based on the ' .
  1033. 'current query state. Use `Query::where()` instead.'
  1034. );
  1035. $this->_conjugate('where', $conditions, 'OR', $types);
  1036. return $this;
  1037. }
  1038. /**
  1039. * Adds a single or multiple fields to be used in the ORDER clause for this query.
  1040. * Fields can be passed as an array of strings, array of expression
  1041. * objects, a single expression or a single string.
  1042. *
  1043. * If an array is passed, keys will be used as the field itself and the value will
  1044. * represent the order in which such field should be ordered. When called multiple
  1045. * times with the same fields as key, the last order definition will prevail over
  1046. * the others.
  1047. *
  1048. * By default this function will append any passed argument to the list of fields
  1049. * to be selected, unless the second argument is set to true.
  1050. *
  1051. * ### Examples:
  1052. *
  1053. * ```
  1054. * $query->order(['title' => 'DESC', 'author_id' => 'ASC']);
  1055. * ```
  1056. *
  1057. * Produces:
  1058. *
  1059. * `ORDER BY title DESC, author_id ASC`
  1060. *
  1061. * ```
  1062. * $query->order(['title' => 'DESC NULLS FIRST'])->order('author_id');
  1063. * ```
  1064. *
  1065. * Will generate:
  1066. *
  1067. * `ORDER BY title DESC NULLS FIRST, author_id`
  1068. *
  1069. * ```
  1070. * $expression = $query->newExpr()->add(['id % 2 = 0']);
  1071. * $query->order($expression)->order(['title' => 'ASC']);
  1072. * ```
  1073. *
  1074. * and
  1075. *
  1076. * ```
  1077. * $query->order(function ($exp, $query) {
  1078. * return [$exp->add(['id % 2 = 0']), 'title' => 'ASC'];
  1079. * });
  1080. * ```
  1081. *
  1082. * Will both become:
  1083. *
  1084. * `ORDER BY (id %2 = 0), title ASC`
  1085. *
  1086. * Order fields/directions are not sanitized by the query builder.
  1087. * You should use a whitelist of fields/directions when passing
  1088. * in user-supplied data to `order()`.
  1089. *
  1090. * If you need to set complex expressions as order conditions, you
  1091. * should use `orderAsc()` or `orderDesc()`.
  1092. *
  1093. * @param array|\Cake\Database\ExpressionInterface|callable|string $fields fields to be added to the list
  1094. * @param bool $overwrite whether to reset order with field list or not
  1095. * @return $this
  1096. */
  1097. public function order($fields, $overwrite = false)
  1098. {
  1099. if ($overwrite) {
  1100. $this->_parts['order'] = null;
  1101. }
  1102. if (!$fields) {
  1103. return $this;
  1104. }
  1105. if (!$this->_parts['order']) {
  1106. $this->_parts['order'] = new OrderByExpression();
  1107. }
  1108. $this->_conjugate('order', $fields, '', []);
  1109. return $this;
  1110. }
  1111. /**
  1112. * Add an ORDER BY clause with an ASC direction.
  1113. *
  1114. * This method allows you to set complex expressions
  1115. * as order conditions unlike order()
  1116. *
  1117. * Order fields are not suitable for use with user supplied data as they are
  1118. * not sanitized by the query builder.
  1119. *
  1120. * @param string|\Cake\Database\Expression\QueryExpression $field The field to order on.
  1121. * @param bool $overwrite Whether or not to reset the order clauses.
  1122. * @return $this
  1123. */
  1124. public function orderAsc($field, $overwrite = false)
  1125. {
  1126. if ($overwrite) {
  1127. $this->_parts['order'] = null;
  1128. }
  1129. if (!$field) {
  1130. return $this;
  1131. }
  1132. if (!$this->_parts['order']) {
  1133. $this->_parts['order'] = new OrderByExpression();
  1134. }
  1135. $this->_parts['order']->add(new OrderClauseExpression($field, 'ASC'));
  1136. return $this;
  1137. }
  1138. /**
  1139. * Add an ORDER BY clause with a DESC direction.
  1140. *
  1141. * This method allows you to set complex expressions
  1142. * as order conditions unlike order()
  1143. *
  1144. * Order fields are not suitable for use with user supplied data as they are
  1145. * not sanitized by the query builder.
  1146. *
  1147. * @param string|\Cake\Database\Expression\QueryExpression $field The field to order on.
  1148. * @param bool $overwrite Whether or not to reset the order clauses.
  1149. * @return $this
  1150. */
  1151. public function orderDesc($field, $overwrite = false)
  1152. {
  1153. if ($overwrite) {
  1154. $this->_parts['order'] = null;
  1155. }
  1156. if (!$field) {
  1157. return $this;
  1158. }
  1159. if (!$this->_parts['order']) {
  1160. $this->_parts['order'] = new OrderByExpression();
  1161. }
  1162. $this->_parts['order']->add(new OrderClauseExpression($field, 'DESC'));
  1163. return $this;
  1164. }
  1165. /**
  1166. * Adds a single or multiple fields to be used in the GROUP BY clause for this query.
  1167. * Fields can be passed as an array of strings, array of expression
  1168. * objects, a single expression or a single string.
  1169. *
  1170. * By default this function will append any passed argument to the list of fields
  1171. * to be grouped, unless the second argument is set to true.
  1172. *
  1173. * ### Examples:
  1174. *
  1175. * ```
  1176. * // Produces GROUP BY id, title
  1177. * $query->group(['id', 'title']);
  1178. *
  1179. * // Produces GROUP BY title
  1180. * $query->group('title');
  1181. * ```
  1182. *
  1183. * Group fields are not suitable for use with user supplied data as they are
  1184. * not sanitized by the query builder.
  1185. *
  1186. * @param array|\Cake\Database\ExpressionInterface|string $fields fields to be added to the list
  1187. * @param bool $overwrite whether to reset fields with passed list or not
  1188. * @return $this
  1189. */
  1190. public function group($fields, $overwrite = false)
  1191. {
  1192. if ($overwrite) {
  1193. $this->_parts['group'] = [];
  1194. }
  1195. if (!is_array($fields)) {
  1196. $fields = [$fields];
  1197. }
  1198. $this->_parts['group'] = array_merge($this->_parts['group'], array_values($fields));
  1199. $this->_dirty();
  1200. return $this;
  1201. }
  1202. /**
  1203. * Adds a condition or set of conditions to be used in the `HAVING` clause for this
  1204. * query. This method operates in exactly the same way as the method `where()`
  1205. * does. Please refer to its documentation for an insight on how to using each
  1206. * parameter.
  1207. *
  1208. * Having fields are not suitable for use with user supplied data as they are
  1209. * not sanitized by the query builder.
  1210. *
  1211. * @param string|array|\Cake\Database\ExpressionInterface|callable|null $conditions The having conditions.
  1212. * @param array $types associative array of type names used to bind values to query
  1213. * @param bool $overwrite whether to reset conditions with passed list or not
  1214. * @see \Cake\Database\Query::where()
  1215. * @return $this
  1216. */
  1217. public function having($conditions = null, $types = [], $overwrite = false)
  1218. {
  1219. if ($overwrite) {
  1220. $this->_parts['having'] = $this->newExpr();
  1221. }
  1222. $this->_conjugate('having', $conditions, 'AND', $types);
  1223. return $this;
  1224. }
  1225. /**
  1226. * Connects any previously defined set of conditions to the provided list
  1227. * using the AND operator in the HAVING clause. This method operates in exactly
  1228. * the same way as the method `andWhere()` does. Please refer to its
  1229. * documentation for an insight on how to using each parameter.
  1230. *
  1231. * Having fields are not suitable for use with user supplied data as they are
  1232. * not sanitized by the query builder.
  1233. *
  1234. * @param string|array|\Cake\Database\ExpressionInterface|callable $conditions The AND conditions for HAVING.
  1235. * @param array $types associative array of type names used to bind values to query
  1236. * @see \Cake\Database\Query::andWhere()
  1237. * @return $this
  1238. */
  1239. public function andHaving($conditions, $types = [])
  1240. {
  1241. $this->_conjugate('having', $conditions, 'AND', $types);
  1242. return $this;
  1243. }
  1244. /**
  1245. * Connects any previously defined set of conditions to the provided list
  1246. * using the OR operator in the HAVING clause. This method operates in exactly
  1247. * the same way as the method `orWhere()` does. Please refer to its
  1248. * documentation for an insight on how to using each parameter.
  1249. *
  1250. * Having fields are not suitable for use with user supplied data as they are
  1251. * not sanitized by the query builder.
  1252. *
  1253. * @param string|array|\Cake\Database\ExpressionInterface|callable $conditions The OR conditions for HAVING.
  1254. * @param array $types associative array of type names used to bind values to query.
  1255. * @see \Cake\Database\Query::orWhere()
  1256. * @return $this
  1257. * @deprecated 3.5.0 This method creates hard to predict SQL based on the current query state.
  1258. * Use `Query::having()` instead as it has more predicatable and easier to understand behavior.
  1259. */
  1260. public function orHaving($conditions, $types = [])
  1261. {
  1262. deprecationWarning('Query::orHaving() is deprecated. Use Query::having() instead.');
  1263. $this->_conjugate('having', $conditions, 'OR', $types);
  1264. return $this;
  1265. }
  1266. /**
  1267. * Set the page of results you want.
  1268. *
  1269. * This method provides an easier to use interface to set the limit + offset
  1270. * in the record set you want as results. If empty the limit will default to
  1271. * the existing limit clause, and if that too is empty, then `25` will be used.
  1272. *
  1273. * Pages must start at 1.
  1274. *
  1275. * @param int $num The page number you want.
  1276. * @param int|null $limit The number of rows you want in the page. If null
  1277. * the current limit clause will be used.
  1278. * @return $this
  1279. * @throws \InvalidArgumentException If page number < 1.
  1280. */
  1281. public function page($num, $limit = null)
  1282. {
  1283. if ($num < 1) {
  1284. throw new InvalidArgumentException('Pages must start at 1.');
  1285. }
  1286. if ($limit !== null) {
  1287. $this->limit($limit);
  1288. }
  1289. $limit = $this->clause('limit');
  1290. if ($limit === null) {
  1291. $limit = 25;
  1292. $this->limit($limit);
  1293. }
  1294. $offset = ($num - 1) * $limit;
  1295. if (PHP_INT_MAX <= $offset) {
  1296. $offset = PHP_INT_MAX;
  1297. }
  1298. $this->offset((int)$offset);
  1299. return $this;
  1300. }
  1301. /**
  1302. * Sets the number of records that should be retrieved from database,
  1303. * accepts an integer or an expression object that evaluates to an integer.
  1304. * In some databases, this operation might not be supported or will require
  1305. * the query to be transformed in order to limit the result set size.
  1306. *
  1307. * ### Examples
  1308. *
  1309. * ```
  1310. * $query->limit(10) // generates LIMIT 10
  1311. * $query->limit($query->newExpr()->add(['1 + 1'])); // LIMIT (1 + 1)
  1312. * ```
  1313. *
  1314. * @param int|\Cake\Database\ExpressionInterface $num number of records to be returned
  1315. * @return $this
  1316. */
  1317. public function limit($num)
  1318. {
  1319. $this->_dirty();
  1320. if ($num !== null && !is_object($num)) {
  1321. $num = (int)$num;
  1322. }
  1323. $this->_parts['limit'] = $num;
  1324. return $this;
  1325. }
  1326. /**
  1327. * Sets the number of records that should be skipped from the original result set
  1328. * This is commonly used for paginating large results. Accepts an integer or an
  1329. * expression object that evaluates to an integer.
  1330. *
  1331. * In some databases, this operation might not be supported or will require
  1332. * the query to be transformed in order to limit the result set size.
  1333. *
  1334. * ### Examples
  1335. *
  1336. * ```
  1337. * $query->offset(10) // generates OFFSET 10
  1338. * $query->offset($query->newExpr()->add(['1 + 1'])); // OFFSET (1 + 1)
  1339. * ```
  1340. *
  1341. * @param int|\Cake\Database\ExpressionInterface $num number of records to be skipped
  1342. * @return $this
  1343. */
  1344. public function offset($num)
  1345. {
  1346. $this->_dirty();
  1347. if ($num !== null && !is_object($num)) {
  1348. $num = (int)$num;
  1349. }
  1350. $this->_parts['offset'] = $num;
  1351. return $this;
  1352. }
  1353. /**
  1354. * Adds a complete query to be used in conjunction with an UNION operator with
  1355. * this query. This is used to combine the result set of this query with the one
  1356. * that will be returned by the passed query. You can add as many queries as you
  1357. * required by calling multiple times this method with different queries.
  1358. *
  1359. * By default, the UNION operator will remove duplicate rows, if you wish to include
  1360. * every row for all queries, use unionAll().
  1361. *
  1362. * ### Examples
  1363. *
  1364. * ```
  1365. * $union = (new Query($conn))->select(['id', 'title'])->from(['a' => 'articles']);
  1366. * $query->select(['id', 'name'])->from(['d' => 'things'])->union($union);
  1367. * ```
  1368. *
  1369. * Will produce:
  1370. *
  1371. * `SELECT id, name FROM things d UNION SELECT id, title FROM articles a`
  1372. *
  1373. * @param string|\Cake\Database\Query $query full SQL query to be used in UNION operator
  1374. * @param bool $overwrite whether to reset the list of queries to be operated or not
  1375. * @return $this
  1376. */
  1377. public function union($query, $overwrite = false)
  1378. {
  1379. if ($overwrite) {
  1380. $this->_parts['union'] = [];
  1381. }
  1382. $this->_parts['union'][] = [
  1383. 'all' => false,
  1384. 'query' => $query
  1385. ];
  1386. $this->_dirty();
  1387. return $this;
  1388. }
  1389. /**
  1390. * Adds a complete query to be used in conjunction with the UNION ALL operator with
  1391. * this query. This is used to combine the result set of this query with the one
  1392. * that will be returned by the passed query. You can add as many queries as you
  1393. * required by calling multiple times this method with different queries.
  1394. *
  1395. * Unlike UNION, UNION ALL will not remove duplicate rows.
  1396. *
  1397. * ```
  1398. * $union = (new Query($conn))->select(['id', 'title'])->from(['a' => 'articles']);
  1399. * $query->select(['id', 'name'])->from(['d' => 'things'])->unionAll($union);
  1400. * ```
  1401. *
  1402. * Will produce:
  1403. *
  1404. * `SELECT id, name FROM things d UNION ALL SELECT id, title FROM articles a`
  1405. *
  1406. * @param string|\Cake\Database\Query $query full SQL query to be used in UNION operator
  1407. * @param bool $overwrite whether to reset the list of queries to be operated or not
  1408. * @return $this
  1409. */
  1410. public function unionAll($query, $overwrite = false)
  1411. {
  1412. if ($overwrite) {
  1413. $this->_parts['union'] = [];
  1414. }
  1415. $this->_parts['union'][] = [
  1416. 'all' => true,
  1417. 'query' => $query
  1418. ];
  1419. $this->_dirty();
  1420. return $this;
  1421. }
  1422. /**
  1423. * Create an insert query.
  1424. *
  1425. * Note calling this method will reset any data previously set
  1426. * with Query::values().
  1427. *
  1428. * @param array $columns The columns to insert into.
  1429. * @param array $types A map between columns & their datatypes.
  1430. * @return $this
  1431. * @throws \RuntimeException When there are 0 columns.
  1432. */
  1433. public function insert(array $columns, array $types = [])
  1434. {
  1435. if (empty($columns)) {
  1436. throw new RuntimeException('At least 1 column is required to perform an insert.');
  1437. }
  1438. $this->_dirty();
  1439. $this->_type = 'insert';
  1440. $this->_parts['insert'][1] = $columns;
  1441. if (!$this->_parts['values']) {
  1442. $this->_parts['values'] = new ValuesExpression($columns, $this->getTypeMap()->setTypes($types));
  1443. } else {
  1444. $this->_parts['values']->setColumns($columns);
  1445. }
  1446. return $this;
  1447. }
  1448. /**
  1449. * Set the table name for insert queries.
  1450. *
  1451. * @param string $table The table name to insert into.
  1452. * @return $this
  1453. */
  1454. public function into($table)
  1455. {
  1456. $this->_dirty();
  1457. $this->_type = 'insert';
  1458. $this->_parts['insert'][0] = $table;
  1459. return $this;
  1460. }
  1461. /**
  1462. * Creates an expression that refers to an identifier. Identifiers are used to refer to field names and allow
  1463. * the SQL compiler to apply quotes or escape the identifier.
  1464. *
  1465. * The value is used as is, and you might be required to use aliases or include the table reference in
  1466. * the identifier. Do not use this method to inject SQL methods or logical statements.
  1467. *
  1468. * ### Example
  1469. *
  1470. * ```
  1471. * $query->newExp()->lte('count', $query->identifier('total'));
  1472. * ```
  1473. *
  1474. * @param string $identifier The identifier for an expression
  1475. * @return \Cake\Database\ExpressionInterface
  1476. */
  1477. public function identifier($identifier)
  1478. {
  1479. return new IdentifierExpression($identifier);
  1480. }
  1481. /**
  1482. * Set the values for an insert query.
  1483. *
  1484. * Multi inserts can be performed by calling values() more than one time,
  1485. * or by providing an array of value sets. Additionally $data can be a Query
  1486. * instance to insert data from another SELECT statement.
  1487. *
  1488. * @param array|\Cake\Database\Query $data The data to insert.
  1489. * @return $this
  1490. * @throws \Cake\Database\Exception if you try to set values before declaring columns.
  1491. * Or if you try to set values on non-insert queries.
  1492. */
  1493. public function values($data)
  1494. {
  1495. if ($this->_type !== 'insert') {
  1496. throw new Exception(
  1497. 'You cannot add values before defining columns to use.'
  1498. );
  1499. }
  1500. if (empty($this->_parts['insert'])) {
  1501. throw new Exception(
  1502. 'You cannot add values before defining columns to use.'
  1503. );
  1504. }
  1505. $this->_dirty();
  1506. if ($data instanceof ValuesExpression) {
  1507. $this->_parts['values'] = $data;
  1508. return $this;
  1509. }
  1510. $this->_parts['values']->add($data);
  1511. return $this;
  1512. }
  1513. /**
  1514. * Create an update query.
  1515. *
  1516. * Can be combined with set() and where() methods to create update queries.
  1517. *
  1518. * @param string|\Cake\Database\ExpressionInterface $table The table you want to update.
  1519. * @return $this
  1520. */
  1521. public function update($table)
  1522. {
  1523. if (!is_string($table) && !($table instanceof ExpressionInterface)) {
  1524. $text = 'Table must be of type string or "%s", got "%s"';
  1525. $message = sprintf($text, ExpressionInterface::class, gettype($table));
  1526. throw new InvalidArgumentException($message);
  1527. }
  1528. $this->_dirty();
  1529. $this->_type = 'update';
  1530. $this->_parts['update'][0] = $table;
  1531. return $this;
  1532. }
  1533. /**
  1534. * Set one or many fields to update.
  1535. *
  1536. * ### Examples
  1537. *
  1538. * Passing a string:
  1539. *
  1540. * ```
  1541. * $query->update('articles')->set('title', 'The Title');
  1542. * ```
  1543. *
  1544. * Passing an array:
  1545. *
  1546. * ```
  1547. * $query->update('articles')->set(['title' => 'The Title'], ['title' => 'string']);
  1548. * ```
  1549. *
  1550. * Passing a callable:
  1551. *
  1552. * ```
  1553. * $query->update('articles')->set(function ($exp) {
  1554. * return $exp->eq('title', 'The title', 'string');
  1555. * });
  1556. * ```
  1557. *
  1558. * @param string|array|callable|\Cake\Database\Expression\QueryExpression $key The column name or array of keys
  1559. * + values to set. This can also be a QueryExpression containing a SQL fragment.
  1560. * It can also be a callable, that is required to return an expression object.
  1561. * @param mixed $value The value to update $key to. Can be null if $key is an
  1562. * array or QueryExpression. When $key is an array, this parameter will be
  1563. * used as $types instead.
  1564. * @param array $types The column types to treat data as.
  1565. * @return $this
  1566. */
  1567. public function set($key, $value = null, $types = [])
  1568. {
  1569. if (empty($this->_parts['set'])) {
  1570. $this->_parts['set'] = $this->newExpr()->setConjunction(',');
  1571. }
  1572. if ($this->_parts['set']->isCallable($key)) {
  1573. $exp = $this->newExpr()->setConjunction(',');
  1574. $this->_parts['set']->add($key($exp));
  1575. return $this;
  1576. }
  1577. if (is_array($key) || $key instanceof ExpressionInterface) {
  1578. $types = (array)$value;
  1579. $this->_parts['set']->add($key, $types);
  1580. return $this;
  1581. }
  1582. if (is_string($types) && is_string($key)) {
  1583. $types = [$key => $types];
  1584. }
  1585. $this->_parts['set']->eq($key, $value, $types);
  1586. return $this;
  1587. }
  1588. /**
  1589. * Create a delete query.
  1590. *
  1591. * Can be combined with from(), where() and other methods to
  1592. * create delete queries with specific conditions.
  1593. *
  1594. * @param string|null $table The table to use when deleting.
  1595. * @return $this
  1596. */
  1597. public function delete($table = null)
  1598. {
  1599. $this->_dirty();
  1600. $this->_type = 'delete';
  1601. if ($table !== null) {
  1602. $this->from($table);
  1603. }
  1604. return $this;
  1605. }
  1606. /**
  1607. * A string or expression that will be appended to the generated query
  1608. *
  1609. * ### Examples:
  1610. * ```
  1611. * $query->select('id')->where(['author_id' => 1])->epilog('FOR UPDATE');
  1612. * $query
  1613. * ->insert('articles', ['title'])
  1614. * ->values(['author_id' => 1])
  1615. * ->epilog('RETURNING id');
  1616. * ```
  1617. *
  1618. * Epliog content is raw SQL and not suitable for use with user supplied data.
  1619. *
  1620. * @param string|\Cake\Database\Expression\QueryExpression|null $expression The expression to be appended
  1621. * @return $this
  1622. */
  1623. public function epilog($expression = null)
  1624. {
  1625. $this->_dirty();
  1626. $this->_parts['epilog'] = $expression;
  1627. return $this;
  1628. }
  1629. /**
  1630. * Returns the type of this query (select, insert, update, delete)
  1631. *
  1632. * @return string
  1633. */
  1634. public function type()
  1635. {
  1636. return $this->_type;
  1637. }
  1638. /**
  1639. * Returns a new QueryExpression object. This is a handy function when
  1640. * building complex queries using a fluent interface. You can also override
  1641. * this function in subclasses to use a more specialized QueryExpression class
  1642. * if required.
  1643. *
  1644. * You can optionally pass a single raw SQL string or an array or expressions in
  1645. * any format accepted by \Cake\Database\Expression\QueryExpression:
  1646. *
  1647. * ```
  1648. * $expression = $query->newExpr(); // Returns an empty expression object
  1649. * $expression = $query->newExpr('Table.column = Table2.column'); // Return a raw SQL expression
  1650. * ```
  1651. *
  1652. * @param mixed $rawExpression A string, array or anything you want wrapped in an expression object
  1653. * @return \Cake\Database\Expression\QueryExpression
  1654. */
  1655. public function newExpr($rawExpression = null)
  1656. {
  1657. $expression = new QueryExpression([], $this->getTypeMap());
  1658. if ($rawExpression !== null) {
  1659. $expression->add($rawExpression);
  1660. }
  1661. return $expression;
  1662. }
  1663. /**
  1664. * Returns an instance of a functions builder object that can be used for
  1665. * generating arbitrary SQL functions.
  1666. *
  1667. * ### Example:
  1668. *
  1669. * ```
  1670. * $query->func()->count('*');
  1671. * $query->func()->dateDiff(['2012-01-05', '2012-01-02'])
  1672. * ```
  1673. *
  1674. * @return \Cake\Database\FunctionsBuilder
  1675. */
  1676. public function func()
  1677. {
  1678. if ($this->_functionsBuilder === null) {
  1679. $this->_functionsBuilder = new FunctionsBuilder();
  1680. }
  1681. return $this->_functionsBuilder;
  1682. }
  1683. /**
  1684. * Executes this query and returns a results iterator. This function is required
  1685. * for implementing the IteratorAggregate interface and allows the query to be
  1686. * iterated without having to call execute() manually, thus making it look like
  1687. * a result set instead of the query itself.
  1688. *
  1689. * @return \Cake\Database\StatementInterface|null
  1690. */
  1691. public function getIterator()
  1692. {
  1693. if ($this->_iterator === null || $this->_dirty) {
  1694. $this->_iterator = $this->execute();
  1695. }
  1696. return $this->_iterator;
  1697. }
  1698. /**
  1699. * Returns any data that was stored in the specified clause. This is useful for
  1700. * modifying any internal part of the query and it is used by the SQL dialects
  1701. * to transform the query accordingly before it is executed. The valid clauses that
  1702. * can be retrieved are: delete, update, set, insert, values, select, distinct,
  1703. * from, join, set, where, group, having, order, limit, offset and union.
  1704. *
  1705. * The return value for each of those parts may vary. Some clauses use QueryExpression
  1706. * to internally store their state, some use arrays and others may use booleans or
  1707. * integers. This is summary of the return types for each clause.
  1708. *
  1709. * - update: string The name of the table to update
  1710. * - set: QueryExpression
  1711. * - insert: array, will return an array containing the table + columns.
  1712. * - values: ValuesExpression
  1713. * - select: array, will return empty array when no fields are set
  1714. * - distinct: boolean
  1715. * - from: array of tables
  1716. * - join: array
  1717. * - set: array
  1718. * - where: QueryExpression, returns null when not set
  1719. * - group: array
  1720. * - having: QueryExpression, returns null when not set
  1721. * - order: OrderByExpression, returns null when not set
  1722. * - limit: integer or QueryExpression, null when not set
  1723. * - offset: integer or QueryExpression, null when not set
  1724. * - union: array
  1725. *
  1726. * @param string $name name of the clause to be returned
  1727. * @return mixed
  1728. * @throws \InvalidArgumentException When the named clause does not exist.
  1729. */
  1730. public function clause($name)
  1731. {
  1732. if (!array_key_exists($name, $this->_parts)) {
  1733. $clauses = implode(', ', array_keys($this->_parts));
  1734. throw new InvalidArgumentException("The '$name' clause is not defined. Valid clauses are: $clauses");
  1735. }
  1736. return $this->_parts[$name];
  1737. }
  1738. /**
  1739. * Registers a callback to be executed for each result that is fetched from the
  1740. * result set, the callback function will receive as first parameter an array with
  1741. * the raw data from the database for every row that is fetched and must return the
  1742. * row with any possible modifications.
  1743. *
  1744. * Callbacks will be executed lazily, if only 3 rows are fetched for database it will
  1745. * called 3 times, event though there might be more rows to be fetched in the cursor.
  1746. *
  1747. * Callbacks are stacked in the order they are registered, if you wish to reset the stack
  1748. * the call this function with the second parameter set to true.
  1749. *
  1750. * If you wish to remove all decorators from the stack, set the first parameter
  1751. * to null and the second to true.
  1752. *
  1753. * ### Example
  1754. *
  1755. * ```
  1756. * $query->decorateResults(function ($row) {
  1757. * $row['order_total'] = $row['subtotal'] + ($row['subtotal'] * $row['tax']);
  1758. * return $row;
  1759. * });
  1760. * ```
  1761. *
  1762. * @param callable|null $callback The callback to invoke when results are fetched.
  1763. * @param bool $overwrite Whether or not this should append or replace all existing decorators.
  1764. * @return $this
  1765. */
  1766. public function decorateResults($callback, $overwrite = false)
  1767. {
  1768. if ($overwrite) {
  1769. $this->_resultDecorators = [];
  1770. }
  1771. if ($callback !== null) {
  1772. $this->_resultDecorators[] = $callback;
  1773. }
  1774. return $this;
  1775. }
  1776. /**
  1777. * This function works similar to the traverse() function, with the difference
  1778. * that it does a full depth traversal of the entire expression tree. This will execute
  1779. * the provided callback function for each ExpressionInterface object that is
  1780. * stored inside this query at any nesting depth in any part of the query.
  1781. *
  1782. * Callback will receive as first parameter the currently visited expression.
  1783. *
  1784. * @param callable $callback the function to be executed for each ExpressionInterface
  1785. * found inside this query.
  1786. * @return $this|null
  1787. */
  1788. public function traverseExpressions(callable $callback)
  1789. {
  1790. $visitor = function ($expression) use (&$visitor, $callback) {
  1791. if (is_array($expression)) {
  1792. foreach ($expression as $e) {
  1793. $visitor($e);
  1794. }
  1795. return null;
  1796. }
  1797. if ($expression instanceof ExpressionInterface) {
  1798. $expression->traverse($visitor);
  1799. if (!($expression instanceof self)) {
  1800. $callback($expression);
  1801. }
  1802. }
  1803. };
  1804. return $this->traverse($visitor);
  1805. }
  1806. /**
  1807. * Associates a query placeholder to a value and a type.
  1808. *
  1809. * If type is expressed as "atype[]" (note braces) then it will cause the
  1810. * placeholder to be re-written dynamically so if the value is an array, it
  1811. * will create as many placeholders as values are in it. For example:
  1812. *
  1813. * ```
  1814. * $query->bind(':id', [1, 2, 3], 'int[]');
  1815. * ```
  1816. *
  1817. * Will create 3 int placeholders. When using named placeholders, this method
  1818. * requires that the placeholders include `:` e.g. `:value`.
  1819. *
  1820. * @param string|int $param placeholder to be replaced with quoted version
  1821. * of $value
  1822. * @param mixed $value The value to be bound
  1823. * @param string|int $type the mapped type name, used for casting when sending
  1824. * to database
  1825. * @return $this
  1826. */
  1827. public function bind($param, $value, $type = 'string')
  1828. {
  1829. $this->getValueBinder()->bind($param, $value, $type);
  1830. return $this;
  1831. }
  1832. /**
  1833. * Returns the currently used ValueBinder instance.
  1834. *
  1835. * A ValueBinder is responsible for generating query placeholders and temporarily
  1836. * associate values to those placeholders so that they can be passed correctly
  1837. * to the statement object.
  1838. *
  1839. * @return \Cake\Database\ValueBinder
  1840. */
  1841. public function getValueBinder()
  1842. {
  1843. if ($this->_valueBinder === null) {
  1844. $this->_valueBinder = new ValueBinder();
  1845. }
  1846. return $this->_valueBinder;
  1847. }
  1848. /**
  1849. * Overwrite the current value binder
  1850. *
  1851. * A ValueBinder is responsible for generating query placeholders and temporarily
  1852. * associate values to those placeholders so that they can be passed correctly
  1853. * to the statement object.
  1854. *
  1855. * @param \Cake\Database\ValueBinder|bool $binder The binder or false to disable binding.
  1856. * @return $this
  1857. */
  1858. public function setValueBinder($binder)
  1859. {
  1860. $this->_valueBinder = $binder;
  1861. return $this;
  1862. }
  1863. /**
  1864. * Returns the currently used ValueBinder instance. If a value is passed,
  1865. * it will be set as the new instance to be used.
  1866. *
  1867. * A ValueBinder is responsible for generating query placeholders and temporarily
  1868. * associate values to those placeholders so that they can be passed correctly
  1869. * to the statement object.
  1870. *
  1871. * @deprecated 3.5.0 Use setValueBinder()/getValueBinder() instead.
  1872. * @param \Cake\Database\ValueBinder|false|null $binder new instance to be set. If no value is passed the
  1873. * default one will be returned
  1874. * @return $this|\Cake\Database\ValueBinder
  1875. */
  1876. public function valueBinder($binder = null)
  1877. {
  1878. deprecationWarning('Query::valueBinder() is deprecated. Use Query::getValueBinder()/setValueBinder() instead.');
  1879. if ($binder === null) {
  1880. if ($this->_valueBinder === null) {
  1881. $this->_valueBinder = new ValueBinder();
  1882. }
  1883. return $this->_valueBinder;
  1884. }
  1885. $this->_valueBinder = $binder;
  1886. return $this;
  1887. }
  1888. /**
  1889. * Enables/Disables buffered results.
  1890. *
  1891. * When enabled the results returned by this Query will be
  1892. * buffered. This enables you to iterate a result set multiple times, or
  1893. * both cache and iterate it.
  1894. *
  1895. * When disabled it will consume less memory as fetched results are not
  1896. * remembered for future iterations.
  1897. *
  1898. * @param bool $enable Whether or not to enable buffering
  1899. * @return $this
  1900. */
  1901. public function enableBufferedResults($enable = true)
  1902. {
  1903. $this->_dirty();
  1904. $this->_useBufferedResults = (bool)$enable;
  1905. return $this;
  1906. }
  1907. /**
  1908. * Disables buffered results.
  1909. *
  1910. * Disabling buffering will consume less memory as fetched results are not
  1911. * remembered for future iterations.
  1912. *
  1913. * @return $this
  1914. */
  1915. public function disableBufferedResults()
  1916. {
  1917. $this->_dirty();
  1918. $this->_useBufferedResults = false;
  1919. return $this;
  1920. }
  1921. /**
  1922. * Returns whether buffered results are enabled/disabled.
  1923. *
  1924. * When enabled the results returned by this Query will be
  1925. * buffered. This enables you to iterate a result set multiple times, or
  1926. * both cache and iterate it.
  1927. *
  1928. * When disabled it will consume less memory as fetched results are not
  1929. * remembered for future iterations.
  1930. *
  1931. * @return bool
  1932. */
  1933. public function isBufferedResultsEnabled()
  1934. {
  1935. return $this->_useBufferedResults;
  1936. }
  1937. /**
  1938. * Enable/Disable buffered results.
  1939. *
  1940. * When enabled the results returned by this Query will be
  1941. * buffered. This enables you to iterate a result set multiple times, or
  1942. * both cache and iterate it.
  1943. *
  1944. * When disabled it will consume less memory as fetched results are not
  1945. * remembered for future iterations.
  1946. *
  1947. * If called with no arguments, it will return whether or not buffering is
  1948. * enabled.
  1949. *
  1950. * @deprecated 3.4.0 Use enableBufferedResults()/isBufferedResultsEnabled() instead.
  1951. * @param bool|null $enable Whether or not to enable buffering
  1952. * @return bool|$this
  1953. */
  1954. public function bufferResults($enable = null)
  1955. {
  1956. deprecationWarning(
  1957. 'Query::bufferResults() is deprecated. ' .
  1958. 'Use Query::enableBufferedResults()/isBufferedResultsEnabled() instead.'
  1959. );
  1960. if ($enable !== null) {
  1961. return $this->enableBufferedResults($enable);
  1962. }
  1963. return $this->isBufferedResultsEnabled();
  1964. }
  1965. /**
  1966. * Sets the TypeMap class where the types for each of the fields in the
  1967. * select clause are stored.
  1968. *
  1969. * @param \Cake\Database\TypeMap $typeMap The map object to use
  1970. * @return $this
  1971. */
  1972. public function setSelectTypeMap(TypeMap $typeMap)
  1973. {
  1974. $this->_selectTypeMap = $typeMap;
  1975. $this->_dirty();
  1976. return $this;
  1977. }
  1978. /**
  1979. * Gets the TypeMap class where the types for each of the fields in the
  1980. * select clause are stored.
  1981. *
  1982. * @return \Cake\Database\TypeMap
  1983. */
  1984. public function getSelectTypeMap()
  1985. {
  1986. if ($this->_selectTypeMap === null) {
  1987. $this->_selectTypeMap = new TypeMap();
  1988. }
  1989. return $this->_selectTypeMap;
  1990. }
  1991. /**
  1992. * Disables the automatic casting of fields to their corresponding PHP data type
  1993. *
  1994. * @return $this
  1995. */
  1996. public function disableResultsCasting()
  1997. {
  1998. $this->typeCastEnabled = false;
  1999. return $this;
  2000. }
  2001. /**
  2002. * Enables the automatic casting of fields to their corresponding type
  2003. *
  2004. * @return $this
  2005. */
  2006. public function enableResultsCasting()
  2007. {
  2008. $this->typeCastEnabled = true;
  2009. return $this;
  2010. }
  2011. /**
  2012. * Sets the TypeMap class where the types for each of the fields in the
  2013. * select clause are stored.
  2014. *
  2015. * When called with no arguments, the current TypeMap object is returned.
  2016. *
  2017. * @deprecated 3.4.0 Use setSelectTypeMap()/getSelectTypeMap() instead.
  2018. * @param \Cake\Database\TypeMap|null $typeMap The map object to use
  2019. * @return $this|\Cake\Database\TypeMap
  2020. */
  2021. public function selectTypeMap(TypeMap $typeMap = null)
  2022. {
  2023. deprecationWarning(
  2024. 'Query::selectTypeMap() is deprecated. ' .
  2025. 'Use Query::setSelectTypeMap()/getSelectTypeMap() instead.'
  2026. );
  2027. if ($typeMap !== null) {
  2028. return $this->setSelectTypeMap($typeMap);
  2029. }
  2030. return $this->getSelectTypeMap();
  2031. }
  2032. /**
  2033. * Auxiliary function used to wrap the original statement from the driver with
  2034. * any registered callbacks.
  2035. *
  2036. * @param \Cake\Database\StatementInterface $statement to be decorated
  2037. * @return \Cake\Database\Statement\CallbackStatement
  2038. */
  2039. protected function _decorateStatement($statement)
  2040. {
  2041. $typeMap = $this->getSelectTypeMap();
  2042. $driver = $this->getConnection()->getDriver();
  2043. if ($this->typeCastEnabled && $typeMap->toArray()) {
  2044. $statement = new CallbackStatement($statement, $driver, new FieldTypeConverter($typeMap, $driver));
  2045. }
  2046. foreach ($this->_resultDecorators as $f) {
  2047. $statement = new CallbackStatement($statement, $driver, $f);
  2048. }
  2049. return $statement;
  2050. }
  2051. /**
  2052. * Helper function used to build conditions by composing QueryExpression objects.
  2053. *
  2054. * @param string $part Name of the query part to append the new part to
  2055. * @param string|null|array|\Cake\Database\ExpressionInterface|callable $append Expression or builder function to append.
  2056. * @param string $conjunction type of conjunction to be used to operate part
  2057. * @param array $types associative array of type names used to bind values to query
  2058. * @return void
  2059. */
  2060. protected function _conjugate($part, $append, $conjunction, $types)
  2061. {
  2062. $expression = $this->_parts[$part] ?: $this->newExpr();
  2063. if (empty($append)) {
  2064. $this->_parts[$part] = $expression;
  2065. return;
  2066. }
  2067. if ($expression->isCallable($append)) {
  2068. $append = $append($this->newExpr(), $this);
  2069. }
  2070. if ($expression->getConjunction() === $conjunction) {
  2071. $expression->add($append, $types);
  2072. } else {
  2073. $expression = $this->newExpr()
  2074. ->setConjunction($conjunction)
  2075. ->add([$expression, $append], $types);
  2076. }
  2077. $this->_parts[$part] = $expression;
  2078. $this->_dirty();
  2079. }
  2080. /**
  2081. * Marks a query as dirty, removing any preprocessed information
  2082. * from in memory caching.
  2083. *
  2084. * @return void
  2085. */
  2086. protected function _dirty()
  2087. {
  2088. $this->_dirty = true;
  2089. if ($this->_iterator && $this->_valueBinder) {
  2090. $this->getValueBinder()->reset();
  2091. }
  2092. }
  2093. /**
  2094. * Do a deep clone on this object.
  2095. *
  2096. * Will clone all of the expression objects used in
  2097. * each of the clauses, as well as the valueBinder.
  2098. *
  2099. * @return void
  2100. */
  2101. public function __clone()
  2102. {
  2103. $this->_iterator = null;
  2104. if ($this->_valueBinder !== null) {
  2105. $this->_valueBinder = clone $this->_valueBinder;
  2106. }
  2107. if ($this->_selectTypeMap !== null) {
  2108. $this->_selectTypeMap = clone $this->_selectTypeMap;
  2109. }
  2110. foreach ($this->_parts as $name => $part) {
  2111. if (empty($part)) {
  2112. continue;
  2113. }
  2114. if (is_array($part)) {
  2115. foreach ($part as $i => $piece) {
  2116. if ($piece instanceof ExpressionInterface) {
  2117. $this->_parts[$name][$i] = clone $piece;
  2118. }
  2119. }
  2120. }
  2121. if ($part instanceof ExpressionInterface) {
  2122. $this->_parts[$name] = clone $part;
  2123. }
  2124. }
  2125. }
  2126. /**
  2127. * Returns string representation of this query (complete SQL statement).
  2128. *
  2129. * @return string
  2130. */
  2131. public function __toString()
  2132. {
  2133. return $this->sql();
  2134. }
  2135. /**
  2136. * Returns an array that can be used to describe the internal state of this
  2137. * object.
  2138. *
  2139. * @return array
  2140. */
  2141. public function __debugInfo()
  2142. {
  2143. try {
  2144. set_error_handler(function ($errno, $errstr) {
  2145. throw new RuntimeException($errstr, $errno);
  2146. }, E_ALL);
  2147. $sql = $this->sql();
  2148. $params = $this->getValueBinder()->bindings();
  2149. } catch (RuntimeException $e) {
  2150. $sql = 'SQL could not be generated for this query as it is incomplete.';
  2151. $params = [];
  2152. } finally {
  2153. restore_error_handler();
  2154. }
  2155. return [
  2156. '(help)' => 'This is a Query object, to get the results execute or iterate it.',
  2157. 'sql' => $sql,
  2158. 'params' => $params,
  2159. 'defaultTypes' => $this->getDefaultTypes(),
  2160. 'decorators' => count($this->_resultDecorators),
  2161. 'executed' => $this->_iterator ? true : false
  2162. ];
  2163. }
  2164. }