Query.php 57 KB

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