3 namespace Drupal\Core\Database\Query;
5 use Drupal\Core\Database\Database;
6 use Drupal\Core\Database\Connection;
9 * Query builder for SELECT statements.
13 class Select extends Query implements SelectInterface {
15 use QueryConditionTrait;
18 * The fields to SELECT.
22 protected $fields = [];
25 * The expressions to SELECT as virtual fields.
29 protected $expressions = [];
32 * The tables against which to JOIN.
34 * This property is a nested array. Each entry is an array representing
35 * a single table against which to join. The structure of each entry is:
38 * 'type' => $join_type (one of INNER, LEFT OUTER, RIGHT OUTER),
40 * 'alias' => $alias_of_the_table,
41 * 'condition' => $join_condition (string or Condition object),
42 * 'arguments' => $array_of_arguments_for_placeholders_in_the condition.
43 * 'all_fields' => TRUE to SELECT $alias.*, FALSE or NULL otherwise.
46 * If $table is a string, it is taken as the name of a table. If it is
47 * a Select query object, it is taken as a subquery.
49 * If $join_condition is a Condition object, any arguments should be
50 * incorporated into the object; a separate array of arguments does not
51 * need to be provided.
55 protected $tables = [];
58 * The fields by which to order this query.
60 * This is an associative array. The keys are the fields to order, and the value
61 * is the direction to order, either ASC or DESC.
65 protected $order = [];
68 * The fields by which to group.
72 protected $group = [];
75 * The conditional object for the HAVING clause.
77 * @var \Drupal\Core\Database\Query\Condition
82 * Whether or not this query should be DISTINCT
86 protected $distinct = FALSE;
89 * The range limiters for this query.
96 * An array whose elements specify a query to UNION, and the UNION type. The
97 * 'type' key may be '', 'ALL', or 'DISTINCT' to represent a 'UNION',
98 * 'UNION ALL', or 'UNION DISTINCT' statement, respectively.
100 * All entries in this array will be applied from front to back, with the
101 * first query to union on the right of the original query, the second union
102 * to the right of the first, etc.
106 protected $union = [];
109 * Indicates if preExecute() has already been called.
112 protected $prepared = FALSE;
115 * The FOR UPDATE status
117 protected $forUpdate = FALSE;
120 * Constructs a Select object.
122 * @param string $table
123 * The name of the table that is being queried.
124 * @param string $alias
125 * The alias for the table.
126 * @param \Drupal\Core\Database\Connection $connection
127 * Database connection object.
128 * @param array $options
129 * Array of query options.
131 public function __construct($table, $alias = NULL, Connection $connection, $options = []) {
132 $options['return'] = Database::RETURN_STATEMENT;
133 parent::__construct($connection, $options);
134 $conjunction = isset($options['conjunction']) ? $options['conjunction'] : 'AND';
135 $this->condition = new Condition($conjunction);
136 $this->having = new Condition($conjunction);
137 $this->addJoin(NULL, $table, $alias);
143 public function addTag($tag) {
144 $this->alterTags[$tag] = 1;
151 public function hasTag($tag) {
152 return isset($this->alterTags[$tag]);
158 public function hasAllTags() {
159 return !(boolean)array_diff(func_get_args(), array_keys($this->alterTags));
165 public function hasAnyTag() {
166 return (boolean)array_intersect(func_get_args(), array_keys($this->alterTags));
172 public function addMetaData($key, $object) {
173 $this->alterMetaData[$key] = $object;
180 public function getMetaData($key) {
181 return isset($this->alterMetaData[$key]) ? $this->alterMetaData[$key] : NULL;
187 public function arguments() {
188 if (!$this->compiled()) {
192 $args = $this->condition->arguments() + $this->having->arguments();
194 foreach ($this->tables as $table) {
195 if ($table['arguments']) {
196 $args += $table['arguments'];
198 // If this table is a subquery, grab its arguments recursively.
199 if ($table['table'] instanceof SelectInterface) {
200 $args += $table['table']->arguments();
202 // If the join condition is an object, grab its arguments recursively.
203 if (!empty($table['condition']) && $table['condition'] instanceof ConditionInterface) {
204 $args += $table['condition']->arguments();
208 foreach ($this->expressions as $expression) {
209 if ($expression['arguments']) {
210 $args += $expression['arguments'];
214 // If there are any dependent queries to UNION,
215 // incorporate their arguments recursively.
216 foreach ($this->union as $union) {
217 $args += $union['query']->arguments();
226 public function compile(Connection $connection, PlaceholderInterface $queryPlaceholder) {
227 $this->condition->compile($connection, $queryPlaceholder);
228 $this->having->compile($connection, $queryPlaceholder);
230 foreach ($this->tables as $table) {
231 // If this table is a subquery, compile it recursively.
232 if ($table['table'] instanceof SelectInterface) {
233 $table['table']->compile($connection, $queryPlaceholder);
235 // Make sure join conditions are also compiled.
236 if (!empty($table['condition']) && $table['condition'] instanceof ConditionInterface) {
237 $table['condition']->compile($connection, $queryPlaceholder);
241 // If there are any dependent queries to UNION, compile it recursively.
242 foreach ($this->union as $union) {
243 $union['query']->compile($connection, $queryPlaceholder);
250 public function compiled() {
251 if (!$this->condition->compiled() || !$this->having->compiled()) {
255 foreach ($this->tables as $table) {
256 // If this table is a subquery, check its status recursively.
257 if ($table['table'] instanceof SelectInterface) {
258 if (!$table['table']->compiled()) {
262 if (!empty($table['condition']) && $table['condition'] instanceof ConditionInterface) {
263 if (!$table['condition']->compiled()) {
269 foreach ($this->union as $union) {
270 if (!$union['query']->compiled()) {
281 public function havingCondition($field, $value = NULL, $operator = NULL) {
282 $this->having->condition($field, $value, $operator);
289 public function &havingConditions() {
290 return $this->having->conditions();
296 public function havingArguments() {
297 return $this->having->arguments();
303 public function having($snippet, $args = []) {
304 $this->having->where($snippet, $args);
311 public function havingCompile(Connection $connection) {
312 $this->having->compile($connection, $this);
318 public function extend($extender_name) {
319 $override_class = $extender_name . '_' . $this->connection->driver();
320 if (class_exists($override_class)) {
321 $extender_name = $override_class;
323 return new $extender_name($this, $this->connection);
329 public function havingIsNull($field) {
330 $this->having->isNull($field);
337 public function havingIsNotNull($field) {
338 $this->having->isNotNull($field);
345 public function havingExists(SelectInterface $select) {
346 $this->having->exists($select);
353 public function havingNotExists(SelectInterface $select) {
354 $this->having->notExists($select);
361 public function forUpdate($set = TRUE) {
363 $this->forUpdate = $set;
371 public function &getFields() {
372 return $this->fields;
378 public function &getExpressions() {
379 return $this->expressions;
385 public function &getOrderBy() {
392 public function &getGroupBy() {
399 public function &getTables() {
400 return $this->tables;
406 public function &getUnion() {
413 public function escapeLike($string) {
414 return $this->connection->escapeLike($string);
420 public function escapeField($string) {
421 return $this->connection->escapeField($string);
427 public function getArguments(PlaceholderInterface $queryPlaceholder = NULL) {
428 if (!isset($queryPlaceholder)) {
429 $queryPlaceholder = $this;
431 $this->compile($this->connection, $queryPlaceholder);
432 return $this->arguments();
438 public function isPrepared() {
439 return $this->prepared;
445 public function preExecute(SelectInterface $query = NULL) {
446 // If no query object is passed in, use $this.
447 if (!isset($query)) {
451 // Only execute this once.
452 if ($query->isPrepared()) {
456 // Modules may alter all queries or only those having a particular tag.
457 if (isset($this->alterTags)) {
458 // Many contrib modules as well as Entity Reference in core assume that
459 // query tags used for access-checking purposes follow the pattern
460 // $entity_type . '_access'. But this is not the case for taxonomy terms,
461 // since the core Taxonomy module used to add term_access instead of
462 // taxonomy_term_access to its queries. Provide backwards compatibility
463 // by adding both tags here instead of attempting to fix all contrib
464 // modules in a coordinated effort.
466 // - Extract this mechanism into a hook as part of a public (non-security)
468 // - Emit E_USER_DEPRECATED if term_access is used.
469 // https://www.drupal.org/node/2575081
470 $term_access_tags = ['term_access' => 1, 'taxonomy_term_access' => 1];
471 if (array_intersect_key($this->alterTags, $term_access_tags)) {
472 $this->alterTags += $term_access_tags;
475 foreach ($this->alterTags as $tag => $value) {
476 $hooks[] = 'query_' . $tag;
478 \Drupal::moduleHandler()->alter($hooks, $query);
481 $this->prepared = TRUE;
483 // Now also prepare any sub-queries.
484 foreach ($this->tables as $table) {
485 if ($table['table'] instanceof SelectInterface) {
486 $table['table']->preExecute();
490 foreach ($this->union as $union) {
491 $union['query']->preExecute();
494 return $this->prepared;
500 public function execute() {
501 // If validation fails, simply return NULL.
502 // Note that validation routines in preExecute() may throw exceptions instead.
503 if (!$this->preExecute()) {
507 $args = $this->getArguments();
508 return $this->connection->query((string) $this, $args, $this->queryOptions);
514 public function distinct($distinct = TRUE) {
515 $this->distinct = $distinct;
522 public function addField($table_alias, $field, $alias = NULL) {
523 // If no alias is specified, first try the field name itself.
528 // If that's already in use, try the table name and field name.
529 if (!empty($this->fields[$alias])) {
530 $alias = $table_alias . '_' . $field;
533 // If that is already used, just add a counter until we find an unused alias.
534 $alias_candidate = $alias;
536 while (!empty($this->fields[$alias_candidate])) {
537 $alias_candidate = $alias . '_' . $count++;
539 $alias = $alias_candidate;
541 $this->fields[$alias] = [
543 'table' => $table_alias,
553 public function fields($table_alias, array $fields = []) {
555 foreach ($fields as $field) {
556 // We don't care what alias was assigned.
557 $this->addField($table_alias, $field);
561 // We want all fields from this table.
562 $this->tables[$table_alias]['all_fields'] = TRUE;
571 public function addExpression($expression, $alias = NULL, $arguments = []) {
573 $alias = 'expression';
576 $alias_candidate = $alias;
578 while (!empty($this->expressions[$alias_candidate])) {
579 $alias_candidate = $alias . '_' . $count++;
581 $alias = $alias_candidate;
583 $this->expressions[$alias] = [
584 'expression' => $expression,
586 'arguments' => $arguments,
595 public function join($table, $alias = NULL, $condition = NULL, $arguments = []) {
596 return $this->addJoin('INNER', $table, $alias, $condition, $arguments);
602 public function innerJoin($table, $alias = NULL, $condition = NULL, $arguments = []) {
603 return $this->addJoin('INNER', $table, $alias, $condition, $arguments);
609 public function leftJoin($table, $alias = NULL, $condition = NULL, $arguments = []) {
610 return $this->addJoin('LEFT OUTER', $table, $alias, $condition, $arguments);
616 public function rightJoin($table, $alias = NULL, $condition = NULL, $arguments = []) {
617 return $this->addJoin('RIGHT OUTER', $table, $alias, $condition, $arguments);
623 public function addJoin($type, $table, $alias = NULL, $condition = NULL, $arguments = []) {
625 if ($table instanceof SelectInterface) {
633 $alias_candidate = $alias;
635 while (!empty($this->tables[$alias_candidate])) {
636 $alias_candidate = $alias . '_' . $count++;
638 $alias = $alias_candidate;
640 if (is_string($condition)) {
641 $condition = str_replace('%alias', $alias, $condition);
644 $this->tables[$alias] = [
645 'join type' => $type,
648 'condition' => $condition,
649 'arguments' => $arguments,
658 public function orderBy($field, $direction = 'ASC') {
659 // Only allow ASC and DESC, default to ASC.
660 $direction = strtoupper($direction) == 'DESC' ? 'DESC' : 'ASC';
661 $this->order[$field] = $direction;
668 public function orderRandom() {
669 $alias = $this->addExpression('RAND()', 'random_field');
670 $this->orderBy($alias);
677 public function range($start = NULL, $length = NULL) {
678 $this->range = $start !== NULL ? ['start' => $start, 'length' => $length] : [];
685 public function union(SelectInterface $query, $type = '') {
686 // Handle UNION aliasing.
688 // Fold UNION DISTINCT to UNION for better cross database support.
710 public function groupBy($field) {
711 $this->group[$field] = $field;
718 public function countQuery() {
719 $count = $this->prepareCountQuery();
721 $query = $this->connection->select($count, NULL, $this->queryOptions);
722 $query->addExpression('COUNT(*)');
728 * Prepares a count query from the current query object.
730 * @return \Drupal\Core\Database\Query\Select
731 * A new query object ready to have COUNT(*) performed on it.
733 protected function prepareCountQuery() {
734 // Create our new query object that we will mutate into a count query.
735 $count = clone($this);
737 $group_by = $count->getGroupBy();
738 $having = $count->havingConditions();
740 if (!$count->distinct && !isset($having[0])) {
741 // When not executing a distinct query, we can zero-out existing fields
742 // and expressions that are not used by a GROUP BY or HAVING. Fields
743 // listed in a GROUP BY or HAVING clause need to be present in the
745 $fields =& $count->getFields();
746 foreach (array_keys($fields) as $field) {
747 if (empty($group_by[$field])) {
748 unset($fields[$field]);
752 $expressions =& $count->getExpressions();
753 foreach (array_keys($expressions) as $field) {
754 if (empty($group_by[$field])) {
755 unset($expressions[$field]);
759 // Also remove 'all_fields' statements, which are expanded into tablename.*
760 // when the query is executed.
761 foreach ($count->tables as &$table) {
762 unset($table['all_fields']);
766 // If we've just removed all fields from the query, make sure there is at
767 // least one so that the query still runs.
768 $count->addExpression('1');
770 // Ordering a count query is a waste of cycles, and breaks on some
772 $orders = &$count->getOrderBy();
775 if ($count->distinct && !empty($group_by)) {
776 // If the query is distinct and contains a GROUP BY, we need to remove the
777 // distinct because SQL99 does not support counting on distinct multiple fields.
778 $count->distinct = FALSE;
781 // If there are any dependent queries to UNION, prepare each of those for
782 // the count query also.
783 foreach ($count->union as &$union) {
784 $union['query'] = $union['query']->prepareCountQuery();
793 public function __toString() {
794 // For convenience, we compile the query ourselves if the caller forgot
795 // to do it. This allows constructs like "(string) $query" to work. When
796 // the query will be executed, it will be recompiled using the proper
797 // placeholder generator anyway.
798 if (!$this->compiled()) {
799 $this->compile($this->connection, $this);
802 // Create a sanitized comment string to prepend to the query.
803 $comments = $this->connection->makeComment($this->comments);
806 $query = $comments . 'SELECT ';
807 if ($this->distinct) {
808 $query .= 'DISTINCT ';
811 // FIELDS and EXPRESSIONS
813 foreach ($this->tables as $alias => $table) {
814 if (!empty($table['all_fields'])) {
815 $fields[] = $this->connection->escapeTable($alias) . '.*';
818 foreach ($this->fields as $field) {
819 // Always use the AS keyword for field aliases, as some
820 // databases require it (e.g., PostgreSQL).
821 $fields[] = (isset($field['table']) ? $this->connection->escapeTable($field['table']) . '.' : '') . $this->connection->escapeField($field['field']) . ' AS ' . $this->connection->escapeAlias($field['alias']);
823 foreach ($this->expressions as $expression) {
824 $fields[] = $expression['expression'] . ' AS ' . $this->connection->escapeAlias($expression['alias']);
826 $query .= implode(', ', $fields);
829 // FROM - We presume all queries have a FROM, as any query that doesn't won't need the query builder anyway.
831 foreach ($this->tables as $table) {
833 if (isset($table['join type'])) {
834 $query .= $table['join type'] . ' JOIN ';
837 // If the table is a subquery, compile it and integrate it into this query.
838 if ($table['table'] instanceof SelectInterface) {
839 // Run preparation steps on this sub-query before converting to string.
840 $subquery = $table['table'];
841 $subquery->preExecute();
842 $table_string = '(' . (string) $subquery . ')';
845 $table_string = $this->connection->escapeTable($table['table']);
846 // Do not attempt prefixing cross database / schema queries.
847 if (strpos($table_string, '.') === FALSE) {
848 $table_string = '{' . $table_string . '}';
852 // Don't use the AS keyword for table aliases, as some
853 // databases don't support it (e.g., Oracle).
854 $query .= $table_string . ' ' . $this->connection->escapeTable($table['alias']);
856 if (!empty($table['condition'])) {
857 $query .= ' ON ' . (string) $table['condition'];
862 if (count($this->condition)) {
863 // There is an implicit string cast on $this->condition.
864 $query .= "\nWHERE " . $this->condition;
869 $query .= "\nGROUP BY " . implode(', ', $this->group);
873 if (count($this->having)) {
874 // There is an implicit string cast on $this->having.
875 $query .= "\nHAVING " . $this->having;
878 // UNION is a little odd, as the select queries to combine are passed into
879 // this query, but syntactically they all end up on the same level.
881 foreach ($this->union as $union) {
882 $query .= ' ' . $union['type'] . ' ' . (string) $union['query'];
888 $query .= "\nORDER BY ";
890 foreach ($this->order as $field => $direction) {
891 $fields[] = $this->connection->escapeField($field) . ' ' . $direction;
893 $query .= implode(', ', $fields);
897 // There is no universal SQL standard for handling range or limit clauses.
898 // Fortunately, all core-supported databases use the same range syntax.
899 // Databases that need a different syntax can override this method and
900 // do whatever alternate logic they need to.
901 if (!empty($this->range)) {
902 $query .= "\nLIMIT " . (int) $this->range['length'] . " OFFSET " . (int) $this->range['start'];
905 if ($this->forUpdate) {
906 $query .= ' FOR UPDATE';
915 public function __clone() {
916 // On cloning, also clone the dependent objects. However, we do not
917 // want to clone the database connection object as that would duplicate the
918 // connection itself.
920 $this->condition = clone($this->condition);
921 $this->having = clone($this->having);
922 foreach ($this->union as $key => $aggregate) {
923 $this->union[$key]['query'] = clone($aggregate['query']);