Tables.php 20.1 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
use Drupal\Core\Entity\TypedData\EntityDataDefinitionInterface;
11
use Drupal\Core\Field\FieldStorageDefinitionInterface;
12
use Drupal\Core\TypedData\DataReferenceDefinitionInterface;
13 14 15 16

/**
 * Adds tables and fields to the SQL entity query.
 */
17
class Tables implements TablesInterface {
18 19 20 21 22 23 24

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

  /**
25
   * Entity table array.
26 27
   *
   * This array contains at most two entries: one for the data, one for the
28 29 30 31
   * properties. Its keys are unique references to the tables, values are
   * aliases.
   *
   * @see \Drupal\Core\Entity\Query\Sql\Tables::ensureEntityTable().
32 33 34
   *
   * @var array
   */
35
  protected $entityTables = [];
36 37 38 39 40 41 42 43

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

46
  /**
47 48 49 50 51 52 53 54
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The entity field manager.
55
   *
56
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
57
   */
58
  protected $entityFieldManager;
59

60 61 62 63 64
  /**
   * List of case sensitive fields.
   *
   * @var array
   */
65
  protected $caseSensitiveFields = [];
66

67 68 69
  /**
   * @param \Drupal\Core\Database\Query\SelectInterface $sql_query
   */
70
  public function __construct(SelectInterface $sql_query) {
71
    $this->sqlQuery = $sql_query;
72 73
    $this->entityTypeManager = \Drupal::entityTypeManager();
    $this->entityFieldManager = \Drupal::service('entity_field.manager');
74 75 76
  }

  /**
77
   * {@inheritdoc}
78
   */
79
  public function addField($field, $type, $langcode) {
80
    $entity_type_id = $this->sqlQuery->getMetaData('entity_type');
81
    $all_revisions = $this->sqlQuery->getMetaData('all_revisions');
82 83 84 85 86 87 88 89 90 91 92 93 94
    // 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.
95
    $propertyDefinitions = [];
96
    $entity_type = $this->entityTypeManager->getActiveDefinition($entity_type_id);
97

98
    $field_storage_definitions = $this->entityFieldManager->getActiveFieldStorageDefinitions($entity_type_id);
99
    for ($key = 0; $key <= $count; $key++) {
100 101 102 103 104
      // 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];
105
        $column = $field_storage->getMainPropertyName();
106 107 108
      }
      else {
        $field_storage = FALSE;
109
        $column = NULL;
110 111
      }

112 113 114 115 116
      // If there is revision support, all the revisions are being queried, and
      // the field is revisionable or the revision ID field itself, then use the
      // revision ID. Otherwise, the entity ID will do.
      $query_revisions = $all_revisions && $field_storage && ($field_storage->isRevisionable() || $field_storage->getName() === $entity_type->getKey('revision'));
      if ($query_revisions) {
117 118
        // This contains the relevant SQL field to be used when joining entity
        // tables.
119
        $entity_id_field = $entity_type->getKey('revision');
120 121 122 123 124
        // This contains the relevant SQL field to be used when joining field
        // tables.
        $field_id_field = 'revision_id';
      }
      else {
125
        $entity_id_field = $entity_type->getKey('id');
126 127
        $field_id_field = 'entity_id';
      }
128 129

      /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
130
      $table_mapping = $this->entityTypeManager->getStorage($entity_type_id)->getTableMapping();
131 132 133

      // Check whether this field is stored in a dedicated table.
      if ($field_storage && $table_mapping->requiresDedicatedTableStorage($field_storage)) {
134
        $delta = NULL;
135

136 137
        if ($key < $count) {
          $next = $specifiers[$key + 1];
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
          // 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;
            }
          }
163
          // Is this a field column?
164
          $columns = $field_storage->getColumns();
165
          if (isset($columns[$next]) || in_array($next, $table_mapping->getReservedColumns())) {
166 167 168 169 170 171 172 173 174 175 176 177 178 179
            // 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];
180
            $propertyDefinitions = $field_storage->getPropertyDefinitions();
181

182 183 184 185
            // Prepare the next index prefix.
            $next_index_prefix = "$relationship_specifier.$column";
          }
        }
186
        $table = $this->ensureFieldTable($index_prefix, $field_storage, $type, $langcode, $base_table, $entity_id_field, $field_id_field, $delta);
187
        $sql_column = $table_mapping->getFieldColumnName($field_storage, $column);
188
      }
