SqlContentEntityStorageSchema.php 91.4 KB
Newer Older
1 2
<?php

3
namespace Drupal\Core\Entity\Sql;
4

5
use Drupal\Core\Database\Connection;
6
use Drupal\Core\Database\DatabaseExceptionWrapper;
7
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
8 9
use Drupal\Core\Entity\ContentEntityTypeInterface;
use Drupal\Core\Entity\EntityManagerInterface;
10
use Drupal\Core\Entity\EntityPublishedInterface;
11
use Drupal\Core\Entity\EntityStorageException;
12
use Drupal\Core\Entity\EntityTypeInterface;
13
use Drupal\Core\Entity\Exception\FieldStorageDefinitionUpdateForbiddenException;
14
use Drupal\Core\Entity\Schema\DynamicallyFieldableEntityStorageSchemaInterface;
15
use Drupal\Core\Field\BaseFieldDefinition;
16
use Drupal\Core\Field\FieldException;
17
use Drupal\Core\Field\FieldStorageDefinitionInterface;
18
use Drupal\Core\Language\LanguageInterface;
19 20 21

/**
 * Defines a schema handler that supports revisionable, translatable entities.
22 23 24 25 26
 *
 * Entity types may extend this class and optimize the generated schema for all
 * entity base tables by overriding getEntitySchema() for cross-field
 * optimizations and getSharedTableFieldSchema() for optimizations applying to
 * a single field.
27
 */
28
class SqlContentEntityStorageSchema implements DynamicallyFieldableEntityStorageSchemaInterface {
29

30 31
  use DependencySerializationTrait;

32 33 34 35 36 37 38
  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
  protected $entityManager;

39 40 41 42 43 44 45 46 47 48
  /**
   * The entity type this schema builder is responsible for.
   *
   * @var \Drupal\Core\Entity\ContentEntityTypeInterface
   */
  protected $entityType;

  /**
   * The storage field definitions for this entity type.
   *
49
   * @var \Drupal\Core\Field\FieldStorageDefinitionInterface[]
50 51 52
   */
  protected $fieldStorageDefinitions;

53 54 55 56 57 58 59 60
  /**
   * The original storage field definitions for this entity type. Used during
   * field schema updates.
   *
   * @var \Drupal\Core\Field\FieldDefinitionInterface[]
   */
  protected $originalDefinitions;

61 62 63
  /**
   * The storage object for the given entity type.
   *
64
   * @var \Drupal\Core\Entity\Sql\SqlContentEntityStorage
65 66 67 68 69 70 71 72 73 74
   */
  protected $storage;

