Query.php 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361
  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 Query::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|string[]|\Cake\Database\ExpressionInterface[] $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|string[]|\Cake\Database\ExpressionInterface[] $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|string[]|\Cake\Database\ExpressionInterface[] $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|string[]|\Cake\Database\ExpressionInterface[] $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|callable $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. if ($this->_parts['order']->isCallable($field)) {
  1136. $field = $field($this->newExpr(), $this);
  1137. }
  1138. $this->_parts['order']->add(new OrderClauseExpression($field, 'ASC'));
  1139. return $this;
  1140. }
  1141. /**
  1142. * Add an ORDER BY clause with a DESC direction.
  1143. *
  1144. * This method allows you to set complex expressions
  1145. * as order conditions unlike order()
  1146. *
  1147. * Order fields are not suitable for use with user supplied data as they are
  1148. * not sanitized by the query builder.
  1149. *
  1150. * @param string|\Cake\Database\Expression\QueryExpression|callable $field The field to order on.
  1151. * @param bool $overwrite Whether or not to reset the order clauses.
  1152. * @return $this
  1153. */
  1154. public function orderDesc($field, $overwrite = false)
  1155. {
  1156. if ($overwrite) {
  1157. $this->_parts['order'] = null;
  1158. }
  1159. if (!$field) {
  1160. return $this;
  1161. }
  1162. if (!$this->_parts['order']) {
  1163. $this->_parts['order'] = new OrderByExpression();
  1164. }
  1165. if ($this->_parts['order']->isCallable($field)) {
  1166. $field = $field($this->newExpr(), $this);
  1167. }
  1168. $this->_parts['order']->add(new OrderClauseExpression($field, 'DESC'));
  1169. return $this;
  1170. }
  1171. /**
  1172. * Adds a single or multiple fields to be used in the GROUP BY clause for this query.
  1173. * Fields can be passed as an array of strings, array of expression
  1174. * objects, a single expression or a single string.
  1175. *
  1176. * By default this function will append any passed argument to the list of fields
  1177. * to be grouped, unless the second argument is set to true.
  1178. *
  1179. * ### Examples:
  1180. *
  1181. * ```
  1182. * // Produces GROUP BY id, title
  1183. * $query->group(['id', 'title']);
  1184. *
  1185. * // Produces GROUP BY title
  1186. * $query->group('title');
  1187. * ```
  1188. *
  1189. * Group fields are not suitable for use with user supplied data as they are
  1190. * not sanitized by the query builder.
  1191. *
  1192. * @param array|\Cake\Database\ExpressionInterface|string $fields fields to be added to the list
  1193. * @param bool $overwrite whether to reset fields with passed list or not
  1194. * @return $this
  1195. */
  1196. public function group($fields, $overwrite = false)
  1197. {
  1198. if ($overwrite) {
  1199. $this->_parts['group'] = [];
  1200. }
  1201. if (!is_array($fields)) {
  1202. $fields = [$fields];
  1203. }
  1204. $this->_parts['group'] = array_merge($this->_parts['group'], array_values($fields));
  1205. $this->_dirty();
  1206. return $this;
  1207. }
  1208. /**
  1209. * Adds a condition or set of conditions to be used in the `HAVING` clause for this
  1210. * query. This method operates in exactly the same way as the method `where()`
  1211. * does. Please refer to its documentation for an insight on how to using each
  1212. * parameter.
  1213. *
  1214. * Having fields are not suitable for use with user supplied data as they are
  1215. * not sanitized by the query builder.
  1216. *
  1217. * @param string|array|\Cake\Database\ExpressionInterface|callable|null $conditions The having conditions.
  1218. * @param array $types associative array of type names used to bind values to query
  1219. * @param bool $overwrite whether to reset conditions with passed list or not
  1220. * @see \Cake\Database\Query::where()
  1221. * @return $this
  1222. */
  1223. public function having($conditions = null, $types = [], $overwrite = false)
  1224. {
  1225. if ($overwrite) {
  1226. $this->_parts['having'] = $this->newExpr();
  1227. }
  1228. $this->_conjugate('having', $conditions, 'AND', $types);
  1229. return $this;
  1230. }
  1231. /**
  1232. * Connects any previously defined set of conditions to the provided list
  1233. * using the AND operator in the HAVING clause. This method operates in exactly
  1234. * the same way as the method `andWhere()` does. Please refer to its
  1235. * documentation for an insight on how to using each parameter.
  1236. *
  1237. * Having fields are not suitable for use with user supplied data as they are
  1238. * not sanitized by the query builder.
  1239. *
  1240. * @param string|array|\Cake\Database\ExpressionInterface|callable $conditions The AND conditions for HAVING.
  1241. * @param array $types associative array of type names used to bind values to query
  1242. * @see \Cake\Database\Query::andWhere()
  1243. * @return $this
  1244. */
  1245. public function andHaving($conditions, $types = [])
  1246. {
  1247. $this->_conjugate('having', $conditions, 'AND', $types);
  1248. return $this;
  1249. }
  1250. /**
  1251. * Connects any previously defined set of conditions to the provided list
  1252. * using the OR operator in the HAVING clause. This method operates in exactly
  1253. * the same way as the method `orWhere()` does. Please refer to its
  1254. * documentation for an insight on how to using each parameter.
  1255. *
  1256. * Having fields are not suitable for use with user supplied data as they are
  1257. * not sanitized by the query builder.
  1258. *
  1259. * @param string|array|\Cake\Database\ExpressionInterface|callable $conditions The OR conditions for HAVING.
  1260. * @param array $types associative array of type names used to bind values to query.
  1261. * @see \Cake\Database\Query::orWhere()
  1262. * @return $this
  1263. * @deprecated 3.5.0 This method creates hard to predict SQL based on the current query state.
  1264. * Use `Query::having()` instead as it has more predicatable and easier to understand behavior.
  1265. */
  1266. public function orHaving($conditions, $types = [])
  1267. {
  1268. deprecationWarning('Query::orHaving() is deprecated. Use Query::having() instead.');
  1269. $this->_conjugate('having', $conditions, 'OR', $types);
  1270. return $this;
  1271. }
  1272. /**
  1273. * Set the page of results you want.
  1274. *
  1275. * This method provides an easier to use interface to set the limit + offset
  1276. * in the record set you want as results. If empty the limit will default to
  1277. * the existing limit clause, and if that too is empty, then `25` will be used.
  1278. *
  1279. * Pages must start at 1.
  1280. *
  1281. * @param int $num The page number you want.
  1282. * @param int|null $limit The number of rows you want in the page. If null
  1283. * the current limit clause will be used.
  1284. * @return $this
  1285. * @throws \InvalidArgumentException If page number < 1.
  1286. */
  1287. public function page($num, $limit = null)
  1288. {
  1289. if ($num < 1) {
  1290. throw new InvalidArgumentException('Pages must start at 1.');
  1291. }
  1292. if ($limit !== null) {
  1293. $this->limit($limit);
  1294. }
  1295. $limit = $this->clause('limit');
  1296. if ($limit === null) {
  1297. $limit = 25;
  1298. $this->limit($limit);
  1299. }
  1300. $offset = ($num - 1) * $limit;
  1301. if (PHP_INT_MAX <= $offset) {
  1302. $offset = PHP_INT_MAX;
  1303. }
  1304. $this->offset((int)$offset);
  1305. return $this;
  1306. }
  1307. /**
  1308. * Sets the number of records that should be retrieved from database,
  1309. * accepts an integer or an expression object that evaluates to an integer.
  1310. * In some databases, this operation might not be supported or will require
  1311. * the query to be transformed in order to limit the result set size.
  1312. *
  1313. * ### Examples
  1314. *
  1315. * ```
  1316. * $query->limit(10) // generates LIMIT 10
  1317. * $query->limit($query->newExpr()->add(['1 + 1'])); // LIMIT (1 + 1)
  1318. * ```
  1319. *
  1320. * @param int|\Cake\Database\ExpressionInterface|null $num number of records to be returned
  1321. * @return $this
  1322. */
  1323. public function limit($num)
  1324. {
  1325. $this->_dirty();
  1326. if ($num !== null && !is_object($num)) {
  1327. $num = (int)$num;
  1328. }
  1329. $this->_parts['limit'] = $num;
  1330. return $this;
  1331. }
  1332. /**
  1333. * Sets the number of records that should be skipped from the original result set
  1334. * This is commonly used for paginating large results. Accepts an integer or an
  1335. * expression object that evaluates to an integer.
  1336. *
  1337. * In some databases, this operation might not be supported or will require
  1338. * the query to be transformed in order to limit the result set size.
  1339. *
  1340. * ### Examples
  1341. *
  1342. * ```
  1343. * $query->offset(10) // generates OFFSET 10
  1344. * $query->offset($query->newExpr()->add(['1 + 1'])); // OFFSET (1 + 1)
  1345. * ```
  1346. *
  1347. * @param int|\Cake\Database\ExpressionInterface|null $num number of records to be skipped
  1348. * @return $this
  1349. */
  1350. public function offset($num)
  1351. {
  1352. $this->_dirty();
  1353. if ($num !== null && !is_object($num)) {
  1354. $num = (int)$num;
  1355. }
  1356. $this->_parts['offset'] = $num;
  1357. return $this;
  1358. }
  1359. /**
  1360. * Adds a complete query to be used in conjunction with an UNION operator with
  1361. * this query. This is used to combine the result set of this query with the one
  1362. * that will be returned by the passed query. You can add as many queries as you
  1363. * required by calling multiple times this method with different queries.
  1364. *
  1365. * By default, the UNION operator will remove duplicate rows, if you wish to include
  1366. * every row for all queries, use unionAll().
  1367. *
  1368. * ### Examples
  1369. *
  1370. * ```
  1371. * $union = (new Query($conn))->select(['id', 'title'])->from(['a' => 'articles']);
  1372. * $query->select(['id', 'name'])->from(['d' => 'things'])->union($union);
  1373. * ```
  1374. *
  1375. * Will produce:
  1376. *
  1377. * `SELECT id, name FROM things d UNION SELECT id, title FROM articles a`
  1378. *
  1379. * @param string|\Cake\Database\Query $query full SQL query to be used in UNION operator
  1380. * @param bool $overwrite whether to reset the list of queries to be operated or not
  1381. * @return $this
  1382. */
  1383. public function union($query, $overwrite = false)
  1384. {
  1385. if ($overwrite) {
  1386. $this->_parts['union'] = [];
  1387. }
  1388. $this->_parts['union'][] = [
  1389. 'all' => false,
  1390. 'query' => $query,
  1391. ];
  1392. $this->_dirty();
  1393. return $this;
  1394. }
  1395. /**
  1396. * Adds a complete query to be used in conjunction with the UNION ALL operator with
  1397. * this query. This is used to combine the result set of this query with the one
  1398. * that will be returned by the passed query. You can add as many queries as you
  1399. * required by calling multiple times this method with different queries.
  1400. *
  1401. * Unlike UNION, UNION ALL will not remove duplicate rows.
  1402. *
  1403. * ```
  1404. * $union = (new Query($conn))->select(['id', 'title'])->from(['a' => 'articles']);
  1405. * $query->select(['id', 'name'])->from(['d' => 'things'])->unionAll($union);
  1406. * ```
  1407. *
  1408. * Will produce:
  1409. *
  1410. * `SELECT id, name FROM things d UNION ALL SELECT id, title FROM articles a`
  1411. *
  1412. * @param string|\Cake\Database\Query $query full SQL query to be used in UNION operator
  1413. * @param bool $overwrite whether to reset the list of queries to be operated or not
  1414. * @return $this
  1415. */
  1416. public function unionAll($query, $overwrite = false)
  1417. {
  1418. if ($overwrite) {
  1419. $this->_parts['union'] = [];
  1420. }
  1421. $this->_parts['union'][] = [
  1422. 'all' => true,
  1423. 'query' => $query,
  1424. ];
  1425. $this->_dirty();
  1426. return $this;
  1427. }
  1428. /**
  1429. * Create an insert query.
  1430. *
  1431. * Note calling this method will reset any data previously set
  1432. * with Query::values().
  1433. *
  1434. * @param array $columns The columns to insert into.
  1435. * @param string[] $types A map between columns & their datatypes.
  1436. * @return $this
  1437. * @throws \RuntimeException When there are 0 columns.
  1438. */
  1439. public function insert(array $columns, array $types = [])
  1440. {
  1441. if (empty($columns)) {
  1442. throw new RuntimeException('At least 1 column is required to perform an insert.');
  1443. }
  1444. $this->_dirty();
  1445. $this->_type = 'insert';
  1446. $this->_parts['insert'][1] = $columns;
  1447. if (!$this->_parts['values']) {
  1448. $this->_parts['values'] = new ValuesExpression($columns, $this->getTypeMap()->setTypes($types));
  1449. } else {
  1450. $this->_parts['values']->setColumns($columns);
  1451. }
  1452. return $this;
  1453. }
  1454. /**
  1455. * Set the table name for insert queries.
  1456. *
  1457. * @param string $table The table name to insert into.
  1458. * @return $this
  1459. */
  1460. public function into($table)
  1461. {
  1462. $this->_dirty();
  1463. $this->_type = 'insert';
  1464. $this->_parts['insert'][0] = $table;
  1465. return $this;
  1466. }
  1467. /**
  1468. * Creates an expression that refers to an identifier. Identifiers are used to refer to field names and allow
  1469. * the SQL compiler to apply quotes or escape the identifier.
  1470. *
  1471. * The value is used as is, and you might be required to use aliases or include the table reference in
  1472. * the identifier. Do not use this method to inject SQL methods or logical statements.
  1473. *
  1474. * ### Example
  1475. *
  1476. * ```
  1477. * $query->newExpr()->lte('count', $query->identifier('total'));
  1478. * ```
  1479. *
  1480. * @param string $identifier The identifier for an expression
  1481. * @return \Cake\Database\ExpressionInterface
  1482. */
  1483. public function identifier($identifier)
  1484. {
  1485. return new IdentifierExpression($identifier);
  1486. }
  1487. /**
  1488. * Set the values for an insert query.
  1489. *
  1490. * Multi inserts can be performed by calling values() more than one time,
  1491. * or by providing an array of value sets. Additionally $data can be a Query
  1492. * instance to insert data from another SELECT statement.
  1493. *
  1494. * @param array|\Cake\Database\Query $data The data to insert.
  1495. * @return $this
  1496. * @throws \Cake\Database\Exception if you try to set values before declaring columns.
  1497. * Or if you try to set values on non-insert queries.
  1498. */
  1499. public function values($data)
  1500. {
  1501. if ($this->_type !== 'insert') {
  1502. throw new Exception(
  1503. 'You cannot add values before defining columns to use.'
  1504. );
  1505. }
  1506. if (empty($this->_parts['insert'])) {
  1507. throw new Exception(
  1508. 'You cannot add values before defining columns to use.'
  1509. );
  1510. }
  1511. $this->_dirty();
  1512. if ($data instanceof ValuesExpression) {
  1513. $this->_parts['values'] = $data;
  1514. return $this;
  1515. }
  1516. $this->_parts['values']->add($data);
  1517. return $this;
  1518. }
  1519. /**
  1520. * Create an update query.
  1521. *
  1522. * Can be combined with set() and where() methods to create update queries.
  1523. *
  1524. * @param string|\Cake\Database\ExpressionInterface $table The table you want to update.
  1525. * @return $this
  1526. */
  1527. public function update($table)
  1528. {
  1529. if (!is_string($table) && !($table instanceof ExpressionInterface)) {
  1530. $text = 'Table must be of type string or "%s", got "%s"';
  1531. $message = sprintf($text, ExpressionInterface::class, gettype($table));
  1532. throw new InvalidArgumentException($message);
  1533. }
  1534. $this->_dirty();
  1535. $this->_type = 'update';
  1536. $this->_parts['update'][0] = $table;
  1537. return $this;
  1538. }
  1539. /**
  1540. * Set one or many fields to update.
  1541. *
  1542. * ### Examples
  1543. *
  1544. * Passing a string:
  1545. *
  1546. * ```
  1547. * $query->update('articles')->set('title', 'The Title');
  1548. * ```
  1549. *
  1550. * Passing an array:
  1551. *
  1552. * ```
  1553. * $query->update('articles')->set(['title' => 'The Title'], ['title' => 'string']);
  1554. * ```
  1555. *
  1556. * Passing a callable:
  1557. *
  1558. * ```
  1559. * $query->update('articles')->set(function ($exp) {
  1560. * return $exp->eq('title', 'The title', 'string');
  1561. * });
  1562. * ```
  1563. *
  1564. * @param string|array|callable|\Cake\Database\Expression\QueryExpression $key The column name or array of keys
  1565. * + values to set. This can also be a QueryExpression containing a SQL fragment.
  1566. * It can also be a callable, that is required to return an expression object.
  1567. * @param mixed $value The value to update $key to. Can be null if $key is an
  1568. * array or QueryExpression. When $key is an array, this parameter will be
  1569. * used as $types instead.
  1570. * @param array|string $types The column types to treat data as.
  1571. * @return $this
  1572. */
  1573. public function set($key, $value = null, $types = [])
  1574. {
  1575. if (empty($this->_parts['set'])) {
  1576. $this->_parts['set'] = $this->newExpr()->setConjunction(',');
  1577. }
  1578. if ($this->_parts['set']->isCallable($key)) {
  1579. $exp = $this->newExpr()->setConjunction(',');
  1580. $this->_parts['set']->add($key($exp));
  1581. return $this;
  1582. }
  1583. if (is_array($key) || $key instanceof ExpressionInterface) {
  1584. $types = (array)$value;
  1585. $this->_parts['set']->add($key, $types);
  1586. return $this;
  1587. }
  1588. if (is_string($types) && is_string($key)) {
  1589. $types = [$key => $types];
  1590. }
  1591. $this->_parts['set']->eq($key, $value, $types);
  1592. return $this;
  1593. }
  1594. /**
  1595. * Create a delete query.
  1596. *
  1597. * Can be combined with from(), where() and other methods to
  1598. * create delete queries with specific conditions.
  1599. *
  1600. * @param string|null $table The table to use when deleting.
  1601. * @return $this
  1602. */
  1603. public function delete($table = null)
  1604. {
  1605. $this->_dirty();
  1606. $this->_type = 'delete';
  1607. if ($table !== null) {
  1608. $this->from($table);
  1609. }
  1610. return $this;
  1611. }
  1612. /**
  1613. * A string or expression that will be appended to the generated query
  1614. *
  1615. * ### Examples:
  1616. * ```
  1617. * $query->select('id')->where(['author_id' => 1])->epilog('FOR UPDATE');
  1618. * $query
  1619. * ->insert('articles', ['title'])
  1620. * ->values(['author_id' => 1])
  1621. * ->epilog('RETURNING id');
  1622. * ```
  1623. *
  1624. * Epliog content is raw SQL and not suitable for use with user supplied data.
  1625. *
  1626. * @param string|\Cake\Database\ExpressionInterface|null $expression The expression to be appended
  1627. * @return $this
  1628. */
  1629. public function epilog($expression = null)
  1630. {
  1631. $this->_dirty();
  1632. $this->_parts['epilog'] = $expression;
  1633. return $this;
  1634. }
  1635. /**
  1636. * Returns the type of this query (select, insert, update, delete)
  1637. *
  1638. * @return string
  1639. */
  1640. public function type()
  1641. {
  1642. return $this->_type;
  1643. }
  1644. /**
  1645. * Returns a new QueryExpression object. This is a handy function when
  1646. * building complex queries using a fluent interface. You can also override
  1647. * this function in subclasses to use a more specialized QueryExpression class
  1648. * if required.
  1649. *
  1650. * You can optionally pass a single raw SQL string or an array or expressions in
  1651. * any format accepted by \Cake\Database\Expression\QueryExpression:
  1652. *
  1653. * ```
  1654. * $expression = $query->newExpr(); // Returns an empty expression object
  1655. * $expression = $query->newExpr('Table.column = Table2.column'); // Return a raw SQL expression
  1656. * ```
  1657. *
  1658. * @param mixed $rawExpression A string, array or anything you want wrapped in an expression object
  1659. * @return \Cake\Database\Expression\QueryExpression
  1660. */
  1661. public function newExpr($rawExpression = null)
  1662. {
  1663. $expression = new QueryExpression([], $this->getTypeMap());
  1664. if ($rawExpression !== null) {
  1665. $expression->add($rawExpression);
  1666. }
  1667. return $expression;
  1668. }
  1669. /**
  1670. * Returns an instance of a functions builder object that can be used for
  1671. * generating arbitrary SQL functions.
  1672. *
  1673. * ### Example:
  1674. *
  1675. * ```
  1676. * $query->func()->count('*');
  1677. * $query->func()->dateDiff(['2012-01-05', '2012-01-02'])
  1678. * ```
  1679. *
  1680. * @return \Cake\Database\FunctionsBuilder
  1681. */
  1682. public function func()
  1683. {
  1684. if ($this->_functionsBuilder === null) {
  1685. $this->_functionsBuilder = new FunctionsBuilder();
  1686. }
  1687. return $this->_functionsBuilder;
  1688. }
  1689. /**
  1690. * Executes this query and returns a results iterator. This function is required
  1691. * for implementing the IteratorAggregate interface and allows the query to be
  1692. * iterated without having to call execute() manually, thus making it look like
  1693. * a result set instead of the query itself.
  1694. *
  1695. * @return \Cake\Database\StatementInterface|null
  1696. */
  1697. public function getIterator()
  1698. {
  1699. if ($this->_iterator === null || $this->_dirty) {
  1700. $this->_iterator = $this->execute();
  1701. }
  1702. return $this->_iterator;
  1703. }
  1704. /**
  1705. * Returns any data that was stored in the specified clause. This is useful for
  1706. * modifying any internal part of the query and it is used by the SQL dialects
  1707. * to transform the query accordingly before it is executed. The valid clauses that
  1708. * can be retrieved are: delete, update, set, insert, values, select, distinct,
  1709. * from, join, set, where, group, having, order, limit, offset and union.
  1710. *
  1711. * The return value for each of those parts may vary. Some clauses use QueryExpression
  1712. * to internally store their state, some use arrays and others may use booleans or
  1713. * integers. This is summary of the return types for each clause.
  1714. *
  1715. * - update: string The name of the table to update
  1716. * - set: QueryExpression
  1717. * - insert: array, will return an array containing the table + columns.
  1718. * - values: ValuesExpression
  1719. * - select: array, will return empty array when no fields are set
  1720. * - distinct: boolean
  1721. * - from: array of tables
  1722. * - join: array
  1723. * - set: array
  1724. * - where: QueryExpression, returns null when not set
  1725. * - group: array
  1726. * - having: QueryExpression, returns null when not set
  1727. * - order: OrderByExpression, returns null when not set
  1728. * - limit: integer or QueryExpression, null when not set
  1729. * - offset: integer or QueryExpression, null when not set
  1730. * - union: array
  1731. *
  1732. * @param string $name name of the clause to be returned
  1733. * @return mixed
  1734. * @throws \InvalidArgumentException When the named clause does not exist.
  1735. */
  1736. public function clause($name)
  1737. {
  1738. if (!array_key_exists($name, $this->_parts)) {
  1739. $clauses = implode(', ', array_keys($this->_parts));
  1740. throw new InvalidArgumentException("The '$name' clause is not defined. Valid clauses are: $clauses");
  1741. }
  1742. return $this->_parts[$name];
  1743. }
  1744. /**
  1745. * Registers a callback to be executed for each result that is fetched from the
  1746. * result set, the callback function will receive as first parameter an array with
  1747. * the raw data from the database for every row that is fetched and must return the
  1748. * row with any possible modifications.
  1749. *
  1750. * Callbacks will be executed lazily, if only 3 rows are fetched for database it will
  1751. * called 3 times, event though there might be more rows to be fetched in the cursor.
  1752. *
  1753. * Callbacks are stacked in the order they are registered, if you wish to reset the stack
  1754. * the call this function with the second parameter set to true.
  1755. *
  1756. * If you wish to remove all decorators from the stack, set the first parameter
  1757. * to null and the second to true.
  1758. *
  1759. * ### Example
  1760. *
  1761. * ```
  1762. * $query->decorateResults(function ($row) {
  1763. * $row['order_total'] = $row['subtotal'] + ($row['subtotal'] * $row['tax']);
  1764. * return $row;
  1765. * });
  1766. * ```
  1767. *
  1768. * @param callable|null $callback The callback to invoke when results are fetched.
  1769. * @param bool $overwrite Whether or not this should append or replace all existing decorators.
  1770. * @return $this
  1771. */
  1772. public function decorateResults($callback, $overwrite = false)
  1773. {
  1774. if ($overwrite) {
  1775. $this->_resultDecorators = [];
  1776. }
  1777. if ($callback !== null) {
  1778. $this->_resultDecorators[] = $callback;
  1779. }
  1780. return $this;
  1781. }
  1782. /**
  1783. * This function works similar to the traverse() function, with the difference
  1784. * that it does a full depth traversal of the entire expression tree. This will execute
  1785. * the provided callback function for each ExpressionInterface object that is
  1786. * stored inside this query at any nesting depth in any part of the query.
  1787. *
  1788. * Callback will receive as first parameter the currently visited expression.
  1789. *
  1790. * @param callable $callback the function to be executed for each ExpressionInterface
  1791. * found inside this query.
  1792. * @return $this|null
  1793. */
  1794. public function traverseExpressions(callable $callback)
  1795. {
  1796. $visitor = function ($expression) use (&$visitor, $callback) {
  1797. if (is_array($expression)) {
  1798. foreach ($expression as $e) {
  1799. $visitor($e);
  1800. }
  1801. return null;
  1802. }
  1803. if ($expression instanceof ExpressionInterface) {
  1804. $expression->traverse($visitor);
  1805. if (!($expression instanceof self)) {
  1806. $callback($expression);
  1807. }
  1808. }
  1809. };
  1810. return $this->traverse($visitor);
  1811. }
  1812. /**
  1813. * Associates a query placeholder to a value and a type.
  1814. *
  1815. * ```
  1816. * $query->bind(':id', 1, 'integer');
  1817. * ```
  1818. *
  1819. * @param string|int $param placeholder to be replaced with quoted version
  1820. * of $value
  1821. * @param mixed $value The value to be bound
  1822. * @param string|int $type the mapped type name, used for casting when sending
  1823. * to database
  1824. * @return $this
  1825. */
  1826. public function bind($param, $value, $type = 'string')
  1827. {
  1828. $this->getValueBinder()->bind($param, $value, $type);
  1829. return $this;
  1830. }
  1831. /**
  1832. * Returns the currently used ValueBinder instance.
  1833. *
  1834. * A ValueBinder is responsible for generating query placeholders and temporarily
  1835. * associate values to those placeholders so that they can be passed correctly
  1836. * to the statement object.
  1837. *
  1838. * @return \Cake\Database\ValueBinder
  1839. */
  1840. public function getValueBinder()
  1841. {
  1842. if ($this->_valueBinder === null) {
  1843. $this->_valueBinder = new ValueBinder();
  1844. }
  1845. return $this->_valueBinder;
  1846. }
  1847. /**
  1848. * Overwrite the current value binder
  1849. *
  1850. * A ValueBinder is responsible for generating query placeholders and temporarily
  1851. * associate values to those placeholders so that they can be passed correctly
  1852. * to the statement object.
  1853. *
  1854. * @param \Cake\Database\ValueBinder|false $binder The binder or false to disable binding.
  1855. * @return $this
  1856. */
  1857. public function setValueBinder($binder)
  1858. {
  1859. $this->_valueBinder = $binder;
  1860. return $this;
  1861. }
  1862. /**
  1863. * Returns the currently used ValueBinder instance. If a value is passed,
  1864. * it will be set as the new instance to be used.
  1865. *
  1866. * A ValueBinder is responsible for generating query placeholders and temporarily
  1867. * associate values to those placeholders so that they can be passed correctly
  1868. * to the statement object.
  1869. *
  1870. * @deprecated 3.5.0 Use setValueBinder()/getValueBinder() instead.
  1871. * @param \Cake\Database\ValueBinder|false|null $binder new instance to be set. If no value is passed the
  1872. * default one will be returned
  1873. * @return $this|\Cake\Database\ValueBinder
  1874. */
  1875. public function valueBinder($binder = null)
  1876. {
  1877. deprecationWarning('Query::valueBinder() is deprecated. Use Query::getValueBinder()/setValueBinder() instead.');
  1878. if ($binder === null) {
  1879. if ($this->_valueBinder === null) {
  1880. $this->_valueBinder = new ValueBinder();
  1881. }
  1882. return $this->_valueBinder;
  1883. }
  1884. $this->_valueBinder = $binder;
  1885. return $this;
  1886. }
  1887. /**
  1888. * Enables/Disables buffered results.
  1889. *
  1890. * When enabled the results returned by this Query will be
  1891. * buffered. This enables you to iterate a result set multiple times, or
  1892. * both cache and iterate it.
  1893. *
  1894. * When disabled it will consume less memory as fetched results are not
  1895. * remembered for future iterations.
  1896. *
  1897. * @param bool $enable Whether or not to enable buffering
  1898. * @return $this
  1899. */
  1900. public function enableBufferedResults($enable = true)
  1901. {
  1902. $this->_dirty();
  1903. $this->_useBufferedResults = (bool)$enable;
  1904. return $this;
  1905. }
  1906. /**
  1907. * Disables buffered results.
  1908. *
  1909. * Disabling buffering will consume less memory as fetched results are not
  1910. * remembered for future iterations.
  1911. *
  1912. * @return $this
  1913. */
  1914. public function disableBufferedResults()
  1915. {
  1916. $this->_dirty();
  1917. $this->_useBufferedResults = false;
  1918. return $this;
  1919. }
  1920. /**
  1921. * Returns whether buffered results are enabled/disabled.
  1922. *
  1923. * When enabled the results returned by this Query will be
  1924. * buffered. This enables you to iterate a result set multiple times, or
  1925. * both cache and iterate it.
  1926. *
  1927. * When disabled it will consume less memory as fetched results are not
  1928. * remembered for future iterations.
  1929. *
  1930. * @return bool
  1931. */
  1932. public function isBufferedResultsEnabled()
  1933. {
  1934. return $this->_useBufferedResults;
  1935. }
  1936. /**
  1937. * Enable/Disable buffered results.
  1938. *
  1939. * When enabled the results returned by this Query will be
  1940. * buffered. This enables you to iterate a result set multiple times, or
  1941. * both cache and iterate it.
  1942. *
  1943. * When disabled it will consume less memory as fetched results are not
  1944. * remembered for future iterations.
  1945. *
  1946. * If called with no arguments, it will return whether or not buffering is
  1947. * enabled.
  1948. *
  1949. * @deprecated 3.4.0 Use enableBufferedResults()/isBufferedResultsEnabled() instead.
  1950. * @param bool|null $enable Whether or not to enable buffering
  1951. * @return bool|$this
  1952. */
  1953. public function bufferResults($enable = null)
  1954. {
  1955. deprecationWarning(
  1956. 'Query::bufferResults() is deprecated. ' .
  1957. 'Use Query::enableBufferedResults()/isBufferedResultsEnabled() instead.'
  1958. );
  1959. if ($enable !== null) {
  1960. return $this->enableBufferedResults($enable);
  1961. }
  1962. return $this->isBufferedResultsEnabled();
  1963. }
  1964. /**
  1965. * Sets the TypeMap class where the types for each of the fields in the
  1966. * select clause are stored.
  1967. *
  1968. * @param \Cake\Database\TypeMap $typeMap The map object to use
  1969. * @return $this
  1970. */
  1971. public function setSelectTypeMap(TypeMap $typeMap)
  1972. {
  1973. $this->_selectTypeMap = $typeMap;
  1974. $this->_dirty();
  1975. return $this;
  1976. }
  1977. /**
  1978. * Gets the TypeMap class where the types for each of the fields in the
  1979. * select clause are stored.
  1980. *
  1981. * @return \Cake\Database\TypeMap
  1982. */
  1983. public function getSelectTypeMap()
  1984. {
  1985. if ($this->_selectTypeMap === null) {
  1986. $this->_selectTypeMap = new TypeMap();
  1987. }
  1988. return $this->_selectTypeMap;
  1989. }
  1990. /**
  1991. * Disables the automatic casting of fields to their corresponding PHP data type
  1992. *
  1993. * @return $this
  1994. */
  1995. public function disableResultsCasting()
  1996. {
  1997. $this->typeCastEnabled = false;
  1998. return $this;
  1999. }
  2000. /**
  2001. * Enables the automatic casting of fields to their corresponding type
  2002. *
  2003. * @return $this
  2004. */
  2005. public function enableResultsCasting()
  2006. {
  2007. $this->typeCastEnabled = true;
  2008. return $this;
  2009. }
  2010. /**
  2011. * Sets the TypeMap class where the types for each of the fields in the
  2012. * select clause are stored.
  2013. *
  2014. * When called with no arguments, the current TypeMap object is returned.
  2015. *
  2016. * @deprecated 3.4.0 Use setSelectTypeMap()/getSelectTypeMap() instead.
  2017. * @param \Cake\Database\TypeMap|null $typeMap The map object to use
  2018. * @return $this|\Cake\Database\TypeMap
  2019. */
  2020. public function selectTypeMap(TypeMap $typeMap = null)
  2021. {
  2022. deprecationWarning(
  2023. 'Query::selectTypeMap() is deprecated. ' .
  2024. 'Use Query::setSelectTypeMap()/getSelectTypeMap() instead.'
  2025. );
  2026. if ($typeMap !== null) {
  2027. return $this->setSelectTypeMap($typeMap);
  2028. }
  2029. return $this->getSelectTypeMap();
  2030. }
  2031. /**
  2032. * Auxiliary function used to wrap the original statement from the driver with
  2033. * any registered callbacks.
  2034. *
  2035. * @param \Cake\Database\StatementInterface $statement to be decorated
  2036. * @return \Cake\Database\Statement\CallbackStatement
  2037. */
  2038. protected function _decorateStatement($statement)
  2039. {
  2040. $typeMap = $this->getSelectTypeMap();
  2041. $driver = $this->getConnection()->getDriver();
  2042. if ($this->typeCastEnabled && $typeMap->toArray()) {
  2043. $statement = new CallbackStatement($statement, $driver, new FieldTypeConverter($typeMap, $driver));
  2044. }
  2045. foreach ($this->_resultDecorators as $f) {
  2046. $statement = new CallbackStatement($statement, $driver, $f);
  2047. }
  2048. return $statement;
  2049. }
  2050. /**
  2051. * Helper function used to build conditions by composing QueryExpression objects.
  2052. *
  2053. * @param string $part Name of the query part to append the new part to
  2054. * @param string|array|\Cake\Database\ExpressionInterface|callable|null $append Expression or builder function to append.
  2055. * @param string $conjunction type of conjunction to be used to operate part
  2056. * @param array $types associative array of type names used to bind values to query
  2057. * @return void
  2058. */
  2059. protected function _conjugate($part, $append, $conjunction, $types)
  2060. {
  2061. $expression = $this->_parts[$part] ?: $this->newExpr();
  2062. if (empty($append)) {
  2063. $this->_parts[$part] = $expression;
  2064. return;
  2065. }
  2066. if ($expression->isCallable($append)) {
  2067. $append = $append($this->newExpr(), $this);
  2068. }
  2069. if ($expression->getConjunction() === $conjunction) {
  2070. $expression->add($append, $types);
  2071. } else {
  2072. $expression = $this->newExpr()
  2073. ->setConjunction($conjunction)
  2074. ->add([$expression, $append], $types);
  2075. }
  2076. $this->_parts[$part] = $expression;
  2077. $this->_dirty();
  2078. }
  2079. /**
  2080. * Marks a query as dirty, removing any preprocessed information
  2081. * from in memory caching.
  2082. *
  2083. * @return void
  2084. */
  2085. protected function _dirty()
  2086. {
  2087. $this->_dirty = true;
  2088. if ($this->_iterator && $this->_valueBinder) {
  2089. $this->getValueBinder()->reset();
  2090. }
  2091. }
  2092. /**
  2093. * Do a deep clone on this object.
  2094. *
  2095. * Will clone all of the expression objects used in
  2096. * each of the clauses, as well as the valueBinder.
  2097. *
  2098. * @return void
  2099. */
  2100. public function __clone()
  2101. {
  2102. $this->_iterator = null;
  2103. if ($this->_valueBinder !== null) {
  2104. $this->_valueBinder = clone $this->_valueBinder;
  2105. }
  2106. if ($this->_selectTypeMap !== null) {
  2107. $this->_selectTypeMap = clone $this->_selectTypeMap;
  2108. }
  2109. foreach ($this->_parts as $name => $part) {
  2110. if (empty($part)) {
  2111. continue;
  2112. }
  2113. if (is_array($part)) {
  2114. foreach ($part as $i => $piece) {
  2115. if ($piece instanceof ExpressionInterface) {
  2116. $this->_parts[$name][$i] = clone $piece;
  2117. }
  2118. }
  2119. }
  2120. if ($part instanceof ExpressionInterface) {
  2121. $this->_parts[$name] = clone $part;
  2122. }
  2123. }
  2124. }
  2125. /**
  2126. * Returns string representation of this query (complete SQL statement).
  2127. *
  2128. * @return string
  2129. */
  2130. public function __toString()
  2131. {
  2132. return $this->sql();
  2133. }
  2134. /**
  2135. * Returns an array that can be used to describe the internal state of this
  2136. * object.
  2137. *
  2138. * @return array
  2139. */
  2140. public function __debugInfo()
  2141. {
  2142. try {
  2143. set_error_handler(function ($errno, $errstr) {
  2144. throw new RuntimeException($errstr, $errno);
  2145. }, E_ALL);
  2146. $sql = $this->sql();
  2147. $params = $this->getValueBinder()->bindings();
  2148. } catch (RuntimeException $e) {
  2149. $sql = 'SQL could not be generated for this query as it is incomplete.';
  2150. $params = [];
  2151. } finally {
  2152. restore_error_handler();
  2153. }
  2154. return [
  2155. '(help)' => 'This is a Query object, to get the results execute or iterate it.',
  2156. 'sql' => $sql,
  2157. 'params' => $params,
  2158. 'defaultTypes' => $this->getDefaultTypes(),
  2159. 'decorators' => count($this->_resultDecorators),
  2160. 'executed' => $this->_iterator ? true : false,
  2161. ];
  2162. }
  2163. }