189
      // The field is stored in a shared table.
190 191 192
      else {
        // ensureEntityTable() decides whether an entity property will be
        // queried from the data table or the base table based on where it
193
        // finds the property first. The data table is preferred, which is why
194
        // it gets added before the base table.
195
        $entity_tables = [];
196
        $revision_table = NULL;
197
        if ($query_revisions) {
198 199 200 201 202 203
          $data_table = $entity_type->getRevisionDataTable();
          $entity_base_table = $entity_type->getRevisionTable();
        }
        else {
          $data_table = $entity_type->getDataTable();
          $entity_base_table = $entity_type->getBaseTable();
204 205 206 207

          if ($field_storage && $field_storage->isRevisionable() && in_array($field_storage->getName(), $entity_type->getRevisionMetadataKeys())) {
            $revision_table = $entity_type->getRevisionTable();
          }
208 209
        }
        if ($data_table) {
210
          $this->sqlQuery->addMetaData('simple_query', FALSE);
211
          $entity_tables[$data_table] = $this->getTableMapping($data_table, $entity_type_id);
212
        }
213 214 215
        if ($revision_table) {
          $entity_tables[$revision_table] = $this->getTableMapping($revision_table, $entity_type_id);
        }
216
        $entity_tables[$entity_base_table] = $this->getTableMapping($entity_base_table, $entity_type_id);
217
        $sql_column = $specifier;
218 219 220 221 222

        // 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];
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
          // 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) {
239
              $this->sqlQuery->alwaysFalse();
240 241 242 243
            }
            $key++;
            $next = $specifiers[$key + 1];
          }
244 245 246 247 248 249 250 251 252
          // 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++;
          }
        }
253 254 255 256 257 258 259 260
        // If there are no additional specifiers but the field has a main
        // property, use that to look up the column name.
        elseif ($field_storage && $column) {
          $columns = $field_storage->getColumns();
          if (isset($columns[$column])) {
            $sql_column = $table_mapping->getFieldColumnName($field_storage, $column);
          }
        }
261 262

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

265 266 267 268 269 270
      // If there is a field storage (some specifiers are not) and a field
      // column, check for case sensitivity.
      if ($field_storage && $column) {
        $property_definitions = $field_storage->getPropertyDefinitions();
        if (isset($property_definitions[$column])) {
          $this->caseSensitiveFields[$field] = $property_definitions[$column]->getSetting('case_sensitive');
271
        }
272
      }
273

274
      // If there are more specifiers to come, it's a relationship.
275
      if ($field_storage && $key < $count) {
276 277 278
        // Computed fields have prepared their property definition already, do
        // it for properties as well.
        if (!$propertyDefinitions) {
279
          $propertyDefinitions = $field_storage->getPropertyDefinitions();
280 281 282
          $relationship_specifier = $specifiers[$key + 1];
          $next_index_prefix = $relationship_specifier;
        }
283 284 285 286 287 288
        $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);
        }
289
        // Check for a valid relationship.
290 291 292 293 294 295 296
        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();
          }
297 298
          $entity_type = $this->entityTypeManager->getActiveDefinition($entity_type_id);
          $field_storage_definitions = $this->entityFieldManager->getActiveFieldStorageDefinitions($entity_type_id);
299
          // Add the new entity base table using the table and sql column.
300
          $base_table = $this->addNextBaseTable($entity_type, $table, $sql_column, $field_storage);
301
          $propertyDefinitions = [];
