Tables.php 16.6 KB
Newer Older
1
2
<?php

3
namespace Drupal\Core\Entity\Query\Sql;
4
5

use Drupal\Core\Database\Query\SelectInterface;
6
use Drupal\Core\Entity\EntityType;
7
use Drupal\Core\Entity\Query\QueryException;
8
use Drupal\Core\Entity\Sql\SqlEntityStorageInterface;
9
use Drupal\Core\Entity\Sql\TableMappingInterface;
10
11
use Drupal\Core\Entity\TypedData\EntityDataDefinitionInterface;
use Drupal\Core\TypedData\DataReferenceDefinitionInterface;
12
13
14
15

/**
 * Adds tables and fields to the SQL entity query.
 */
16
class Tables implements TablesInterface {
17
18
19
20
21
22
23
24
25
26
27
28
29
30

  /**
   * @var \Drupal\Core\Database\Query\SelectInterface
   */
  protected $sqlQuery;

  /**
   * Entity table array, key is table name, value is alias.
   *
   * This array contains at most two entries: one for the data, one for the
   * properties.
   *
   * @var array
   */
31
  protected $entityTables = [];
32
33
34
35
36
37
38
39

  /**
   * Field table array, key is table name, value is alias.
   *
   * This array contains one entry per field table.
   *
   * @var array
   */
40
  protected $fieldTables = [];
41

42
43
44
45
46
47
48
  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityManager
   */
  protected $entityManager;

49
50
51
52
53
  /**
   * List of case sensitive fields.
   *
   * @var array
   */
54
  protected $caseSensitiveFields = [];
55

56
57
58
  /**
   * @param \Drupal\Core\Database\Query\SelectInterface $sql_query
   */
59
  public function __construct(SelectInterface $sql_query) {
60
    $this->sqlQuery = $sql_query;
61
    $this->entityManager = \Drupal::entityManager();
62
63
64
  }

