Query.php 52 KB

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