  /**
   * A static cache of the generated schema array.
   *
   * @var array
   */
  protected $schema;

75 76 77 78 79 80 81
  /**
   * The database connection to be used.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

82 83 84 85 86 87 88
  /**
   * The key-value collection for tracking installed storage schema.
   *
   * @var \Drupal\Core\KeyValueStore\KeyValueStoreInterface
   */
  protected $installedStorageSchema;

89 90 91 92 93 94 95
  /**
   * The deleted fields repository.
   *
   * @var \Drupal\Core\Field\DeletedFieldsRepositoryInterface
   */
  protected $deletedFieldsRepository;

96
  /**
97
   * Constructs a SqlContentEntityStorageSchema.
98 99 100 101 102
   *
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager.
   * @param \Drupal\Core\Entity\ContentEntityTypeInterface $entity_type
   *   The entity type.
103
   * @param \Drupal\Core\Entity\Sql\SqlContentEntityStorage $storage
104
   *   The storage of the entity type. This must be an SQL-based storage.
105 106
   * @param \Drupal\Core\Database\Connection $database
   *   The database connection to be used.
107
   */
108
  public function __construct(EntityManagerInterface $entity_manager, ContentEntityTypeInterface $entity_type, SqlContentEntityStorage $storage, Connection $database) {
109
    $this->entityManager = $entity_manager;
110 111 112
    $this->entityType = $entity_type;
    $this->fieldStorageDefinitions = $entity_manager->getFieldStorageDefinitions($entity_type->id());
    $this->storage = $storage;
113 114 115
    $this->database = $database;
  }

116
  /**
117
   * Gets the keyvalue collection for tracking the installed schema.
118 119 120 121 122 123 124 125 126 127 128 129 130 131
   *
   * @return \Drupal\Core\KeyValueStore\KeyValueStoreInterface
   *
   * @todo Inject this dependency in the constructor once this class can be
   *   instantiated as a regular entity handler:
   *   https://www.drupal.org/node/2332857.
   */
  protected function installedStorageSchema() {
    if (!isset($this->installedStorageSchema)) {
      $this->installedStorageSchema = \Drupal::keyValue('entity.storage_schema.sql');
    }
    return $this->installedStorageSchema;
  }

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
  /**
   * Gets the deleted fields repository.
   *
   * @return \Drupal\Core\Field\DeletedFieldsRepositoryInterface
   *   The deleted fields repository.
   *
   * @todo Inject this dependency in the constructor once this class can be
   *   instantiated as a regular entity handler:
   *   https://www.drupal.org/node/2332857.
   */
  protected function deletedFieldsRepository() {
    if (!isset($this->deletedFieldsRepository)) {
      $this->deletedFieldsRepository = \Drupal::service('entity_field.deleted_fields_repository');
    }
    return $this->deletedFieldsRepository;
  }

149 150 151 152 153
  /**
   * {@inheritdoc}
   */
  public function requiresEntityStorageSchemaChanges(EntityTypeInterface $entity_type, EntityTypeInterface $original) {
    return
alexpott's avatar
alexpott committed
154
      $this->hasSharedTableStructureChange($entity_type, $original) ||
155 156
      // Detect changes in key or index definitions.
      $this->getEntitySchemaData($entity_type, $this->getEntitySchema($entity_type, TRUE)) != $this->loadEntitySchemaData($original);
157 158
  }

alexpott's avatar
alexpott committed
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
  /**
   * Detects whether there is a change in the shared table structure.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The new entity type.
   * @param \Drupal\Core\Entity\EntityTypeInterface $original
   *   The origin entity type.
   *
   * @return bool
   *   Returns TRUE if either the revisionable or translatable flag changes or
   *   a table has been renamed.
   */
  protected function hasSharedTableStructureChange(EntityTypeInterface $entity_type, EntityTypeInterface $original) {
    return
      $entity_type->isRevisionable() != $original->isRevisionable() ||
      $entity_type->isTranslatable() != $original->isTranslatable() ||
      $this->hasSharedTableNameChanges($entity_type, $original);
  }

178 179 180 181 182 183 184 185 186 187 188 189
  /**
   * Detects whether any table name got renamed in an entity type update.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The new entity type.
   * @param \Drupal\Core\Entity\EntityTypeInterface $original
   *   The origin entity type.
   *
   * @return bool
   *   Returns TRUE if there have been changes.
   */
  protected function hasSharedTableNameChanges(EntityTypeInterface $entity_type, EntityTypeInterface $original) {
190 191 192 193 194 195 196 197
    $base_table = $this->database->schema()->tableExists($entity_type->getBaseTable());
    $data_table = $this->database->schema()->tableExists($entity_type->getDataTable());
    $revision_table = $this->database->schema()->tableExists($entity_type->getRevisionTable());
    $revision_data_table = $this->database->schema()->tableExists($entity_type->getRevisionDataTable());

    // We first check if the new table already exists because the storage might
    // have created it even though it wasn't specified in the entity type
    // definition.
198
    return
199 200 201 202
      (!$base_table && $entity_type->getBaseTable() != $original->getBaseTable()) ||
      (!$data_table && $entity_type->getDataTable() != $original->getDataTable()) ||
      (!$revision_table && $entity_type->getRevisionTable() != $original->getRevisionTable()) ||
      (!$revision_data_table && $entity_type->getRevisionDataTable() != $original->getRevisionDataTable());
203 204
  }

205 206 207 208
  /**
   * {@inheritdoc}
   */
  public function requiresFieldStorageSchemaChanges(FieldStorageDefinitionInterface $storage_definition, FieldStorageDefinitionInterface $original) {
209 210 211
    $table_mapping = $this->storage->getTableMapping();

    if (
212 213 214
      $storage_definition->hasCustomStorage() != $original->hasCustomStorage() ||
      $storage_definition->getSchema() != $original->getSchema() ||
      $storage_definition->isRevisionable() != $original->isRevisionable() ||
215 216 217 218 219 220
      $table_mapping->allowsSharedTableStorage($storage_definition) != $table_mapping->allowsSharedTableStorage($original) ||
      $table_mapping->requiresDedicatedTableStorage($storage_definition) != $table_mapping->requiresDedicatedTableStorage($original)
    ) {
      return TRUE;
    }

221 222 223 224 225 226 227 228
    if ($storage_definition->hasCustomStorage()) {
      // The field has custom storage, so we don't know if a schema change is
      // needed or not, but since per the initial checks earlier in this
      // function, nothing about the definition changed that we manage, we
      // return FALSE.
      return FALSE;
    }

229 230
    $current_schema = $this->getSchemaFromStorageDefinition($storage_definition);
    $this->processFieldStorageSchema($current_schema);
231 232
    $installed_schema = $this->loadFieldSchemaData($original);
    $this->processFieldStorageSchema($installed_schema);
233

234
    return $current_schema != $installed_schema;
235 236 237 238 239 240 241 242 243 244 245 246 247
  }

  /**
   * Gets the schema data for the given field storage definition.
   *
   * @param \Drupal\Core\Field\FieldStorageDefinitionInterface $storage_definition
   *   The field storage definition. The field that must not have custom
   *   storage, i.e. the storage must take care of storing the field.
   *
   * @return array
   *   The schema data.
   */
  protected function getSchemaFromStorageDefinition(FieldStorageDefinitionInterface $storage_definition) {
248
    assert(!$storage_definition->hasCustomStorage());
249 250
    $table_mapping = $this->storage->getTableMapping();
    $schema = [];
251
    if ($table_mapping->requiresDedicatedTableStorage($storage_definition)) {
252
      $schema = $this->getDedicatedTableSchema($storage_definition);
253 254 255 256 257 258 259 260 261 262
    }
    elseif ($table_mapping->allowsSharedTableStorage($storage_definition)) {
      $field_name = $storage_definition->getName();
      foreach (array_diff($table_mapping->getTableNames(), $table_mapping->getDedicatedTableNames()) as $table_name) {
        if (in_array($field_name, $table_mapping->getFieldNames($table_name))) {
          $column_names = $table_mapping->getColumnNames($storage_definition->getName());
          $schema[$table_name] = $this->getSharedTableFieldSchema($storage_definition, $table_name, $column_names);
        }
      }
    }
263
    return $schema;
264 265 266 267 268 269
  }

