3 namespace Drupal\Core\Entity\Query\Sql;
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;
13 * The SQL storage entity query class.
15 class Query extends QueryBase implements QueryInterface {
18 * The build sql select query.
20 * @var \Drupal\Core\Database\Query\SelectInterface
25 * An array of fields keyed by the field alias.
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
34 protected $sqlFields = [];
37 * An array of strings added as to the group by, keyed by the string to avoid
42 protected $sqlGroupBy = [];
45 * @var \Drupal\Core\Database\Connection
47 protected $connection;
50 * Constructs a query object.
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.
62 public function __construct(EntityTypeInterface $entity_type, $conjunction, Connection $connection, array $namespaces) {
63 parent::__construct($entity_type, $conjunction, $namespaces);
64 $this->connection = $connection;
70 public function execute() {
80 * Prepares the basic query with proper metadata/tags and base fields.
82 * @return \Drupal\Core\Entity\Query\Sql\Query
83 * Returns the called object.
85 * @throws \Drupal\Core\Entity\Query\QueryException
86 * Thrown if the base table does not exist.
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.");
95 if (!$base_table = $this->entityType->getBaseTable()) {
96 throw new QueryException("No base table for " . $this->entityTypeId . ", invalid query.");
100 if ($this->entityType->getDataTable()) {
101 $simple_query = FALSE;
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
112 $this->sqlFields["base_table.$id_field" . '_1'] = ['base_table', $id_field];
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
119 $this->sqlFields["base_table.$id_field"] = ['base_table', $id_field];
122 // Add a self-join to the base revision table if we're querying only the
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");
129 if ($this->accessCheck) {
130 $this->sqlQuery->addTag($this->entityTypeId . '_access');
132 $this->sqlQuery->addTag('entity_query');
133 $this->sqlQuery->addTag('entity_query_' . $this->entityTypeId);
135 // Add further tags added.
136 if (isset($this->alterTags)) {
137 foreach ($this->alterTags as $tag => $value) {
138 $this->sqlQuery->addTag($tag);
142 // Add further metadata added.
143 if (isset($this->alterMetaData)) {
144 foreach ($this->alterMetaData as $key => $value) {
145 $this->sqlQuery->addMetaData($key, $value);
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);
156 * Compiles the conditions.
158 * @return \Drupal\Core\Entity\Query\Sql\Query
159 * Returns the called object.
161 protected function compile() {
162 $this->condition->compile($this->sqlQuery);
167 * Adds the sort to the build query.
169 * @return \Drupal\Core\Entity\Query\Sql\Query
170 * Returns the called object.
172 protected function addSort() {
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.
181 foreach ($this->sort as $key => $data) {
182 $sort[$key] = $this->getSqlField($data['field'], $data['langcode']);
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;
199 // Now we know whether this is a simple query or not, actually do the
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);
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);
225 * Finish the query by adding fields, GROUP BY and range.
227 * @return \Drupal\Core\Entity\Query\Sql\Query
228 * Returns the called object.
230 protected function finish() {
231 $this->initializePager();
233 $this->sqlQuery->range($this->range['start'], $this->range['length']);
235 foreach ($this->sqlGroupBy as $field) {
236 $this->sqlQuery->groupBy($field);
238 foreach ($this->sqlFields as $field) {
239 $this->sqlQuery->addField($field[0], $field[1], isset($field[2]) ? $field[2] : NULL);
245 * Executes the query and returns the result.
248 * Returns the query result as entity IDs.
250 protected function result() {
252 return $this->sqlQuery->countQuery()->execute()->fetchField();
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();
261 * Constructs a select expression for a given field and language.
263 * @param string $field
264 * The name of the field being queried.
265 * @param string $langcode
266 * The language code of the field.
269 * An expression that will select the given field for the given language in
270 * a SELECT query, such as 'base_table.id'.
272 protected function getSqlField($field, $langcode) {
273 if (!isset($this->tables)) {
274 $this->tables = $this->getTables($this->sqlQuery);
276 $base_property = "base_table.$field";
277 if (isset($this->sqlFields[$base_property])) {
278 return $base_property;
281 return $this->tables->addField($field, 'LEFT', $langcode);
286 * Determines whether the query requires GROUP BY and ORDER BY MIN/MAX.
290 protected function isSimpleQuery() {
291 return (!$this->pager && !$this->range && !$this->count) || $this->sqlQuery->getMetaData('simple_query');
295 * Implements the magic __clone method.
297 * Reset fields and GROUP BY when cloning.
299 public function __clone() {
301 $this->sqlFields = [];
302 $this->sqlGroupBy = [];
306 * Gets the Tables object for this query.
308 * @param \Drupal\Core\Database\Query\SelectInterface $sql_query
309 * The SQL query object being built.
311 * @return \Drupal\Core\Entity\Query\Sql\TablesInterface
312 * The object that adds tables and fields to the SQL query object.
314 public function getTables(SelectInterface $sql_query) {
315 $class = static::getClass($this->namespaces, 'Tables');
316 return new $class($sql_query);