302 303 304 305
          $key++;
          $index_prefix .= "$next_index_prefix.";
        }
        else {
306
          throw new QueryException("Invalid specifier '$relationship_specifier'");
307 308
        }
      }
309 310 311 312
    }
    return "$table.$sql_column";
  }

313 314 315 316 317 318 319 320 321
  /**
   * {@inheritdoc}
   */
  public function isFieldCaseSensitive($field_name) {
    if (isset($this->caseSensitiveFields[$field_name])) {
      return $this->caseSensitiveFields[$field_name];
    }
  }

322
  /**
323
   * Joins the entity table, if necessary, and returns the alias for it.
324
   *
325 326 327 328
   * @param string $index_prefix
   *   The table array index prefix. For a base table this will be empty,
   *   for a target entity reference like 'field_tags.entity:taxonomy_term.name'
   *   this will be 'entity:taxonomy_term.target_id.'.
329
   * @param string $property
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
   *   The field property/column.
   * @param string $type
   *   The join type, can either be INNER or LEFT.
   * @param string $langcode
   *   The langcode we use on the join.
   * @param string $base_table
   *   The table to join to. It can be either the table name, its alias or the
   *   'base_table' placeholder.
   * @param string $id_field
   *   The name of the ID field/property for the current entity. For instance:
   *   tid, nid, etc.
   * @param array $entity_tables
   *   Array of entity tables (data and base tables) where decide the entity
   *   property will be queried from. The first table containing the property
   *   will be used, so the order is important and the data table is always
   *   preferred.
346
   *
347
   * @return string
348
   *   The alias of the joined table.
349
   *
350
   * @throws \Drupal\Core\Entity\Query\QueryException
351
   *   When an invalid property has been passed.
352
   */
353
  protected function ensureEntityTable($index_prefix, $property, $type, $langcode, $base_table, $id_field, $entity_tables) {
354 355
    foreach ($entity_tables as $table => $mapping) {
      if (isset($mapping[$property])) {
356 357 358 359 360 361 362
        // Ensure a table joined multiple times through different index prefixes
        // has unique entityTables entries by concatenating the index prefix
        // and the base table alias. In this way i.e. if we join to the same
        // entity table several times for different entity reference fields,
        // each join gets a separate alias.
        $key = $index_prefix . ($base_table === 'base_table' ? $table : $base_table);
        if (!isset($this->entityTables[$key])) {
363
          $this->entityTables[$key] = $this->addJoin($type, $table, "[%alias].[$id_field] = [$base_table].[$id_field]", $langcode);
364
        }
365
        return $this->entityTables[$key];
366 367
      }
    }
368
    throw new QueryException("'$property' not found");
369 370 371
  }

  /**
372
   * Ensure the field table is joined if necessary.
373
   *
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
   * @param string $index_prefix
   *   The table array index prefix. For a base table this will be empty,
   *   for a target entity reference like 'field_tags.entity:taxonomy_term.name'
   *   this will be 'entity:taxonomy_term.target_id.'.
   * @param \Drupal\Core\Field\FieldStorageDefinitionInterface &$field
   *   The field storage definition for the field being joined.
   * @param string $type
   *   The join type.
   * @param string $langcode
   *   The langcode we use on the join.
   * @param string $base_table
   *   The table to join to. It can be either the table name, its alias or the
   *   'base_table' placeholder.
   * @param string $entity_id_field
   *   The name of the ID field/property for the current entity. For instance:
   *   tid, nid, etc.
   * @param string $field_id_field
   *   The column representing the id for the field. For example, 'revision_id'
   *   or 'entity_id'.
   * @param string $delta
   *   A delta which should be used as additional condition.
395
   *
396
   * @return string
397
   *   The alias of the joined table.
398
   */
