Select.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  1. <?php
  2. namespace Drupal\Core\Database\Query;
  3. use Drupal\Core\Database\Database;
  4. use Drupal\Core\Database\Connection;
  5. /**
  6. * Query builder for SELECT statements.
  7. *
  8. * @ingroup database
  9. */
  10. class Select extends Query implements SelectInterface {
  11. use QueryConditionTrait;
  12. /**
  13. * The fields to SELECT.
  14. *
  15. * @var array
  16. */
  17. protected $fields = [];
  18. /**
  19. * The expressions to SELECT as virtual fields.
  20. *
  21. * @var array
  22. */
  23. protected $expressions = [];
  24. /**
  25. * The tables against which to JOIN.
  26. *
  27. * This property is a nested array. Each entry is an array representing
  28. * a single table against which to join. The structure of each entry is:
  29. *
  30. * array(
  31. * 'type' => $join_type (one of INNER, LEFT OUTER, RIGHT OUTER),
  32. * 'table' => $table,
  33. * 'alias' => $alias_of_the_table,
  34. * 'condition' => $join_condition (string or Condition object),
  35. * 'arguments' => $array_of_arguments_for_placeholders_in_the condition.
  36. * 'all_fields' => TRUE to SELECT $alias.*, FALSE or NULL otherwise.
  37. * )
  38. *
  39. * If $table is a string, it is taken as the name of a table. If it is
  40. * a Select query object, it is taken as a subquery.
  41. *
  42. * If $join_condition is a Condition object, any arguments should be
  43. * incorporated into the object; a separate array of arguments does not
  44. * need to be provided.
  45. *
  46. * @var array
  47. */
  48. protected $tables = [];
  49. /**
  50. * The fields by which to order this query.
  51. *
  52. * This is an associative array. The keys are the fields to order, and the value
  53. * is the direction to order, either ASC or DESC.
  54. *
  55. * @var array
  56. */
  57. protected $order = [];
  58. /**
  59. * The fields by which to group.
  60. *
  61. * @var array
  62. */
  63. protected $group = [];
  64. /**
  65. * The conditional object for the HAVING clause.
  66. *
  67. * @var \Drupal\Core\Database\Query\Condition
  68. */
  69. protected $having;
  70. /**
  71. * Whether or not this query should be DISTINCT
  72. *
  73. * @var bool
  74. */
  75. protected $distinct = FALSE;
  76. /**
  77. * The range limiters for this query.
  78. *
  79. * @var array
  80. */
  81. protected $range;
  82. /**
  83. * An array whose elements specify a query to UNION, and the UNION type. The
  84. * 'type' key may be '', 'ALL', or 'DISTINCT' to represent a 'UNION',
  85. * 'UNION ALL', or 'UNION DISTINCT' statement, respectively.
  86. *
  87. * All entries in this array will be applied from front to back, with the
  88. * first query to union on the right of the original query, the second union
  89. * to the right of the first, etc.
  90. *
  91. * @var array
  92. */
  93. protected $union = [];
  94. /**
  95. * Indicates if preExecute() has already been called.
  96. * @var bool
  97. */
  98. protected $prepared = FALSE;
  99. /**
  100. * The FOR UPDATE status
  101. *
  102. * @var bool
  103. */
  104. protected $forUpdate = FALSE;
  105. /**
  106. * Constructs a Select object.
  107. *
  108. * @param string $table
  109. * The name of the table that is being queried.
  110. * @param string $alias
  111. * The alias for the table.
  112. * @param \Drupal\Core\Database\Connection $connection
  113. * Database connection object.
  114. * @param array $options
  115. * Array of query options.
  116. */
  117. public function __construct($table, $alias, Connection $connection, $options = []) {
  118. $options['return'] = Database::RETURN_STATEMENT;
  119. parent::__construct($connection, $options);
  120. $conjunction = isset($options['conjunction']) ? $options['conjunction'] : 'AND';
  121. $this->condition = new Condition($conjunction);
  122. $this->having = new Condition($conjunction);
  123. $this->addJoin(NULL, $table, $alias);
  124. }
  125. /**
  126. * {@inheritdoc}
  127. */
  128. public function addTag($tag) {
  129. $this->alterTags[$tag] = 1;
  130. return $this;
  131. }
  132. /**
  133. * {@inheritdoc}
  134. */
  135. public function hasTag($tag) {
  136. return isset($this->alterTags[$tag]);
  137. }
  138. /**
  139. * {@inheritdoc}
  140. */
  141. public function hasAllTags() {
  142. return !(boolean) array_diff(func_get_args(), array_keys($this->alterTags));
  143. }
  144. /**
  145. * {@inheritdoc}
  146. */
  147. public function hasAnyTag() {
  148. return (boolean) array_intersect(func_get_args(), array_keys($this->alterTags));
  149. }
  150. /**
  151. * {@inheritdoc}
  152. */
  153. public function addMetaData($key, $object) {
  154. $this->alterMetaData[$key] = $object;
  155. return $this;
  156. }
  157. /**
  158. * {@inheritdoc}
  159. */
  160. public function getMetaData($key) {
  161. return isset($this->alterMetaData[$key]) ? $this->alterMetaData[$key] : NULL;
  162. }
  163. /**
  164. * {@inheritdoc}
  165. */
  166. public function arguments() {
  167. if (!$this->compiled()) {
  168. return NULL;
  169. }
  170. $args = $this->condition->arguments() + $this->having->arguments();
  171. foreach ($this->tables as $table) {
  172. if ($table['arguments']) {
  173. $args += $table['arguments'];
  174. }
  175. // If this table is a subquery, grab its arguments recursively.
  176. if ($table['table'] instanceof SelectInterface) {
  177. $args += $table['table']->arguments();
  178. }
  179. // If the join condition is an object, grab its arguments recursively.
  180. if (!empty($table['condition']) && $table['condition'] instanceof ConditionInterface) {
  181. $args += $table['condition']->arguments();
  182. }
  183. }
  184. foreach ($this->expressions as $expression) {
  185. if ($expression['arguments']) {
  186. $args += $expression['arguments'];
  187. }
  188. }
  189. // If there are any dependent queries to UNION,
  190. // incorporate their arguments recursively.
  191. foreach ($this->union as $union) {
  192. $args += $union['query']->arguments();
  193. }
  194. return $args;
  195. }
  196. /**
  197. * {@inheritdoc}
  198. */
  199. public function compile(Connection $connection, PlaceholderInterface $queryPlaceholder) {
  200. $this->condition->compile($connection, $queryPlaceholder);
  201. $this->having->compile($connection, $queryPlaceholder);
  202. foreach ($this->tables as $table) {
  203. // If this table is a subquery, compile it recursively.
  204. if ($table['table'] instanceof SelectInterface) {
  205. $table['table']->compile($connection, $queryPlaceholder);
  206. }
  207. // Make sure join conditions are also compiled.
  208. if (!empty($table['condition']) && $table['condition'] instanceof ConditionInterface) {
  209. $table['condition']->compile($connection, $queryPlaceholder);
  210. }
  211. }
  212. // If there are any dependent queries to UNION, compile it recursively.
  213. foreach ($this->union as $union) {
  214. $union['query']->compile($connection, $queryPlaceholder);
  215. }
  216. }
  217. /**
  218. * {@inheritdoc}
  219. */
  220. public function compiled() {
  221. if (!$this->condition->compiled() || !$this->having->compiled()) {
  222. return FALSE;
  223. }
  224. foreach ($this->tables as $table) {
  225. // If this table is a subquery, check its status recursively.
  226. if ($table['table'] instanceof SelectInterface) {
  227. if (!$table['table']->compiled()) {
  228. return FALSE;
  229. }
  230. }
  231. if (!empty($table['condition']) && $table['condition'] instanceof ConditionInterface) {
  232. if (!$table['condition']->compiled()) {
  233. return FALSE;
  234. }
  235. }
  236. }
  237. foreach ($this->union as $union) {
  238. if (!$union['query']->compiled()) {
  239. return FALSE;
  240. }
  241. }
  242. return TRUE;
  243. }
  244. /**
  245. * {@inheritdoc}
  246. */
  247. public function havingCondition($field, $value = NULL, $operator = NULL) {
  248. $this->having->condition($field, $value, $operator);
  249. return $this;
  250. }
  251. /**
  252. * {@inheritdoc}
  253. */
  254. public function &havingConditions() {
  255. return $this->having->conditions();
  256. }
  257. /**
  258. * {@inheritdoc}
  259. */
  260. public function havingArguments() {
  261. return $this->having->arguments();
  262. }
  263. /**
  264. * {@inheritdoc}
  265. */
  266. public function having($snippet, $args = []) {
  267. $this->having->where($snippet, $args);
  268. return $this;
  269. }
  270. /**
  271. * {@inheritdoc}
  272. */
  273. public function havingCompile(Connection $connection) {
  274. $this->having->compile($connection, $this);
  275. }
  276. /**
  277. * {@inheritdoc}
  278. */
  279. public function extend($extender_name) {
  280. $override_class = $extender_name . '_' . $this->connection->driver();
  281. if (class_exists($override_class)) {
  282. $extender_name = $override_class;
  283. }
  284. return new $extender_name($this, $this->connection);
  285. }
  286. /**
  287. * {@inheritdoc}
  288. */
  289. public function havingIsNull($field) {
  290. $this->having->isNull($field);
  291. return $this;
  292. }
  293. /**
  294. * {@inheritdoc}
  295. */
  296. public function havingIsNotNull($field) {
  297. $this->having->isNotNull($field);
  298. return $this;
  299. }
  300. /**
  301. * {@inheritdoc}
  302. */
  303. public function havingExists(SelectInterface $select) {
  304. $this->having->exists($select);
  305. return $this;
  306. }
  307. /**
  308. * {@inheritdoc}
  309. */
  310. public function havingNotExists(SelectInterface $select) {
  311. $this->having->notExists($select);
  312. return $this;
  313. }
  314. /**
  315. * {@inheritdoc}
  316. */
  317. public function forUpdate($set = TRUE) {
  318. if (isset($set)) {
  319. $this->forUpdate = $set;
  320. }
  321. return $this;
  322. }
  323. /**
  324. * {@inheritdoc}
  325. */
  326. public function &getFields() {
  327. return $this->fields;
  328. }
  329. /**
  330. * {@inheritdoc}
  331. */
  332. public function &getExpressions() {
  333. return $this->expressions;
  334. }
  335. /**
  336. * {@inheritdoc}
  337. */
  338. public function &getOrderBy() {
  339. return $this->order;
  340. }
  341. /**
  342. * {@inheritdoc}
  343. */
  344. public function &getGroupBy() {
  345. return $this->group;
  346. }
  347. /**
  348. * {@inheritdoc}
  349. */
  350. public function &getTables() {
  351. return $this->tables;
  352. }
  353. /**
  354. * {@inheritdoc}
  355. */
  356. public function &getUnion() {
  357. return $this->union;
  358. }
  359. /**
  360. * {@inheritdoc}
  361. */
  362. public function escapeLike($string) {
  363. return $this->connection->escapeLike($string);
  364. }
  365. /**
  366. * {@inheritdoc}
  367. */
  368. public function escapeField($string) {
  369. return $this->connection->escapeField($string);
  370. }
  371. /**
  372. * {@inheritdoc}
  373. */
  374. public function getArguments(PlaceholderInterface $queryPlaceholder = NULL) {
  375. if (!isset($queryPlaceholder)) {
  376. $queryPlaceholder = $this;
  377. }
  378. $this->compile($this->connection, $queryPlaceholder);
  379. return $this->arguments();
  380. }
  381. /**
  382. * {@inheritdoc}
  383. */
  384. public function isPrepared() {
  385. return $this->prepared;
  386. }
  387. /**
  388. * {@inheritdoc}
  389. */
  390. public function preExecute(SelectInterface $query = NULL) {
  391. // If no query object is passed in, use $this.
  392. if (!isset($query)) {
  393. $query = $this;
  394. }
  395. // Only execute this once.
  396. if ($query->isPrepared()) {
  397. return TRUE;
  398. }
  399. // Modules may alter all queries or only those having a particular tag.
  400. if (isset($this->alterTags)) {
  401. // Many contrib modules as well as Entity Reference in core assume that
  402. // query tags used for access-checking purposes follow the pattern
  403. // $entity_type . '_access'. But this is not the case for taxonomy terms,
  404. // since the core Taxonomy module used to add term_access instead of
  405. // taxonomy_term_access to its queries. Provide backwards compatibility
  406. // by adding both tags here instead of attempting to fix all contrib
  407. // modules in a coordinated effort.
  408. // TODO:
  409. // - Extract this mechanism into a hook as part of a public (non-security)
  410. // issue.
  411. // - Emit E_USER_DEPRECATED if term_access is used.
  412. // https://www.drupal.org/node/2575081
  413. $term_access_tags = ['term_access' => 1, 'taxonomy_term_access' => 1];
  414. if (array_intersect_key($this->alterTags, $term_access_tags)) {
  415. $this->alterTags += $term_access_tags;
  416. }
  417. $hooks = ['query'];
  418. foreach ($this->alterTags as $tag => $value) {
  419. $hooks[] = 'query_' . $tag;
  420. }
  421. \Drupal::moduleHandler()->alter($hooks, $query);
  422. }
  423. $this->prepared = TRUE;
  424. // Now also prepare any sub-queries.
  425. foreach ($this->tables as $table) {
  426. if ($table['table'] instanceof SelectInterface) {
  427. $table['table']->preExecute();
  428. }
  429. }
  430. foreach ($this->union as $union) {
  431. $union['query']->preExecute();
  432. }
  433. return $this->prepared;
  434. }
  435. /**
  436. * {@inheritdoc}
  437. */
  438. public function execute() {
  439. // If validation fails, simply return NULL.
  440. // Note that validation routines in preExecute() may throw exceptions instead.
  441. if (!$this->preExecute()) {
  442. return NULL;
  443. }
  444. $args = $this->getArguments();
  445. return $this->connection->query((string) $this, $args, $this->queryOptions);
  446. }
  447. /**
  448. * {@inheritdoc}
  449. */
  450. public function distinct($distinct = TRUE) {
  451. $this->distinct = $distinct;
  452. return $this;
  453. }
  454. /**
  455. * {@inheritdoc}
  456. */
  457. public function addField($table_alias, $field, $alias = NULL) {
  458. // If no alias is specified, first try the field name itself.
  459. if (empty($alias)) {
  460. $alias = $field;
  461. }
  462. // If that's already in use, try the table name and field name.
  463. if (!empty($this->fields[$alias])) {
  464. $alias = $table_alias . '_' . $field;
  465. }
  466. // If that is already used, just add a counter until we find an unused alias.
  467. $alias_candidate = $alias;
  468. $count = 2;
  469. while (!empty($this->fields[$alias_candidate])) {
  470. $alias_candidate = $alias . '_' . $count++;
  471. }
  472. $alias = $alias_candidate;
  473. $this->fields[$alias] = [
  474. 'field' => $field,
  475. 'table' => $table_alias,
  476. 'alias' => $alias,
  477. ];
  478. return $alias;
  479. }
  480. /**
  481. * {@inheritdoc}
  482. */
  483. public function fields($table_alias, array $fields = []) {
  484. if ($fields) {
  485. foreach ($fields as $field) {
  486. // We don't care what alias was assigned.
  487. $this->addField($table_alias, $field);
  488. }
  489. }
  490. else {
  491. // We want all fields from this table.
  492. $this->tables[$table_alias]['all_fields'] = TRUE;
  493. }
  494. return $this;
  495. }
  496. /**
  497. * {@inheritdoc}
  498. */
  499. public function addExpression($expression, $alias = NULL, $arguments = []) {
  500. if (empty($alias)) {
  501. $alias = 'expression';
  502. }
  503. $alias_candidate = $alias;
  504. $count = 2;
  505. while (!empty($this->expressions[$alias_candidate])) {
  506. $alias_candidate = $alias . '_' . $count++;
  507. }
  508. $alias = $alias_candidate;
  509. $this->expressions[$alias] = [
  510. 'expression' => $expression,
  511. 'alias' => $alias,
  512. 'arguments' => $arguments,
  513. ];
  514. return $alias;
  515. }
  516. /**
  517. * {@inheritdoc}
  518. */
  519. public function join($table, $alias = NULL, $condition = NULL, $arguments = []) {
  520. return $this->addJoin('INNER', $table, $alias, $condition, $arguments);
  521. }
  522. /**
  523. * {@inheritdoc}
  524. */
  525. public function innerJoin($table, $alias = NULL, $condition = NULL, $arguments = []) {
  526. return $this->addJoin('INNER', $table, $alias, $condition, $arguments);
  527. }
  528. /**
  529. * {@inheritdoc}
  530. */
  531. public function leftJoin($table, $alias = NULL, $condition = NULL, $arguments = []) {
  532. return $this->addJoin('LEFT OUTER', $table, $alias, $condition, $arguments);
  533. }
  534. /**
  535. * {@inheritdoc}
  536. */
  537. public function rightJoin($table, $alias = NULL, $condition = NULL, $arguments = []) {
  538. return $this->addJoin('RIGHT OUTER', $table, $alias, $condition, $arguments);
  539. }
  540. /**
  541. * {@inheritdoc}
  542. */
  543. public function addJoin($type, $table, $alias = NULL, $condition = NULL, $arguments = []) {
  544. if (empty($alias)) {
  545. if ($table instanceof SelectInterface) {
  546. $alias = 'subquery';
  547. }
  548. else {
  549. $alias = $table;
  550. }
  551. }
  552. $alias_candidate = $alias;
  553. $count = 2;
  554. while (!empty($this->tables[$alias_candidate])) {
  555. $alias_candidate = $alias . '_' . $count++;
  556. }
  557. $alias = $alias_candidate;
  558. if (is_string($condition)) {
  559. $condition = str_replace('%alias', $alias, $condition);
  560. }
  561. $this->tables[$alias] = [
  562. 'join type' => $type,
  563. 'table' => $table,
  564. 'alias' => $alias,
  565. 'condition' => $condition,
  566. 'arguments' => $arguments,
  567. ];
  568. return $alias;
  569. }
  570. /**
  571. * {@inheritdoc}
  572. */
  573. public function orderBy($field, $direction = 'ASC') {
  574. // Only allow ASC and DESC, default to ASC.
  575. $direction = strtoupper($direction) == 'DESC' ? 'DESC' : 'ASC';
  576. $this->order[$field] = $direction;
  577. return $this;
  578. }
  579. /**
  580. * {@inheritdoc}
  581. */
  582. public function orderRandom() {
  583. $alias = $this->addExpression('RAND()', 'random_field');
  584. $this->orderBy($alias);
  585. return $this;
  586. }
  587. /**
  588. * {@inheritdoc}
  589. */
  590. public function range($start = NULL, $length = NULL) {
  591. $this->range = $start !== NULL ? ['start' => $start, 'length' => $length] : [];
  592. return $this;
  593. }
  594. /**
  595. * {@inheritdoc}
  596. */
  597. public function union(SelectInterface $query, $type = '') {
  598. // Handle UNION aliasing.
  599. switch ($type) {
  600. // Fold UNION DISTINCT to UNION for better cross database support.
  601. case 'DISTINCT':
  602. case '':
  603. $type = 'UNION';
  604. break;
  605. case 'ALL':
  606. $type = 'UNION ALL';
  607. default:
  608. }
  609. $this->union[] = [
  610. 'type' => $type,
  611. 'query' => $query,
  612. ];
  613. return $this;
  614. }
  615. /**
  616. * {@inheritdoc}
  617. */
  618. public function groupBy($field) {
  619. $this->group[$field] = $field;
  620. return $this;
  621. }
  622. /**
  623. * {@inheritdoc}
  624. */
  625. public function countQuery() {
  626. $count = $this->prepareCountQuery();
  627. $query = $this->connection->select($count, NULL, $this->queryOptions);
  628. $query->addExpression('COUNT(*)');
  629. return $query;
  630. }
  631. /**
  632. * Prepares a count query from the current query object.
  633. *
  634. * @return \Drupal\Core\Database\Query\Select
  635. * A new query object ready to have COUNT(*) performed on it.
  636. */
  637. protected function prepareCountQuery() {
  638. // Create our new query object that we will mutate into a count query.
  639. $count = clone($this);
  640. $group_by = $count->getGroupBy();
  641. $having = $count->havingConditions();
  642. if (!$count->distinct && !isset($having[0])) {
  643. // When not executing a distinct query, we can zero-out existing fields
  644. // and expressions that are not used by a GROUP BY or HAVING. Fields
  645. // listed in a GROUP BY or HAVING clause need to be present in the
  646. // query.
  647. $fields =& $count->getFields();
  648. foreach (array_keys($fields) as $field) {
  649. if (empty($group_by[$field])) {
  650. unset($fields[$field]);
  651. }
  652. }
  653. $expressions =& $count->getExpressions();
  654. foreach (array_keys($expressions) as $field) {
  655. if (empty($group_by[$field])) {
  656. unset($expressions[$field]);
  657. }
  658. }
  659. // Also remove 'all_fields' statements, which are expanded into tablename.*
  660. // when the query is executed.
  661. foreach ($count->tables as &$table) {
  662. unset($table['all_fields']);
  663. }
  664. }
  665. // If we've just removed all fields from the query, make sure there is at
  666. // least one so that the query still runs.
  667. $count->addExpression('1');
  668. // Ordering a count query is a waste of cycles, and breaks on some
  669. // databases anyway.
  670. $orders = &$count->getOrderBy();
  671. $orders = [];
  672. if ($count->distinct && !empty($group_by)) {
  673. // If the query is distinct and contains a GROUP BY, we need to remove the
  674. // distinct because SQL99 does not support counting on distinct multiple fields.
  675. $count->distinct = FALSE;
  676. }
  677. // If there are any dependent queries to UNION, prepare each of those for
  678. // the count query also.
  679. foreach ($count->union as &$union) {
  680. $union['query'] = $union['query']->prepareCountQuery();
  681. }
  682. return $count;
  683. }
  684. /**
  685. * {@inheritdoc}
  686. */
  687. public function __toString() {
  688. // For convenience, we compile the query ourselves if the caller forgot
  689. // to do it. This allows constructs like "(string) $query" to work. When
  690. // the query will be executed, it will be recompiled using the proper
  691. // placeholder generator anyway.
  692. if (!$this->compiled()) {
  693. $this->compile($this->connection, $this);
  694. }
  695. // Create a sanitized comment string to prepend to the query.
  696. $comments = $this->connection->makeComment($this->comments);
  697. // SELECT
  698. $query = $comments . 'SELECT ';
  699. if ($this->distinct) {
  700. $query .= 'DISTINCT ';
  701. }
  702. // FIELDS and EXPRESSIONS
  703. $fields = [];
  704. foreach ($this->tables as $alias => $table) {
  705. if (!empty($table['all_fields'])) {
  706. $fields[] = $this->connection->escapeTable($alias) . '.*';
  707. }
  708. }
  709. foreach ($this->fields as $field) {
  710. // Always use the AS keyword for field aliases, as some
  711. // databases require it (e.g., PostgreSQL).
  712. $fields[] = (isset($field['table']) ? $this->connection->escapeTable($field['table']) . '.' : '') . $this->connection->escapeField($field['field']) . ' AS ' . $this->connection->escapeAlias($field['alias']);
  713. }
  714. foreach ($this->expressions as $expression) {
  715. $fields[] = $expression['expression'] . ' AS ' . $this->connection->escapeAlias($expression['alias']);
  716. }
  717. $query .= implode(', ', $fields);
  718. // FROM - We presume all queries have a FROM, as any query that doesn't won't need the query builder anyway.
  719. $query .= "\nFROM";
  720. foreach ($this->tables as $table) {
  721. $query .= "\n";
  722. if (isset($table['join type'])) {
  723. $query .= $table['join type'] . ' JOIN ';
  724. }
  725. // If the table is a subquery, compile it and integrate it into this query.
  726. if ($table['table'] instanceof SelectInterface) {
  727. // Run preparation steps on this sub-query before converting to string.
  728. $subquery = $table['table'];
  729. $subquery->preExecute();
  730. $table_string = '(' . (string) $subquery . ')';
  731. }
  732. else {
  733. $table_string = $this->connection->escapeTable($table['table']);
  734. // Do not attempt prefixing cross database / schema queries.
  735. if (strpos($table_string, '.') === FALSE) {
  736. $table_string = '{' . $table_string . '}';
  737. }
  738. }
  739. // Don't use the AS keyword for table aliases, as some
  740. // databases don't support it (e.g., Oracle).
  741. $query .= $table_string . ' ' . $this->connection->escapeTable($table['alias']);
  742. if (!empty($table['condition'])) {
  743. $query .= ' ON ' . (string) $table['condition'];
  744. }
  745. }
  746. // WHERE
  747. if (count($this->condition)) {
  748. // There is an implicit string cast on $this->condition.
  749. $query .= "\nWHERE " . $this->condition;
  750. }
  751. // GROUP BY
  752. if ($this->group) {
  753. $query .= "\nGROUP BY " . implode(', ', $this->group);
  754. }
  755. // HAVING
  756. if (count($this->having)) {
  757. // There is an implicit string cast on $this->having.
  758. $query .= "\nHAVING " . $this->having;
  759. }
  760. // UNION is a little odd, as the select queries to combine are passed into
  761. // this query, but syntactically they all end up on the same level.
  762. if ($this->union) {
  763. foreach ($this->union as $union) {
  764. $query .= ' ' . $union['type'] . ' ' . (string) $union['query'];
  765. }
  766. }
  767. // ORDER BY
  768. if ($this->order) {
  769. $query .= "\nORDER BY ";
  770. $fields = [];
  771. foreach ($this->order as $field => $direction) {
  772. $fields[] = $this->connection->escapeField($field) . ' ' . $direction;
  773. }
  774. $query .= implode(', ', $fields);
  775. }
  776. // RANGE
  777. // There is no universal SQL standard for handling range or limit clauses.
  778. // Fortunately, all core-supported databases use the same range syntax.
  779. // Databases that need a different syntax can override this method and
  780. // do whatever alternate logic they need to.
  781. if (!empty($this->range)) {
  782. $query .= "\nLIMIT " . (int) $this->range['length'] . " OFFSET " . (int) $this->range['start'];
  783. }
  784. if ($this->forUpdate) {
  785. $query .= ' FOR UPDATE';
  786. }
  787. return $query;
  788. }
  789. /**
  790. * {@inheritdoc}
  791. */
  792. public function __clone() {
  793. parent::__clone();
  794. // On cloning, also clone the dependent objects. However, we do not
  795. // want to clone the database connection object as that would duplicate the
  796. // connection itself.
  797. $this->condition = clone($this->condition);
  798. $this->having = clone($this->having);
  799. foreach ($this->union as $key => $aggregate) {
  800. $this->union[$key]['query'] = clone($aggregate['query']);
  801. }
  802. foreach ($this->tables as $alias => $table) {
  803. if ($table['table'] instanceof SelectInterface) {
  804. $this->tables[$alias]['table'] = clone $table['table'];
  805. }
  806. }
  807. }
  808. }