Security update for Core, with self-updated composer
[yaffs-website] / web / core / lib / Drupal / Core / Entity / Query / Sql / Query.php
1 <?php
2
3 namespace Drupal\Core\Entity\Query\Sql;
4
5 use Drupal\Core\Database\Connection;
6 use Drupal\Core\Database\Query\SelectInterface;
7 use Drupal\Core\Entity\EntityTypeInterface;
8 use Drupal\Core\Entity\Query\QueryBase;
9 use Drupal\Core\Entity\Query\QueryException;
10 use Drupal\Core\Entity\Query\QueryInterface;
11
12 /**
13  * The SQL storage entity query class.
14  */
15 class Query extends QueryBase implements QueryInterface {
16
17   /**
18    * The build sql select query.
19    *
20    * @var \Drupal\Core\Database\Query\SelectInterface
21    */
22   protected $sqlQuery;
23
24   /**
25    * An array of fields keyed by the field alias.
26    *
27    * Each entry correlates to the arguments of
28    * \Drupal\Core\Database\Query\SelectInterface::addField(), so the first one
29    * is the table alias, the second one the field and the last one optional the
30    * field alias.
31    *
32    * @var array
33    */
34   protected $sqlFields = [];
35
36   /**
37    * An array of strings added as to the group by, keyed by the string to avoid
38    * duplicates.
39    *
40    * @var array
41    */
42   protected $sqlGroupBy = [];
43
44   /**
45    * @var \Drupal\Core\Database\Connection
46    */
47   protected $connection;
48
49   /**
50    * Constructs a query object.
51    *
52    * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
53    *   The entity type definition.
54    * @param string $conjunction
55    *   - AND: all of the conditions on the query need to match.
56    *   - OR: at least one of the conditions on the query need to match.
57    * @param \Drupal\Core\Database\Connection $connection
58    *   The database connection to run the query against.
59    * @param array $namespaces
60    *   List of potential namespaces of the classes belonging to this query.
61    */
62   public function __construct(EntityTypeInterface $entity_type, $conjunction, Connection $connection, array $namespaces) {
63     parent::__construct($entity_type, $conjunction, $namespaces);
64     $this->connection = $connection;
65   }
66
67
68   /**
69    * {@inheritdoc}
70    */
71   public function execute() {
72     return $this
73       ->prepare()
74       ->compile()
75       ->addSort()
76       ->finish()
77       ->result();
78   }
79
80   /**
81    * Prepares the basic query with proper metadata/tags and base fields.
82    *
83    * @return \Drupal\Core\Entity\Query\Sql\Query
84    *   Returns the called object.
85    *
86    * @throws \Drupal\Core\Entity\Query\QueryException
87    *   Thrown if the base table does not exist.
88    */
89   protected function prepare() {
90     if ($this->allRevisions) {
91       if (!$base_table = $this->entityType->getRevisionTable()) {
92         throw new QueryException("No revision table for " . $this->entityTypeId . ", invalid query.");
93       }
94     }
95     else {
96       if (!$base_table = $this->entityType->getBaseTable()) {
97         throw new QueryException("No base table for " . $this->entityTypeId . ", invalid query.");
98       }
99     }
100     $simple_query = TRUE;
101     if ($this->entityType->getDataTable()) {
102       $simple_query = FALSE;
103     }
104     $this->sqlQuery = $this->connection->select($base_table, 'base_table', ['conjunction' => $this->conjunction]);
105     $this->sqlQuery->addMetaData('entity_type', $this->entityTypeId);
106     $id_field = $this->entityType->getKey('id');
107     // Add the key field for fetchAllKeyed().
108     if (!$revision_field = $this->entityType->getKey('revision')) {
109       // When there is no revision support, the key field is the entity key.
110       $this->sqlFields["base_table.$id_field"] = ['base_table', $id_field];
111       // Now add the value column for fetchAllKeyed(). This is always the
112       // entity id.
113       $this->sqlFields["base_table.$id_field" . '_1'] = ['base_table', $id_field];
114     }
115     else {
116       // When there is revision support, the key field is the revision key.
117       $this->sqlFields["base_table.$revision_field"] = ['base_table', $revision_field];
118       // Now add the value column for fetchAllKeyed(). This is always the
119       // entity id.
120       $this->sqlFields["base_table.$id_field"] = ['base_table', $id_field];
121     }
122
123     // Add a self-join to the base revision table if we're querying only the
124     // latest revisions.
125     if ($this->latestRevision && $revision_field) {
126       $this->sqlQuery->leftJoin($base_table, 'base_table_2', "base_table.$id_field = base_table_2.$id_field AND base_table.$revision_field < base_table_2.$revision_field");
127       $this->sqlQuery->isNull("base_table_2.$id_field");
128     }
129
130     if ($this->accessCheck) {
131       $this->sqlQuery->addTag($this->entityTypeId . '_access');
132     }
133     $this->sqlQuery->addTag('entity_query');
134     $this->sqlQuery->addTag('entity_query_' . $this->entityTypeId);
135
136     // Add further tags added.
137     if (isset($this->alterTags)) {
138       foreach ($this->alterTags as $tag => $value) {
139         $this->sqlQuery->addTag($tag);
140       }
141     }
142
143     // Add further metadata added.
144     if (isset($this->alterMetaData)) {
145       foreach ($this->alterMetaData as $key => $value) {
146         $this->sqlQuery->addMetaData($key, $value);
147       }
148     }
149     // This now contains first the table containing entity properties and
150     // last the entity base table. They might be the same.
151     $this->sqlQuery->addMetaData('all_revisions', $this->allRevisions);
152     $this->sqlQuery->addMetaData('simple_query', $simple_query);
153     return $this;
154   }
155
156   /**
157    * Compiles the conditions.
158    *
159    * @return \Drupal\Core\Entity\Query\Sql\Query
160    *   Returns the called object.
161    */
162   protected function compile() {
163     $this->condition->compile($this->sqlQuery);
164     return $this;
165   }
166
167   /**
168    * Adds the sort to the build query.
169    *
170    * @return \Drupal\Core\Entity\Query\Sql\Query
171    *   Returns the called object.
172    */
173   protected function addSort() {
174     if ($this->count) {
175       $this->sort = [];
176     }
177     // Gather the SQL field aliases first to make sure every field table
178     // necessary is added. This might change whether the query is simple or
179     // not. See below for more on simple queries.
180     $sort = [];
181     if ($this->sort) {
182       foreach ($this->sort as $key => $data) {
183         $sort[$key] = $this->getSqlField($data['field'], $data['langcode']);
184       }
185     }
186     $simple_query = $this->isSimpleQuery();
187     // If the query is set up for paging either via pager or by range or a
188     // count is requested, then the correct amount of rows returned is
189     // important. If the entity has a data table or multiple value fields are
190     // involved then each revision might appear in several rows and this needs
191     // a significantly more complex query.
192     if (!$simple_query) {
193       // First, GROUP BY revision id (if it has been added) and entity id.
194       // Now each group contains a single revision of an entity.
195       foreach ($this->sqlFields as $field) {
196         $group_by = "$field[0].$field[1]";
197         $this->sqlGroupBy[$group_by] = $group_by;
198       }
199     }
200     // Now we know whether this is a simple query or not, actually do the
201     // sorting.
202     foreach ($sort as $key => $sql_alias) {
203       $direction = $this->sort[$key]['direction'];
204       if ($simple_query || isset($this->sqlGroupBy[$sql_alias])) {
205         // Simple queries, and the grouped columns of complicated queries
206         // can be ordered normally, without the aggregation function.
207         $this->sqlQuery->orderBy($sql_alias, $direction);
208         if (!isset($this->sqlFields[$sql_alias])) {
209           $this->sqlFields[$sql_alias] = explode('.', $sql_alias);
210         }
211       }
212       else {
213         // Order based on the smallest element of each group if the
214         // direction is ascending, or on the largest element of each group
215         // if the direction is descending.
216         $function = $direction == 'ASC' ? 'min' : 'max';
217         $expression = "$function($sql_alias)";
218         $expression_alias = $this->sqlQuery->addExpression($expression);
219         $this->sqlQuery->orderBy($expression_alias, $direction);
220       }
221     }
222     return $this;
223   }
224
225   /**
226    * Finish the query by adding fields, GROUP BY and range.
227    *
228    * @return \Drupal\Core\Entity\Query\Sql\Query
229    *   Returns the called object.
230    */
231   protected function finish() {
232     $this->initializePager();
233     if ($this->range) {
234       $this->sqlQuery->range($this->range['start'], $this->range['length']);
235     }
236     foreach ($this->sqlGroupBy as $field) {
237       $this->sqlQuery->groupBy($field);
238     }
239     foreach ($this->sqlFields as $field) {
240       $this->sqlQuery->addField($field[0], $field[1], isset($field[2]) ? $field[2] : NULL);
241     }
242     return $this;
243   }
244
245   /**
246    * Executes the query and returns the result.
247    *
248    * @return int|array
249    *   Returns the query result as entity IDs.
250    */
251   protected function result() {
252     if ($this->count) {
253       return $this->sqlQuery->countQuery()->execute()->fetchField();
254     }
255     // Return a keyed array of results. The key is either the revision_id or
256     // the entity_id depending on whether the entity type supports revisions.
257     // The value is always the entity id.
258     return $this->sqlQuery->execute()->fetchAllKeyed();
259   }
260
261   /**
262    * Constructs a select expression for a given field and language.
263    *
264    * @param string $field
265    *   The name of the field being queried.
266    * @param string $langcode
267    *   The language code of the field.
268    *
269    * @return string
270    *   An expression that will select the given field for the given language in
271    *   a SELECT query, such as 'base_table.id'.
272    */
273   protected function getSqlField($field, $langcode) {
274     if (!isset($this->tables)) {
275       $this->tables = $this->getTables($this->sqlQuery);
276     }
277     $base_property = "base_table.$field";
278     if (isset($this->sqlFields[$base_property])) {
279       return $base_property;
280     }
281     else {
282       return $this->tables->addField($field, 'LEFT', $langcode);
283     }
284   }
285
286   /**
287    * Determines whether the query requires GROUP BY and ORDER BY MIN/MAX.
288    *
289    * @return bool
290    */
291   protected function isSimpleQuery() {
292     return (!$this->pager && !$this->range && !$this->count) || $this->sqlQuery->getMetaData('simple_query');
293   }
294
295   /**
296    * Implements the magic __clone method.
297    *
298    * Reset fields and GROUP BY when cloning.
299    */
300   public function __clone() {
301     parent::__clone();
302     $this->sqlFields = [];
303     $this->sqlGroupBy = [];
304   }
305
306   /**
307    * Gets the Tables object for this query.
308    *
309    * @param \Drupal\Core\Database\Query\SelectInterface $sql_query
310    *   The SQL query object being built.
311    *
312    * @return \Drupal\Core\Entity\Query\Sql\TablesInterface
313    *   The object that adds tables and fields to the SQL query object.
314    */
315   public function getTables(SelectInterface $sql_query) {
316     $class = static::getClass($this->namespaces, 'Tables');
317     return new $class($sql_query);
318   }
319
320 }