  /**
65
   * {@inheritdoc}
66
   */
67
  public function addField($field, $type, $langcode) {
68
    $entity_type_id = $this->sqlQuery->getMetaData('entity_type');
69
    $all_revisions = $this->sqlQuery->getMetaData('all_revisions');
70
71
72
73
74
75
76
77
78
79
80
81
82
    // This variable ensures grouping works correctly. For example:
    // ->condition('tags', 2, '>')
    // ->condition('tags', 20, '<')
    // ->condition('node_reference.nid.entity.tags', 2)
    // The first two should use the same table but the last one needs to be a
    // new table. So for the first two, the table array index will be 'tags'
    // while the third will be 'node_reference.nid.tags'.
    $index_prefix = '';
    $specifiers = explode('.', $field);
    $base_table = 'base_table';
    $count = count($specifiers) - 1;
    // This will contain the definitions of the last specifier seen by the
    // system.
83
    $propertyDefinitions = [];
84
    $entity_type = $this->entityManager->getDefinition($entity_type_id);
85

86
    $field_storage_definitions = $this->entityManager->getFieldStorageDefinitions($entity_type_id);
87
    for ($key = 0; $key <= $count; $key++) {
88
89
90
91
92
93
94
95
96
97
98
99
100
101
      // This can either be the name of an entity base field or a configurable
      // field.
      $specifier = $specifiers[$key];
      if (isset($field_storage_definitions[$specifier])) {
        $field_storage = $field_storage_definitions[$specifier];
      }
      else {
        $field_storage = FALSE;
      }

      // If there is revision support, only the current revisions are being
      // queried, and the field is revisionable then use the revision id.
      // Otherwise, the entity id will do.
      if (($revision_key = $entity_type->getKey('revision')) && $all_revisions && $field_storage && $field_storage->isRevisionable()) {
102
103
        // This contains the relevant SQL field to be used when joining entity
        // tables.
104
        $entity_id_field = $revision_key;
105
106
107
108
109
        // This contains the relevant SQL field to be used when joining field
        // tables.
        $field_id_field = 'revision_id';
      }
      else {
110
        $entity_id_field = $entity_type->getKey('id');
111
112
        $field_id_field = 'entity_id';
      }
113
114
115
116
117
118

      /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
      $table_mapping = $this->entityManager->getStorage($entity_type_id)->getTableMapping();

      // Check whether this field is stored in a dedicated table.
      if ($field_storage && $table_mapping->requiresDedicatedTableStorage($field_storage)) {
119
        $delta = NULL;
120
        // Find the field column.
121
        $column = $field_storage->getMainPropertyName();
122

123
124
        if ($key < $count) {
          $next = $specifiers[$key + 1];
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
          // If this is a numeric specifier we're adding a condition on the
          // specific delta.
          if (is_numeric($next)) {
            $delta = $next;
            $index_prefix .= ".$delta";
            // Do not process it again.
            $key++;
            $next = $specifiers[$key + 1];
          }
          // If this specifier is the reserved keyword "%delta" we're adding a
          // condition on a delta range.
          elseif ($next == TableMappingInterface::DELTA) {
            $index_prefix .= TableMappingInterface::DELTA;
            // Do not process it again.
            $key++;
            // If there are more specifiers to work with then continue
            // processing. If this is the last specifier then use the reserved
            // keyword as a column name.
            if ($key < $count) {
              $next = $specifiers[$key + 1];
            }
            else {
              $column = TableMappingInterface::DELTA;
            }
          }
150
          // Is this a field column?
151
          $columns = $field_storage->getColumns();
152
          if (isset($columns[$next]) || in_array($next, $table_mapping->getReservedColumns())) {
153
154
155
156
157
158
159
160
161
162
163
164
165
166
            // Use it.
            $column = $next;
            // Do not process it again.
            $key++;
          }
          // If there are more specifiers, the next one must be a
          // relationship. Either the field name followed by a relationship
          // specifier, for example $node->field_image->entity. Or a field
          // column followed by a relationship specifier, for example
          // $node->field_image->fid->entity. In both cases, prepare the
          // property definitions for the relationship. In the first case,
          // also use the property definitions for column.
          if ($key < $count) {
            $relationship_specifier = $specifiers[$key + 1];
167
            $propertyDefinitions = $field_storage->getPropertyDefinitions();
168

169
170
171
172
            // Prepare the next index prefix.
            $next_index_prefix = "$relationship_specifier.$column";
          }
        }
173
        $table = $this->ensureFieldTable($index_prefix, $field_storage, $type, $langcode, $base_table, $entity_id_field, $field_id_field, $delta);
174
        $sql_column = $table_mapping->getFieldColumnName($field_storage, $column);
175
176
177
178
        $property_definitions = $field_storage->getPropertyDefinitions();
        if (isset($property_definitions[$column])) {
          $this->caseSensitiveFields[$field] = $property_definitions[$column]->getSetting('case_sensitive');
        }
179
      }
180
      // The field is stored in a shared table.
181
182
183
      else {
        // ensureEntityTable() decides whether an entity property will be
        // queried from the data table or the base table based on where it
184
        // finds the property first. The data table is preferred, which is why
185
        // it gets added before the base table.
186
        $entity_tables = [];
187
188
189
190
191
192
193
194
195
        if ($all_revisions && $field_storage && $field_storage->isRevisionable()) {
          $data_table = $entity_type->getRevisionDataTable();
          $entity_base_table = $entity_type->getRevisionTable();
        }
        else {
          $data_table = $entity_type->getDataTable();
          $entity_base_table = $entity_type->getBaseTable();
        }
        if ($data_table) {
196
          $this->sqlQuery->addMetaData('simple_query', FALSE);
197
          $entity_tables[$data_table] = $this->getTableMapping($data_table, $entity_type_id);
198
        }
199
        $entity_tables[$entity_base_table] = $this->getTableMapping($entity_base_table, $entity_type_id);
200
        $sql_column = $specifier;
201
202
203
204
205

        // If there are more specifiers, get the right sql column name if the
        // next one is a column of this field.
        if ($key < $count) {
          $next = $specifiers[$key + 1];
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
          // If this specifier is the reserved keyword "%delta" we're adding a
          // condition on a delta range.
          if ($next == TableMappingInterface::DELTA) {
            $key++;
            if ($key < $count) {
              $next = $specifiers[$key + 1];
            }
            else {
              return 0;
            }
          }
          // If this is a numeric specifier we're adding a condition on the
          // specific delta. Since we know that this is a single value base
          // field no other value than 0 makes sense.
          if (is_numeric($next)) {
            if ($next > 0) {
              $this->sqlQuery->condition('1 <> 1');
            }
            $key++;
            $next = $specifiers[$key + 1];
          }
227
228
229
230
231
232
233
234
235
236
237
          // Is this a field column?
          $columns = $field_storage->getColumns();
          if (isset($columns[$next]) || in_array($next, $table_mapping->getReservedColumns())) {
            // Use it.
            $sql_column = $table_mapping->getFieldColumnName($field_storage, $next);
            // Do not process it again.
            $key++;
          }
        }

        $table = $this->ensureEntityTable($index_prefix, $sql_column, $type, $langcode, $base_table, $entity_id_field, $entity_tables);
238

239
240
        // If there is a field storage (some specifiers are not), check for case
        // sensitivity.
241
242
243
244
245
246
247
248
        if ($field_storage) {
          $column = $field_storage->getMainPropertyName();
          $base_field_property_definitions = $field_storage->getPropertyDefinitions();
          if (isset($base_field_property_definitions[$column])) {
            $this->caseSensitiveFields[$field] = $base_field_property_definitions[$column]->getSetting('case_sensitive');
          }
        }

249
250
      }
      // If there are more specifiers to come, it's a relationship.
251
      if ($field_storage && $key < $count) {
252
253
254
        // Computed fields have prepared their property definition already, do
        // it for properties as well.
        if (!$propertyDefinitions) {
255
          $propertyDefinitions = $field_storage->getPropertyDefinitions();
256
257
258
          $relationship_specifier = $specifiers[$key + 1];
          $next_index_prefix = $relationship_specifier;
        }
259
260
261
262
263
264
        $entity_type_id = NULL;
        // Relationship specifier can also contain the entity type ID, i.e.
        // entity:node, entity:user or entity:taxonomy.
        if (strpos($relationship_specifier, ':') !== FALSE) {
          list($relationship_specifier, $entity_type_id) = explode(':', $relationship_specifier, 2);
        }
265
        // Check for a valid relationship.
266
267
268
269
270
271
272
        if (isset($propertyDefinitions[$relationship_specifier]) && $propertyDefinitions[$relationship_specifier] instanceof DataReferenceDefinitionInterface) {
          // If it is, use the entity type if specified already, otherwise use
          // the definition.
          $target_definition = $propertyDefinitions[$relationship_specifier]->getTargetDefinition();
          if (!$entity_type_id && $target_definition instanceof EntityDataDefinitionInterface) {
            $entity_type_id = $target_definition->getEntityTypeId();
          }
273
274
          $entity_type = $this->entityManager->getDefinition($entity_type_id);
          $field_storage_definitions = $this->entityManager->getFieldStorageDefinitions($entity_type_id);
275
          // Add the new entity base table using the table and sql column.
276
277
278
279
280
281
282
283
284
          // An additional $field_storage argument is being passed to
          // addNextBaseTable() in order to improve its functionality, for
          // example by allowing extra processing based on the field type of the
          // storage. In order to maintain backwards compatibility in 8.4.x, the
          // new argument has not been added to the signature of that method,
          // and it will be added only in 8.5.x.
          // @todo Add the $field_storage argument to addNextBaseTable() in
          //   8.5.x. https://www.drupal.org/node/2909425
          $base_table = $this->addNextBaseTable($entity_type, $table, $sql_column, $field_storage);
285
          $propertyDefinitions = [];
286
287
288
289
          $key++;
          $index_prefix .= "$next_index_prefix.";
        }
        else {
290
          throw new QueryException("Invalid specifier '$relationship_specifier'");
291
292
        }
      }
293
294
295
296
    }
    return "$table.$sql_column";
  }

297
298
299
300
301
302
303
304
305
  /**
   * {@inheritdoc}
   */
  public function isFieldCaseSensitive($field_name) {
    if (isset($this->caseSensitiveFields[$field_name])) {
      return $this->caseSensitiveFields[$field_name];
    }
  }

306
307
308
309
  /**
   * Join entity table if necessary and return the alias for it.
   *
   * @param string $property
310
   *
311
   * @return string
312
   *
313
314
   * @throws \Drupal\Core\Entity\Query\QueryException
   */
315
  protected function ensureEntityTable($index_prefix, $property, $type, $langcode, $base_table, $id_field, $entity_tables) {
316
317
    foreach ($entity_tables as $table => $mapping) {
      if (isset($mapping[$property])) {
318
319
        if (!isset($this->entityTables[$index_prefix . $table])) {
          $this->entityTables[$index_prefix . $table] = $this->addJoin($type, $table, "%alias.$id_field = $base_table.$id_field", $langcode);
320
        }
321
        return $this->entityTables[$index_prefix . $table];
322
323
      }
    }
324
    throw new QueryException("'$property' not found");
325
326
327
328
329
330
331
332
333
334
  }