  /**
   * {@inheritdoc}
   */
  public function requiresEntityDataMigration(EntityTypeInterface $entity_type, EntityTypeInterface $original) {
270 271 272 273 274 275
    // Check if the entity type specifies that data migration is being handled
    // elsewhere.
    if ($entity_type->get('requires_data_migration') === FALSE) {
      return FALSE;
    }

276 277
    // If the original storage has existing entities, or it is impossible to
    // determine if that is the case, require entity data to be migrated.
278
    $original_storage_class = $original->getStorageClass();
279 280
    if (!class_exists($original_storage_class)) {
      return TRUE;
281
    }
alexpott's avatar
alexpott committed
282 283 284 285 286 287 288

    // Data migration is not needed when only indexes changed, as they can be
    // applied if there is data.
    if (!$this->hasSharedTableStructureChange($entity_type, $original)) {
      return FALSE;
    }

289 290 291
    // Use the original entity type since the storage has not been updated.
    $original_storage = $this->entityManager->createHandlerInstance($original_storage_class, $original);
    return $original_storage->hasData();
292 293 294 295 296 297
  }

  /**
   * {@inheritdoc}
   */
  public function requiresFieldDataMigration(FieldStorageDefinitionInterface $storage_definition, FieldStorageDefinitionInterface $original) {
298
    return !$this->storage->countFieldData($original, TRUE);
299 300
  }

301 302 303 304
  /**
   * {@inheritdoc}
   */
  public function onEntityTypeCreate(EntityTypeInterface $entity_type) {
305
    $this->checkEntityType($entity_type);
306
    $schema_handler = $this->database->schema();
307 308

    // Create entity tables.
309 310 311 312 313 314
    $schema = $this->getEntitySchema($entity_type, TRUE);
    foreach ($schema as $table_name => $table_schema) {
      if (!$schema_handler->tableExists($table_name)) {
        $schema_handler->createTable($table_name, $table_schema);
      }
    }
315 316

    // Create dedicated field tables.
317 318
    $table_mapping = $this->storage->getTableMapping($this->fieldStorageDefinitions);
    foreach ($this->fieldStorageDefinitions as $field_storage_definition) {
319 320 321 322 323 324 325 326 327 328 329 330
      if ($table_mapping->requiresDedicatedTableStorage($field_storage_definition)) {
        $this->createDedicatedTableSchema($field_storage_definition);
      }
      elseif ($table_mapping->allowsSharedTableStorage($field_storage_definition)) {
        // The shared tables are already fully created, but we need to save the
        // per-field schema definitions for later use.
        $this->createSharedTableSchema($field_storage_definition, TRUE);
      }
    }

    // Save data about entity indexes and keys.
    $this->saveEntitySchemaData($entity_type, $schema);
331 332 333 334 335 336
  }

  /**
   * {@inheritdoc}
   */
  public function onEntityTypeUpdate(EntityTypeInterface $entity_type, EntityTypeInterface $original) {
337 338 339 340 341 342 343 344
    $this->checkEntityType($entity_type);
    $this->checkEntityType($original);

    // If no schema changes are needed, we don't need to do anything.
    if (!$this->requiresEntityStorageSchemaChanges($entity_type, $original)) {
      return;
    }

345 346
    // If a migration is required, we can't proceed.
    if ($this->requiresEntityDataMigration($entity_type, $original)) {
347
      throw new EntityStorageException('The SQL storage cannot change the schema for an existing entity type (' . $entity_type->id() . ') with data.');
348 349
    }

350
    // If we have no data just recreate the entity schema from scratch.
351
    if ($this->isTableEmpty($this->storage->getBaseTable())) {
352 353 354 355 356 357 358 359 360 361 362
      if ($this->database->supportsTransactionalDDL()) {
        // If the database supports transactional DDL, we can go ahead and rely
        // on it. If not, we will have to rollback manually if something fails.
        $transaction = $this->database->startTransaction();
      }
      try {
        $this->onEntityTypeDelete($original);
        $this->onEntityTypeCreate($entity_type);
      }
      catch (\Exception $e) {
        if ($this->database->supportsTransactionalDDL()) {
363
          $transaction->rollBack();
364 365 366 367 368 369 370 371 372
        }
        else {
          // Recreate original schema.
          $this->onEntityTypeCreate($original);
        }
        throw $e;
      }
    }
    else {
373
      // Drop original indexes and unique keys.
374
      $this->deleteEntitySchemaIndexes($this->loadEntitySchemaData($entity_type));
375 376 377

      // Create new indexes and unique keys.
      $entity_schema = $this->getEntitySchema($entity_type, TRUE);
378
      $this->createEntitySchemaIndexes($entity_schema);
379 380 381

      // Store the updated entity schema.
      $this->saveEntitySchemaData($entity_type, $entity_schema);
382
    }
383 384 385 386 387
  }

  /**
   * {@inheritdoc}
   */
388
  public function onEntityTypeDelete(EntityTypeInterface $entity_type) {
389
    $this->checkEntityType($entity_type);
390
    $schema_handler = $this->database->schema();
391 392 393 394 395 396

    $field_storage_definitions = $this->entityManager->getLastInstalledFieldStorageDefinitions($entity_type->id());
    $table_mapping = $this->storage->getCustomTableMapping($entity_type, $field_storage_definitions);

    // Delete entity and field tables.
    foreach ($table_mapping->getTableNames() as $table_name) {
397 398 399 400
      if ($schema_handler->tableExists($table_name)) {
        $schema_handler->dropTable($table_name);
      }
    }
401

402
    // Delete the field schema data.
403
    foreach ($field_storage_definitions as $field_storage_definition) {
404
      $this->deleteFieldSchemaData($field_storage_definition);
405 406 407 408
    }

    // Delete the entity schema.
    $this->deleteEntitySchemaData($entity_type);
409 410
  }

411 412 413 414
  /**
   * {@inheritdoc}
   */
  public function onFieldStorageDefinitionCreate(FieldStorageDefinitionInterface $storage_definition) {
415
    $this->performFieldSchemaOperation('create', $storage_definition);
416 417 418 419 420 421
  }