399
  protected function ensureFieldTable($index_prefix, &$field, $type, $langcode, $base_table, $entity_id_field, $field_id_field, $delta) {
400
    $field_name = $field->getName();
401
    if (!isset($this->fieldTables[$index_prefix . $field_name])) {
402 403
      $entity_type_id = $this->sqlQuery->getMetaData('entity_type');
      /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
404
      $table_mapping = $this->entityTypeManager->getStorage($entity_type_id)->getTableMapping();
405
      $table = !$this->sqlQuery->getMetaData('all_revisions') ? $table_mapping->getDedicatedDataTableName($field) : $table_mapping->getDedicatedRevisionTableName($field);
406
      if ($field->getCardinality() != 1) {
407 408
        $this->sqlQuery->addMetaData('simple_query', FALSE);
      }
409
      $this->fieldTables[$index_prefix . $field_name] = $this->addJoin($type, $table, "[%alias].[$field_id_field] = [$base_table].[$entity_id_field]", $langcode, $delta);
410
    }
411
    return $this->fieldTables[$index_prefix . $field_name];
412 413
  }

414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
  /**
   * Adds a join to a given table.
   *
   * @param string $type
   *   The join type.
   * @param string $table
   *   The table to join to.
   * @param string $join_condition
   *   The condition on which to join to.
   * @param string $langcode
   *   The langcode we use on the join.
   * @param string|null $delta
   *   (optional) A delta which should be used as additional condition.
   *
   * @return string
   *   Returns the alias of the joined table.
   */
431
  protected function addJoin($type, $table, $join_condition, $langcode, $delta = NULL) {
432
    $arguments = [];
433
    if ($langcode) {
434
      $entity_type_id = $this->sqlQuery->getMetaData('entity_type');
435
      $entity_type = $this->entityTypeManager->getActiveDefinition($entity_type_id);
436
      // Only the data table follows the entity language key, dedicated field
437
      // tables have a hard-coded 'langcode' column.
438
      $langcode_key = $entity_type->getDataTable() == $table ? $entity_type->getKey('langcode') : 'langcode';
439
      $placeholder = ':langcode' . $this->sqlQuery->nextPlaceholder();
440
      $join_condition .= ' AND [%alias].[' . $langcode_key . '] = ' . $placeholder;
441 442
      $arguments[$placeholder] = $langcode;
    }
443 444
    if (isset($delta)) {
      $placeholder = ':delta' . $this->sqlQuery->nextPlaceholder();
445
      $join_condition .= ' AND [%alias].[delta] = ' . $placeholder;
446 447
      $arguments[$placeholder] = $delta;
    }
448 449 450
    return $this->sqlQuery->addJoin($type, $table, NULL, $join_condition, $arguments);
  }

451
  /**
452
   * Gets the schema for the given table.
453 454 455
   *
   * @param string $table
   *   The table name.
456
   * @param string $entity_type_id
457
   *
458 459 460 461
   * @return array|false
   *   An associative array of table field mapping for the given table, keyed by
   *   columns name and values are just incrementing integers. If the table
   *   mapping is not available, FALSE is returned.
462 463
   */
  protected function getTableMapping($table, $entity_type_id) {
464
    $storage = $this->entityTypeManager->getStorage($entity_type_id);
465 466 467 468
    if ($storage instanceof SqlEntityStorageInterface) {
      $mapping = $storage->getTableMapping()->getAllColumns($table);
    }
    else {
469
      return FALSE;
470 471 472 473
    }
    return array_flip($mapping);
  }

474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
  /**
   * 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.
490 491
   * @param \Drupal\Core\Field\FieldStorageDefinitionInterface $field_storage
   *   The field storage definition for the field referencing this column.
492 493 494 495
   *
   * @return string
   *   The alias of the next entity table joined in.
   */
496
  protected function addNextBaseTable(EntityType $entity_type, $table, $sql_column, FieldStorageDefinitionInterface $field_storage) {
497 498 499 500
    $join_condition = '%alias.' . $entity_type->getKey('id') . " = $table.$sql_column";
    return $this->sqlQuery->leftJoin($entity_type->getBaseTable(), NULL, $join_condition);
  }

501
}