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