  /**
   * {@inheritdoc}
   */
  public function onFieldStorageDefinitionUpdate(FieldStorageDefinitionInterface $storage_definition, FieldStorageDefinitionInterface $original) {
422 423 424
    // Store original definitions so that switching between shared and dedicated
    // field table layout works.
    $this->performFieldSchemaOperation('update', $storage_definition, $original);
425 426 427 428 429 430
  }

  /**
   * {@inheritdoc}
   */
  public function onFieldStorageDefinitionDelete(FieldStorageDefinitionInterface $storage_definition) {
431
    try {
432
      $has_data = $this->storage->countFieldData($storage_definition, TRUE);
433
    }
434
    catch (DatabaseExceptionWrapper $e) {
435 436 437 438 439
      // This may happen when changing field storage schema, since we are not
      // able to use a table mapping matching the passed storage definition.
      // @todo Revisit this once we are able to instantiate the table mapping
      //   properly. See https://www.drupal.org/node/2274017.
      return;
440 441
    }

442 443 444 445 446 447 448 449 450 451 452 453
    // If the field storage does not have any data, we can safely delete its
    // schema.
    if (!$has_data) {
      $this->performFieldSchemaOperation('delete', $storage_definition);
      return;
    }

    // There's nothing else we can do if the field storage has a custom storage.
    if ($storage_definition->hasCustomStorage()) {
      return;
    }

454
    // Retrieve a table mapping which contains the deleted field still.
455 456
    $storage_definitions = $this->entityManager->getLastInstalledFieldStorageDefinitions($this->entityType->id());
    $table_mapping = $this->storage->getTableMapping($storage_definitions);
457
    $field_table_name = $table_mapping->getFieldTableName($storage_definition->getName());
458

459 460 461 462 463 464 465 466 467 468 469 470
    if ($table_mapping->requiresDedicatedTableStorage($storage_definition)) {
      // Move the table to a unique name while the table contents are being
      // deleted.
      $table = $table_mapping->getDedicatedDataTableName($storage_definition);
      $new_table = $table_mapping->getDedicatedDataTableName($storage_definition, TRUE);
      $this->database->schema()->renameTable($table, $new_table);
      if ($this->entityType->isRevisionable()) {
        $revision_table = $table_mapping->getDedicatedRevisionTableName($storage_definition);
        $revision_new_table = $table_mapping->getDedicatedRevisionTableName($storage_definition, TRUE);
        $this->database->schema()->renameTable($revision_table, $revision_new_table);
      }
    }
471 472 473 474
    else {
      // Move the field data from the shared table to a dedicated one in order
      // to allow it to be purged like any other field.
      $shared_table_field_columns = $table_mapping->getColumnNames($storage_definition->getName());
475

476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
      // Refresh the table mapping to use the deleted storage definition.
      $deleted_storage_definition = $this->deletedFieldsRepository()->getFieldStorageDefinitions()[$storage_definition->getUniqueStorageIdentifier()];
      $original_storage_definitions = [$storage_definition->getName() => $deleted_storage_definition] + $storage_definitions;
      $table_mapping = $this->storage->getTableMapping($original_storage_definitions);

      $dedicated_table_field_schema = $this->getDedicatedTableSchema($deleted_storage_definition);
      $dedicated_table_field_columns = $table_mapping->getColumnNames($deleted_storage_definition->getName());

      $dedicated_table_name = $table_mapping->getDedicatedDataTableName($deleted_storage_definition, TRUE);
      $dedicated_table_name_mapping[$table_mapping->getDedicatedDataTableName($deleted_storage_definition)] = $dedicated_table_name;
      if ($this->entityType->isRevisionable()) {
        $dedicated_revision_table_name = $table_mapping->getDedicatedRevisionTableName($deleted_storage_definition, TRUE);
        $dedicated_table_name_mapping[$table_mapping->getDedicatedRevisionTableName($deleted_storage_definition)] = $dedicated_revision_table_name;
      }

      // Create the dedicated field tables using "deleted" table names.
      foreach ($dedicated_table_field_schema as $name => $table) {
        if (!$this->database->schema()->tableExists($dedicated_table_name_mapping[$name])) {
          $this->database->schema()->createTable($dedicated_table_name_mapping[$name], $table);
        }
        else {
          throw new EntityStorageException('The field ' . $storage_definition->getName() . ' has already been deleted and it is in the process of being purged.');
        }
      }

      if ($this->database->supportsTransactionalDDL()) {
        // If the database supports transactional DDL, we can go ahead and rely
        // on it. If not, we will have to rollback manually if something fails.
        $transaction = $this->database->startTransaction();
      }
      try {
        // Copy the data from the base table.
        $this->database->insert($dedicated_table_name)
509
          ->from($this->getSelectQueryForFieldStorageDeletion($field_table_name, $shared_table_field_columns, $dedicated_table_field_columns))
510 511 512 513
          ->execute();

        // Copy the data from the revision table.
        if (isset($dedicated_revision_table_name)) {
514 515 516 517 518 519
          if ($this->entityType->isTranslatable()) {
            $revision_table = $storage_definition->isRevisionable() ? $this->storage->getRevisionDataTable() : $this->storage->getDataTable();
          }
          else {
            $revision_table = $storage_definition->isRevisionable() ? $this->storage->getRevisionTable() : $this->storage->getBaseTable();
          }
520
          $this->database->insert($dedicated_revision_table_name)
521
            ->from($this->getSelectQueryForFieldStorageDeletion($revision_table, $shared_table_field_columns, $dedicated_table_field_columns, $field_table_name))
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
            ->execute();
        }
      }
      catch (\Exception $e) {
        if (isset($transaction)) {
          $transaction->rollBack();
        }
        else {
          // Delete the dedicated tables.
          foreach ($dedicated_table_field_schema as $name => $table) {
            $this->database->schema()->dropTable($dedicated_table_name_mapping[$name]);
          }
        }
        throw $e;
      }

      // Delete the field from the shared tables.
      $this->deleteSharedTableSchema($storage_definition);
540 541 542 543 544 545 546 547
    }
  }

