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