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;
71 public function execute() {
81 * Prepares the basic query with proper metadata/tags and base fields.
83 * @return \Drupal\Core\Entity\Query\Sql\Query
84 * Returns the called object.
86 * @throws \Drupal\Core\Entity\Query\QueryException
87 * Thrown if the base table does not exist.
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.");
96 if (!$base_table = $this->entityType->getBaseTable()) {
97 throw new QueryException("No base table for " . $this->entityTypeId . ", invalid query.");
100 $simple_query = TRUE;
101 if ($this->entityType->getDataTable()) {
102 $simple_query = FALSE;
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
113 $this->sqlFields["base_table.$id_field" . '_1'] = ['base_table', $id_field];
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
120 $this->sqlFields["base_table.$id_field"] = ['base_table', $id_field];
123 // Add a self-join to the base revision table if we're querying only the
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");
130 if ($this->accessCheck) {
131 $this->sqlQuery->addTag($this->entityTypeId . '_access');
133 $this->sqlQuery->addTag('entity_query');
134 $this->sqlQuery->addTag('entity_query_' . $this->entityTypeId);
136 // Add further tags added.
137 if (isset($this->alterTags)) {
138 foreach ($this->alterTags as $tag => $value) {
139 $this->sqlQuery->addTag($tag);
143 // Add further metadata added.
144 if (isset($this->alterMetaData)) {
145 foreach ($this->alterMetaData as $key => $value) {
146 $this->sqlQuery->addMetaData($key, $value);
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);
157 * Compiles the conditions.
159 * @return \Drupal\Core\Entity\Query\Sql\Query
160 * Returns the called object.
162 protected function compile() {
163 $this->condition->compile($this->sqlQuery);
168 * Adds the sort to the build query.
170 * @return \Drupal\Core\Entity\Query\Sql\Query
171 * Returns the called object.
173 protected function addSort() {
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.
182 foreach ($this->sort as $key => $data) {
183 $sort[$key] = $this->getSqlField($data['field'], $data['langcode']);
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;
200 // Now we know whether this is a simple query or not, actually do the
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);
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);
226 * Finish the query by adding fields, GROUP BY and range.
228 * @return \Drupal\Core\Entity\Query\Sql\Query
229 * Returns the called object.
231 protected function finish() {
232 $this->initializePager();
234 $this->sqlQuery->range($this->range['start'], $this->range['length']);
236 foreach ($this->sqlGroupBy as $field) {
237 $this->sqlQuery->groupBy($field);
239 foreach ($this->sqlFields as $field) {
240 $this->sqlQuery->addField($field[0], $field[1], isset($field[2]) ? $field[2] : NULL);
246 * Executes the query and returns the result.
249 * Returns the query result as entity IDs.
251 protected function result() {
253 return $this->sqlQuery->countQuery()->execute()->fetchField();
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();
262 * Constructs a select expression for a given field and language.
264 * @param string $field
265 * The name of the field being queried.
266 * @param string $langcode
267 * The language code of the field.
270 * An expression that will select the given field for the given language in
271 * a SELECT query, such as 'base_table.id'.
273 protected function getSqlField($field, $langcode) {
274 if (!isset($this->tables)) {
275 $this->tables = $this->getTables($this->sqlQuery);
277 $base_property = "base_table.$field";
278 if (isset($this->sqlFields[$base_property])) {
279 return $base_property;
282 return $this->tables->addField($field, 'LEFT', $langcode);
287 * Determines whether the query requires GROUP BY and ORDER BY MIN/MAX.
291 protected function isSimpleQuery() {
292 return (!$this->pager && !$this->range && !$this->count) || $this->sqlQuery->getMetaData('simple_query');
296 * Implements the magic __clone method.
298 * Reset fields and GROUP BY when cloning.
300 public function __clone() {
302 $this->sqlFields = [];
303 $this->sqlGroupBy = [];
307 * Gets the Tables object for this query.
309 * @param \Drupal\Core\Database\Query\SelectInterface $sql_query
310 * The SQL query object being built.
312 * @return \Drupal\Core\Entity\Query\Sql\TablesInterface
313 * The object that adds tables and fields to the SQL query object.
315 public function getTables(SelectInterface $sql_query) {
316 $class = static::getClass($this->namespaces, 'Tables');
317 return new $class($sql_query);