  /**
   * {@inheritdoc}
   */
  public function finalizePurge(FieldStorageDefinitionInterface $storage_definition) {
    $this->performFieldSchemaOperation('delete', $storage_definition);
548 549
  }

550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
  /**
   * Returns a SELECT query suitable for inserting data into a dedicated table.
   *
   * @param string $table_name
   *   The entity table name to select from.
   * @param array $shared_table_field_columns
   *   An array of field column names for a shared table schema.
   * @param array $dedicated_table_field_columns
   *   An array of field column names for a dedicated table schema.
   * @param string $base_table
   *   (optional) The name of the base entity table. Defaults to NULL.
   *
   * @return \Drupal\Core\Database\Query\SelectInterface
   *   A database select query.
   */
  protected function getSelectQueryForFieldStorageDeletion($table_name, array $shared_table_field_columns, array $dedicated_table_field_columns, $base_table = NULL) {
    // Create a SELECT query that generates a result suitable for writing into
    // a dedicated field table.
    $select = $this->database->select($table_name, 'entity_table');

    // Add the bundle column.
    if ($bundle = $this->entityType->getKey('bundle')) {
      if ($base_table) {
        $select->join($base_table, 'base_table', "entity_table.{$this->entityType->getKey('id')} = %alias.{$this->entityType->getKey('id')}");
        $select->addField('base_table', $bundle, 'bundle');
      }
      else {
        $select->addField('entity_table', $bundle, 'bundle');
      }
    }
    else {
      $select->addExpression(':bundle', 'bundle', [':bundle' => $this->entityType->id()]);
    }

    // Add the deleted column.
    $select->addExpression(':deleted', 'deleted', [':deleted' => 1]);

    // Add the entity_id column.
    $select->addField('entity_table', $this->entityType->getKey('id'), 'entity_id');

    // Add the revision_id column.
    if ($this->entityType->isRevisionable()) {
      $select->addField('entity_table', $this->entityType->getKey('revision'), 'revision_id');
    }
    else {
      $select->addField('entity_table', $this->entityType->getKey('id'), 'revision_id');
    }

    // Add the langcode column.
    if ($langcode = $this->entityType->getKey('langcode')) {
      $select->addField('entity_table', $langcode, 'langcode');
    }
    else {
      $select->addExpression(':langcode', 'langcode', [':langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED]);
    }

    // Add the delta column and set it to 0 because we are only dealing with
    // single cardinality fields.
    $select->addExpression(':delta', 'delta', [':delta' => 0]);

    // Add all the dynamic field columns.
611
    $or = $select->orConditionGroup();
612 613
    foreach ($shared_table_field_columns as $field_column_name => $schema_column_name) {
      $select->addField('entity_table', $schema_column_name, $dedicated_table_field_columns[$field_column_name]);
614
      $or->isNotNull('entity_table.' . $schema_column_name);
615
    }
616
    $select->condition($or);
617 618 619 620 621 622 623

    // Lock the table rows.
    $select->forUpdate(TRUE);

    return $select;
  }

624 625 626 627 628 629 630 631 632 633 634 635 636
  /**
   * Checks that we are dealing with the correct entity type.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type to be checked.
   *
   * @return bool
   *   TRUE if the entity type matches the current one.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  protected function checkEntityType(EntityTypeInterface $entity_type) {
    if ($entity_type->id() != $this->entityType->id()) {
637
      throw new EntityStorageException("Unsupported entity type {$entity_type->id()}");
638 639 640 641
    }
    return TRUE;
  }

642
  /**
643
   * Gets the entity schema for the specified entity type.
644
   *
645 646 647 648 649 650
   * Entity types may override this method in order to optimize the generated
   * schema of the entity tables. However, only cross-field optimizations should
   * be added here; e.g., an index spanning multiple fields. Optimizations that
   * apply to a single field have to be added via
   * SqlContentEntityStorageSchema::getSharedTableFieldSchema() instead.
   *
651 652 653 654 655 656 657 658 659
   * @param \Drupal\Core\Entity\ContentEntityTypeInterface $entity_type
   *   The entity type definition.
   * @param bool $reset
   *   (optional) If set to TRUE static cache will be ignored and a new schema
   *   array generation will be performed. Defaults to FALSE.
   *
   * @return array
   *   A Schema API array describing the entity schema, excluding dedicated
   *   field tables.
660 661
   *
   * @throws \Drupal\Core\Field\FieldException
662 663
   */
  protected function getEntitySchema(ContentEntityTypeInterface $entity_type, $reset = FALSE) {
664
    $this->checkEntityType($entity_type);
665
    $entity_type_id = $entity_type->id();
666

667
    if (!isset($this->schema[$entity_type_id]) || $reset) {
668
      // Prepare basic information about the entity type.
669
      $tables = $this->getEntitySchemaTables();
670 671 672

      // Initialize the table schema.
      $schema[$tables['base_table']] = $this->initializeBaseTable($entity_type);
673
      if (isset($tables['revision_table'])) {
674
        $schema[$tables['revision_table']] = $this->initializeRevisionTable($entity_type);
675 676
      }
      if (isset($tables['data_table'])) {
677
        $schema[$tables['data_table']] = $this->initializeDataTable($entity_type);
678 679
      }
      if (isset($tables['revision_data_table'])) {
680
        $schema[$tables['revision_data_table']] = $this->initializeRevisionDataTable($entity_type);
681 682
      }

683
      // We need to act only on shared entity schema tables.
684
      $table_mapping = $this->storage->getCustomTableMapping($entity_type, $this->fieldStorageDefinitions);
685 686 687
      $table_names = array_diff($table_mapping->getTableNames(), $table_mapping->getDedicatedTableNames());
      foreach ($table_names as $table_name) {
        if (!isset($schema[$table_name])) {
688
          $schema[$table_name] = [];
689
        }
690
        foreach ($table_mapping->getFieldNames($table_name) as $field_name) {
691
          if (!isset($this->fieldStorageDefinitions[$field_name])) {
692
            throw new FieldException("Field storage definition for '$field_name' could not be found.");
693 694
          }
          // Add the schema for base field definitions.
695
          elseif ($table_mapping->allowsSharedTableStorage($this->fieldStorageDefinitions[$field_name])) {
696
            $column_names = $table_mapping->getColumnNames($field_name);
697
            $storage_definition = $this->fieldStorageDefinitions[$field_name];
698 699
            $schema[$table_name] = array_merge_recursive($schema[$table_name], $this->getSharedTableFieldSchema($storage_definition, $table_name, $column_names));
          }
700 701 702 703
        }
      }

      // Process tables after having gathered field information.
704
      $this->processBaseTable($entity_type, $schema[$tables['base_table']]);
705
      if (isset($tables['revision_table'])) {
706
        $this->processRevisionTable($entity_type, $schema[$tables['revision_table']]);
707 708
      }
      if (isset($tables['data_table'])) {
709
        $this->processDataTable($entity_type, $schema[$tables['data_table']]);
710 711
      }
      if (isset($tables['revision_data_table'])) {
712
        $this->processRevisionDataTable($entity_type, $schema[$tables['revision_data_table']]);
713 714
      }

715 716 717
      // Add an index for the 'published' entity key.
      if (is_subclass_of($entity_type->getClass(), EntityPublishedInterface::class)) {
        $published_key = $entity_type->getKey('published');
718
        if ($published_key && !$this->fieldStorageDefinitions[$published_key]->hasCustomStorage()) {
719 720 721 722 723 724 725 726 727 728 729 730 731 732
          $published_field_table = $table_mapping->getFieldTableName($published_key);
          $id_key = $entity_type->getKey('id');
          if ($bundle_key = $entity_type->getKey('bundle')) {
            $key = "{$published_key}_{$bundle_key}";
            $columns = [$published_key, $bundle_key, $id_key];
          }
          else {
            $key = $published_key;
            $columns = [$published_key, $id_key];
          }
          $schema[$published_field_table]['indexes'][$this->getEntityIndexName($entity_type, $key)] = $columns;
        }
      }

733
      $this->schema[$entity_type_id] = $schema;
734 735
    }

736
    return $this->schema[$entity_type_id];
737 738 739 740 741 742 743 744
  }

  /**
   * Gets a list of entity type tables.
   *
   * @return array
   *   A list of entity type tables, keyed by table key.
   */
745
  protected function getEntitySchemaTables() {
746
    return array_filter([
747 748 749 750
      'base_table' => $this->storage->getBaseTable(),
      'revision_table' => $this->storage->getRevisionTable(),
      'data_table' => $this->storage->getDataTable(),
      'revision_data_table' => $this->storage->getRevisionDataTable(),
751
    ]);
752 753 754
  }

  /**
755
   * Gets entity schema definitions for index and key definitions.
756
   *
757 758
   * @param \Drupal\Core\Entity\ContentEntityTypeInterface $entity_type
   *   The entity type definition.
759
   * @param array $schema
760 761 762 763 764 765
   *   The entity schema array.
   *
   * @return array
   *   A stripped down version of the $schema Schema API array containing, for
   *   each table, only the key and index definitions not derived from field
   *   storage definitions.
766
   */
767 768
  protected function getEntitySchemaData(ContentEntityTypeInterface $entity_type, array $schema) {
    $entity_type_id = $entity_type->id();
769

770 771 772
    // Collect all possible field schema identifiers for shared table fields.
    // These will be used to detect entity schema data in the subsequent loop.
    $field_schema_identifiers = [];
773 774
    $table_mapping = $this->storage->getTableMapping($this->fieldStorageDefinitions);
    foreach ($this->fieldStorageDefinitions as $field_name => $storage_definition) {
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
      if ($table_mapping->allowsSharedTableStorage($storage_definition)) {
        // Make sure both base identifier names and suffixed names are listed.
        $name = $this->getFieldSchemaIdentifierName($entity_type_id, $field_name);
        $field_schema_identifiers[$name] = $name;
        foreach ($storage_definition->getColumns() as $key => $columns) {
          $name = $this->getFieldSchemaIdentifierName($entity_type_id, $field_name, $key);
          $field_schema_identifiers[$name] = $name;
        }
      }
    }

    // Extract entity schema data from the Schema API definition.
    $schema_data = [];
    $keys = ['indexes', 'unique keys'];
    $unused_keys = array_flip(['description', 'fields', 'foreign keys']);
790 791 792 793 794
    foreach ($schema as $table_name => $table_schema) {
      $table_schema = array_diff_key($table_schema, $unused_keys);
      foreach ($keys as $key) {
        // Exclude data generated from field storage definitions, we will check
        // that separately.
795 796
        if ($field_schema_identifiers && !empty($table_schema[$key])) {
          $table_schema[$key] = array_diff_key($table_schema[$key], $field_schema_identifiers);
797
        }
798
      }
799
      $schema_data[$table_name] = array_filter($table_schema);
800 801
    }

802
    return $schema_data;
803 804 805
  }

  /**
806
   * Gets an index schema array for a given field.
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
   *
   * @param string $field_name
   *   The name of the field.
   * @param array $field_schema
   *   The schema of the field.
   * @param string[] $column_mapping
   *   A mapping of field column names to database column names.
   *
   * @return array
   *   The schema definition for the indexes.
   */
  protected function getFieldIndexes($field_name, array $field_schema, array $column_mapping) {
    return $this->getFieldSchemaData($field_name, $field_schema, $column_mapping, 'indexes');
  }

  /**
823
   * Gets a unique key schema array for a given field.
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
   *
   * @param string $field_name
   *   The name of the field.
   * @param array $field_schema
   *   The schema of the field.
   * @param string[] $column_mapping
   *   A mapping of field column names to database column names.
   *
   * @return array
   *   The schema definition for the unique keys.
   */
  protected function getFieldUniqueKeys($field_name, array $field_schema, array $column_mapping) {
    return $this->getFieldSchemaData($field_name, $field_schema, $column_mapping, 'unique keys');
  }

  /**
840
   * Gets field schema data for the given key.
841 842 843 844 845 846 847 848 849 850 851 852 853 854
   *
   * @param string $field_name
   *   The name of the field.
   * @param array $field_schema
   *   The schema of the field.
   * @param string[] $column_mapping
   *   A mapping of field column names to database column names.
   * @param string $schema_key
   *   The type of schema data. Either 'indexes' or 'unique keys'.
   *
   * @return array
   *   The schema definition for the specified key.
   */
  protected function getFieldSchemaData($field_name, array $field_schema, array $column_mapping, $schema_key) {
855
    $data = [];
856

857
    $entity_type_id = $this->entityType->id();
858 859 860 861 862 863
    foreach ($field_schema[$schema_key] as $key => $columns) {
      // To avoid clashes with entity-level indexes or unique keys we use
      // "{$entity_type_id}_field__" as a prefix instead of just
      // "{$entity_type_id}__". We additionally namespace the specifier by the
      // field name to avoid clashes when multiple fields of the same type are
      // added to an entity type.
864
      $real_key = $this->getFieldSchemaIdentifierName($entity_type_id, $field_name, $key);
865 866 867 868 869
      foreach ($columns as $column) {
        // Allow for indexes and unique keys to specified as an array of column
        // name and length.
        if (is_array($column)) {
          list($column_name, $length) = $column;
870
          $data[$real_key][] = [$column_mapping[$column_name], $length];
871 872 873 874 875 876 877 878 879 880
        }
        else {
          $data[$real_key][] = $column_mapping[$column];
        }
      }
    }

    return $data;
  }

881 882 883 884 885 886 887
  /**
   * Generates a safe schema identifier (name of an index, column name etc.).
   *
   * @param string $entity_type_id
   *   The ID of the entity type.
   * @param string $field_name
   *   The name of the field.
888 889
   * @param string|null $key
   *   (optional) A further key to append to the name.
890 891 892 893
   *
   * @return string
   *   The field identifier name.
   */
894 895
  protected function getFieldSchemaIdentifierName($entity_type_id, $field_name, $key = NULL) {
    $real_key = isset($key) ? "{$entity_type_id}_field__{$field_name}__{$key}" : "{$entity_type_id}_field__{$field_name}";
896 897 898 899 900 901 902 903 904 905 906 907 908
    // Limit the string to 48 characters, keeping a 16 characters margin for db
    // prefixes.
    if (strlen($real_key) > 48) {
      // Use a shorter separator, a truncated entity_type, and a hash of the
      // field name.
      // Truncate to the same length for the current and revision tables.
      $entity_type = substr($entity_type_id, 0, 36);
      $field_hash = substr(hash('sha256', $real_key), 0, 10);
      $real_key = $entity_type . '__' . $field_hash;
    }
    return $real_key;
  }

909
  /**
910
   * Gets field foreign keys.
911 912 913 914 915 916 917 918 919 920 921 922
   *
   * @param string $field_name
   *   The name of the field.
   * @param array $field_schema
   *   The schema of the field.
   * @param string[] $column_mapping
   *   A mapping of field column names to database column names.
   *
   * @return array
   *   The schema definition for the foreign keys.
   */
  protected function getFieldForeignKeys($field_name, array $field_schema, array $column_mapping) {
923
    $foreign_keys = [];
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941

    foreach ($field_schema['foreign keys'] as $specifier => $specification) {
      // To avoid clashes with entity-level foreign keys we use
      // "{$entity_type_id}_field__" as a prefix instead of just
      // "{$entity_type_id}__". We additionally namespace the specifier by the
      // field name to avoid clashes when multiple fields of the same type are
      // added to an entity type.
      $entity_type_id = $this->entityType->id();
      $real_specifier = "{$entity_type_id}_field__{$field_name}__{$specifier}";
      $foreign_keys[$real_specifier]['table'] = $specification['table'];
      foreach ($specification['columns'] as $column => $referenced) {
        $foreign_keys[$real_specifier]['columns'][$column_mapping[$column]] = $referenced;
      }
    }

    return $foreign_keys;
  }

942 943 944 945 946 947 948 949 950 951
  /**
   * Loads stored schema data for the given entity type definition.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type definition.
   *
   * @return array
   *   The entity schema data array.
   */
  protected function loadEntitySchemaData(EntityTypeInterface $entity_type) {
952
    return $this->installedStorageSchema()->get($entity_type->id() . '.entity_schema_data', []);
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
  }

  /**
   * Stores schema data for the given entity type definition.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type definition.
   * @param array $schema
   *   The entity schema data array.
   */
  protected function saveEntitySchemaData(EntityTypeInterface $entity_type, $schema) {
    $data = $this->getEntitySchemaData($entity_type, $schema);
    $this->installedStorageSchema()->set($entity_type->id() . '.entity_schema_data', $data);
  }

  /**
   * Deletes schema data for the given entity type definition.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type definition.
   */
  protected function deleteEntitySchemaData(EntityTypeInterface $entity_type) {
    $this->installedStorageSchema()->delete($entity_type->id() . '.entity_schema_data');
  }

  /**
   * Loads stored schema data for the given field storage definition.
   *
   * @param \Drupal\Core\Field\FieldStorageDefinitionInterface $storage_definition
   *   The field storage definition.
   *
   * @return array
   *   The field schema data array.
   */
  protected function loadFieldSchemaData(FieldStorageDefinitionInterface $storage_definition) {
988
    return $this->installedStorageSchema()->get($storage_definition->getTargetEntityTypeId() . '.field_schema_data.' . $storage_definition->getName(), []);
989 990 991 992 993 994 995 996 997 998 999
  }

  /**
   * Stores schema data for the given field storage definition.
   *
   * @param \Drupal\Core\Field\FieldStorageDefinitionInterface $storage_definition
   *   The field storage definition.
   * @param array $schema
   *   The field schema data array.
   */
  protected function saveFieldSchemaData(FieldStorageDefinitionInterface $storage_definition, $schema) {
1000
    $this->processFieldStorageSchema($schema);
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
    $this->installedStorageSchema()->set($storage_definition->getTargetEntityTypeId() . '.field_schema_data.' . $storage_definition->getName(), $schema);
  }

  /**
   * Deletes schema data for the given field storage definition.
   *
   * @param \Drupal\Core\Field\FieldStorageDefinitionInterface $storage_definition
   *   The field storage definition.
   */
  protected function deleteFieldSchemaData(FieldStorageDefinitionInterface $storage_definition) {
    $this->installedStorageSchema()->delete($storage_definition->getTargetEntityTypeId() . '.field_schema_data.' . $storage_definition->getName());
  }

1014 1015 1016
  /**
   * Initializes common information for a base table.
   *
1017 1018 1019
   * @param \Drupal\Core\Entity\ContentEntityTypeInterface $entity_type
   *   The entity type.
   *
1020 1021 1022
   * @return array
   *   A partial schema array for the base table.
   */
1023 1024
  protected function initializeBaseTable(ContentEntityTypeInterface $entity_type) {
    $entity_type_id = $entity_type->id();
1025

1026
    $schema = [
1027
      'description' => "The base table for $entity_type_id entities.",
1028 1029 1030 1031
      'primary key' => [$entity_type->getKey('id')],
      'indexes' => [],
      'foreign keys' => [],
    ];
1032

1033 1034 1035
    if ($entity_type->hasKey('revision')) {
      $revision_key = $entity_type->getKey('revision');
      $key_name = $this->getEntityIndexName($entity_type, $revision_key);
1036 1037
      $schema['unique keys'][$key_name] = [$revision_key];
      $schema['foreign keys'][$entity_type_id . '__revision'] = [
1038
        'table' => $this->storage->getRevisionTable(),
1039 1040
        'columns' => [$revision_key => $revision_key],
      ];
1041 1042
    }

1043 1044
    $this->addTableDefaults($schema);

1045 1046 1047 1048 1049 1050
    return $schema;
  }

  /**
   * Initializes common information for a revision table.
   *
1051 1052 1053
   * @param \Drupal\Core\Entity\ContentEntityTypeInterface $entity_type
   *   The entity type.
   *
1054 1055 1056
   * @return array
   *   A partial schema array for the revision table.
   */
1057 1058 1059 1060
  protected function initializeRevisionTable(ContentEntityTypeInterface $entity_type) {
    $entity_type_id = $entity_type->id();
    $id_key = $entity_type->getKey('id');
    $revision_key = $entity_type->getKey('revision');
1061

1062
    $schema = [
1063
      'description' => "The revision table for $entity_type_id entities.",
1064 1065 1066 1067
      'primary key' => [$revision_key],
      'indexes' => [],
      'foreign keys' => [
        $entity_type_id . '__revisioned' => [
1068
          'table' => $this->storage->getBaseTable(),
1069 1070 1071 1072
          'columns' => [$id_key => $id_key],
        ],
      ],
    ];
1073

1074
    $schema['indexes'][$this->getEntityIndexName($entity_type, $id_key)] = [$id_key];
1075

1076 1077
    $this->addTableDefaults($schema);

1078 1079 1080 1081 1082 1083
    return $schema;
  }

  /**
   * Initializes common information for a data table.
   *
1084 1085 1086
   * @param \Drupal\Core\Entity\ContentEntityTypeInterface $entity_type
   *   The entity type.
   *
1087 1088 1089
   * @return array
   *   A partial schema array for the data table.
   */
1090 1091 1092
  protected function initializeDataTable(ContentEntityTypeInterface $entity_type) {
    $entity_type_id = $entity_type->id();
    $id_key = $entity_type->getKey('id');
1093

1094
    $schema = [
1095
      'description' => "The data table for $entity_type_id entities.",
1096 1097 1098 1099 1100 1101
      'primary key' => [$id_key, $entity_type->getKey('langcode')],
      'indexes' => [
        $entity_type_id . '__id__default_langcode__langcode' => [$id_key, $entity_type->getKey('default_langcode'), $entity_type->getKey('langcode')],
      ],
      'foreign keys' => [
        $entity_type_id => [
1102
          'table' => $this->storage->getBaseTable(),