Query.php 56 KB

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