  /**
   * Join field table if necessary.
   *
   * @param $field_name
   *   Name of the field.
   * @return string
   * @throws \Drupal\Core\Entity\Query\QueryException
   */
335
  protected function ensureFieldTable($index_prefix, &$field, $type, $langcode, $base_table, $entity_id_field, $field_id_field, $delta) {
336
    $field_name = $field->getName();
337
    if (!isset($this->fieldTables[$index_prefix . $field_name])) {
338
339
340
      $entity_type_id = $this->sqlQuery->getMetaData('entity_type');
      /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
      $table_mapping = $this->entityManager->getStorage($entity_type_id)->getTableMapping();
341
      $table = !$this->sqlQuery->getMetaData('all_revisions') ? $table_mapping->getDedicatedDataTableName($field) : $table_mapping->getDedicatedRevisionTableName($field);
342
      if ($field->getCardinality() != 1) {
343
344
        $this->sqlQuery->addMetaData('simple_query', FALSE);
      }
345
      $this->fieldTables[$index_prefix . $field_name] = $this->addJoin($type, $table, "%alias.$field_id_field = $base_table.$entity_id_field", $langcode, $delta);
346
    }
347
    return $this->fieldTables[$index_prefix . $field_name];
348
349
  }

350
  protected function addJoin($type, $table, $join_condition, $langcode, $delta = NULL) {
351
    $arguments = [];
352
    if ($langcode) {
353
354
355
356
357
      $entity_type_id = $this->sqlQuery->getMetaData('entity_type');
      $entity_type = $this->entityManager->getDefinition($entity_type_id);
      // Only the data table follows the entity language key, dedicated field
      // tables have an hard-coded 'langcode' column.
      $langcode_key = $entity_type->getDataTable() == $table ? $entity_type->getKey('langcode') : 'langcode';
358
      $placeholder = ':langcode' . $this->sqlQuery->nextPlaceholder();
359
      $join_condition .= ' AND %alias.' . $langcode_key . ' = ' . $placeholder;
360
361
      $arguments[$placeholder] = $langcode;
    }
362
363
364
365
366
    if (isset($delta)) {
      $placeholder = ':delta' . $this->sqlQuery->nextPlaceholder();
      $join_condition .= ' AND %alias.delta = ' . $placeholder;
      $arguments[$placeholder] = $delta;
    }
367
368
369
    return $this->sqlQuery->addJoin($type, $table, NULL, $join_condition, $arguments);
  }

370
  /**
371
   * Gets the schema for the given table.
372
373
374
375
376
377
378
379
380
381
382
383
384
   *
   * @param string $table
   *   The table name.
   *
   * @return array|bool
   *   The table field mapping for the given table or FALSE if not available.
   */
  protected function getTableMapping($table, $entity_type_id) {
    $storage = $this->entityManager->getStorage($entity_type_id);
    if ($storage instanceof SqlEntityStorageInterface) {
      $mapping = $storage->getTableMapping()->getAllColumns($table);
    }
    else {
385
      return FALSE;
386
387
388
389
    }
    return array_flip($mapping);
  }

390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
  /**
   * Add the next entity base table.
   *
   * For example, when building the SQL query for
   * @code
   * condition('uid.entity.name', 'foo', 'CONTAINS')
   * @endcode
   *
   * this adds the users table.
   *
   * @param \Drupal\Core\Entity\EntityType $entity_type
   *   The entity type being joined, in the above example, User.
   * @param string $table
   *   This is the table being joined, in the above example, {users}.
   * @param string $sql_column
   *   This is the SQL column in the existing table being joined to.
   *
   * @return string
   *   The alias of the next entity table joined in.
   */
  protected function addNextBaseTable(EntityType $entity_type, $table, $sql_column) {
    $join_condition = '%alias.' . $entity_type->getKey('id') . " = $table.$sql_column";
    return $this->sqlQuery->leftJoin($entity_type->getBaseTable(), NULL, $join_condition);
  }

415
}