SqlContentEntityStorage.php 61.1 KB
Newer Older
1 2
<?php

3
namespace Drupal\Core\Entity\Sql;
4

5
use Drupal\Core\Cache\CacheBackendInterface;
6
use Drupal\Core\Database\Connection;
7
use Drupal\Core\Database\Database;
8 9
use Drupal\Core\Database\DatabaseExceptionWrapper;
use Drupal\Core\Database\SchemaException;
10 11
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\ContentEntityStorageBase;
12
use Drupal\Core\Entity\EntityBundleListenerInterface;
13 14 15 16
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Entity\EntityTypeInterface;
17
use Drupal\Core\Entity\Query\QueryInterface;
18
use Drupal\Core\Entity\Schema\DynamicallyFieldableEntityStorageSchemaInterface;
19
use Drupal\Core\Field\FieldDefinitionInterface;
20
use Drupal\Core\Field\FieldStorageDefinitionInterface;
21
use Drupal\Core\Language\LanguageInterface;
22
use Drupal\Core\Language\LanguageManagerInterface;
23 24 25
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
26
 * A content entity database storage implementation.
27
 *
28
 * This class can be used as-is by most content entity types. Entity types
29
 * requiring special handling can extend the class.
30
 *
31
 * The class uses \Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema
32
 * internally in order to automatically generate the database schema based on
33 34
 * the defined base fields. Entity types can override the schema handler to
 * customize the generated schema; e.g., to add additional indexes.
35 36
 *
 * @ingroup entity_api
37
 */
38
class SqlContentEntityStorage extends ContentEntityStorageBase implements SqlEntityStorageInterface, DynamicallyFieldableEntityStorageSchemaInterface, EntityBundleListenerInterface {
39 40 41 42 43 44 45

  /**
   * The mapping of field columns to SQL tables.
   *
   * @var \Drupal\Core\Entity\Sql\TableMappingInterface
   */
  protected $tableMapping;
46 47 48 49 50 51 52 53 54 55

  /**
   * Name of entity's revision database table field, if it supports revisions.
   *
   * Has the value FALSE if this entity does not use revisions.
   *
   * @var string
   */
  protected $revisionKey = FALSE;

56 57 58 59 60 61 62
  /**
   * The entity langcode key.
   *
   * @var string|bool
   */
  protected $langcodeKey = FALSE;

63 64 65 66 67 68 69
  /**
   * The default language entity key.
   *
   * @var string
   */
  protected $defaultLangcodeKey = FALSE;

70 71 72 73 74 75 76
  /**
   * The base table of the entity.
   *
   * @var string
   */
  protected $baseTable;

77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
  /**
   * The table that stores revisions, if the entity supports revisions.
   *
   * @var string
   */
  protected $revisionTable;

  /**
   * The table that stores properties, if the entity has multilingual support.
   *
   * @var string
   */
  protected $dataTable;

  /**
   * The table that stores revision field data if the entity supports revisions.
   *
   * @var string
   */
  protected $revisionDataTable;

  /**
   * Active database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

105
  /**
106
   * The entity type's storage schema object.
107
   *
108
   * @var \Drupal\Core\Entity\Schema\EntityStorageSchemaInterface
109
   */
110
  protected $storageSchema;
111

112 113 114 115 116 117 118
  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

119 120 121 122 123 124 125
  /**
   * Whether this storage should use the temporary table mapping.
   *
   * @var bool
   */
  protected $temporary = FALSE;

126 127 128
  /**
   * {@inheritdoc}
   */
129
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
130
    return new static(
131
      $entity_type,
132
      $container->get('database'),
133
      $container->get('entity.manager'),
134 135
      $container->get('cache.entity'),
      $container->get('language_manager')
136 137 138
    );
  }

139 140 141 142 143 144 145 146 147 148 149
  /**
   * Gets the base field definitions for a content entity type.
   *
   * @return \Drupal\Core\Field\FieldDefinitionInterface[]
   *   The array of base field definitions for the entity type, keyed by field
   *   name.
   */
  public function getFieldStorageDefinitions() {
    return $this->entityManager->getBaseFieldDefinitions($this->entityTypeId);
  }

150
  /**
151
   * Constructs a SqlContentEntityStorage object.
152
   *
153 154
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type definition.
155 156
   * @param \Drupal\Core\Database\Connection $database
   *   The database connection to be used.
157 158
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager.
159
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache
160
   *   The cache backend to be used.
161 162
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager.
163
   */
164
  public function __construct(EntityTypeInterface $entity_type, Connection $database, EntityManagerInterface $entity_manager, CacheBackendInterface $cache, LanguageManagerInterface $language_manager) {
165
    parent::__construct($entity_type, $entity_manager, $cache);
166
    $this->database = $database;
167
    $this->languageManager = $language_manager;
168 169 170 171 172 173 174 175 176 177 178 179 180 181
    $this->initTableLayout();
  }

  /**
   * Initializes table name variables.
   */
  protected function initTableLayout() {
    // Reset table field values to ensure changes in the entity type definition
    // are correctly reflected in the table layout.
    $this->tableMapping = NULL;
    $this->revisionKey = NULL;
    $this->revisionTable = NULL;
    $this->dataTable = NULL;
    $this->revisionDataTable = NULL;
182 183

    // @todo Remove table names from the entity type definition in
184
    //   https://www.drupal.org/node/2232465.
185 186 187 188 189 190
    $this->baseTable = $this->entityType->getBaseTable() ?: $this->entityTypeId;
    $revisionable = $this->entityType->isRevisionable();
    if ($revisionable) {
      $this->revisionKey = $this->entityType->getKey('revision') ?: 'revision_id';
      $this->revisionTable = $this->entityType->getRevisionTable() ?: $this->entityTypeId . '_revision';
    }
191
    $translatable = $this->entityType->isTranslatable();
192 193
    if ($translatable) {
      $this->dataTable = $this->entityType->getDataTable() ?: $this->entityTypeId . '_field_data';
194
      $this->langcodeKey = $this->entityType->getKey('langcode');
195
      $this->defaultLangcodeKey = $this->entityType->getKey('default_langcode');
196 197 198 199 200 201 202
    }
    if ($revisionable && $translatable) {
      $this->revisionDataTable = $this->entityType->getRevisionDataTable() ?: $this->entityTypeId . '_field_revision';
    }
  }

  /**
203
   * Gets the base table name.
204 205 206 207 208 209 210 211 212
   *
   * @return string
   *   The table name.
   */
  public function getBaseTable() {
    return $this->baseTable;
  }

  /**
213
   * Gets the revision table name.
214 215 216 217 218 219 220 221 222
   *
   * @return string|false
   *   The table name or FALSE if it is not available.
   */
  public function getRevisionTable() {
    return $this->revisionTable;
  }

  /**
223
   * Gets the data table name.
224 225 226 227 228 229 230 231 232
   *
   * @return string|false
   *   The table name or FALSE if it is not available.
   */
  public function getDataTable() {
    return $this->dataTable;
  }

  /**
233
   * Gets the revision data table name.
234 235 236 237 238 239 240
   *
   * @return string|false
   *   The table name or FALSE if it is not available.
   */
  public function getRevisionDataTable() {
    return $this->revisionDataTable;
  }
241

242
  /**
243
   * Gets the entity type's storage schema object.
244
   *
245
   * @return \Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema
246
   *   The schema object.
247
   */
248 249 250 251
  protected function getStorageSchema() {
    if (!isset($this->storageSchema)) {
      $class = $this->entityType->getHandlerClass('storage_schema') ?: 'Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema';
      $this->storageSchema = new $class($this->entityManager, $this->entityType, $this, $this->database);
252
    }
253
    return $this->storageSchema;
254
  }
255

256
  /**
257 258 259 260 261
   * Updates the wrapped entity type definition.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The update entity type.
   *
262 263
   * @internal Only to be used internally by Entity API. Expected to be
   *   removed by https://www.drupal.org/node/2274017.
264
   */
265 266 267 268 269 270
  public function setEntityType(EntityTypeInterface $entity_type) {
    if ($this->entityType->id() == $entity_type->id()) {
      $this->entityType = $entity_type;
      $this->initTableLayout();
    }
    else {
271
      throw new EntityStorageException("Unsupported entity type {$entity_type->id()}");
272 273
    }
  }
274

275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
  /**
   * Sets the wrapped table mapping definition.
   *
   * @param \Drupal\Core\Entity\Sql\TableMappingInterface $table_mapping
   *   The table mapping.
   *
   * @internal Only to be used internally by Entity API. Expected to be removed
   *   by https://www.drupal.org/node/2554235.
   */
  public function setTableMapping(TableMappingInterface $table_mapping) {
    $this->tableMapping = $table_mapping;
  }

  /**
   * Changes the temporary state of the storage.
   *
   * @param bool $temporary
   *   Whether to use a temporary table mapping or not.
   *
   * @internal Only to be used internally by Entity API.
   */
  public function setTemporary($temporary) {
    $this->temporary = $temporary;
  }

300 301 302 303 304 305 306 307 308 309 310
  /**
   * {@inheritdoc}
   */
  public function getTableMapping(array $storage_definitions = NULL) {
    $table_mapping = $this->tableMapping;

    // If we are using our internal storage definitions, which is our main use
    // case, we can statically cache the computed table mapping. If a new set
    // of field storage definitions is passed, for instance when comparing old
    // and new storage schema, we compute the table mapping without caching.
    if (!isset($this->tableMapping) || $storage_definitions) {
311
      $table_mapping_class = $this->temporary ? TemporaryTableMapping::class : DefaultTableMapping::class;
312 313
      $definitions = $storage_definitions ?: $this->entityManager->getFieldStorageDefinitions($this->entityTypeId);

314 315
      /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping|\Drupal\Core\Entity\Sql\TemporaryTableMapping $table_mapping */
      $table_mapping = $table_mapping_class::create($this->entityType, $definitions);
316 317 318 319 320 321

      // Cache the computed table mapping only if we are using our internal
      // storage definitions.
      if (!$storage_definitions) {
        $this->tableMapping = $table_mapping;
      }
322
    }
323

324
    return $table_mapping;
325 326 327 328 329
  }

  /**
   * {@inheritdoc}
   */
330
  protected function doLoadMultiple(array $ids = NULL) {
331 332 333 334 335
    // Attempt to load entities from the persistent cache. This will remove IDs
    // that were loaded from $ids.
    $entities_from_cache = $this->getFromPersistentCache($ids);

    // Load any remaining entities from the database.
336 337 338 339
    if ($entities_from_storage = $this->getFromStorage($ids)) {
      $this->invokeStorageLoadHook($entities_from_storage);
      $this->setPersistentCache($entities_from_storage);
    }
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354

    return $entities_from_cache + $entities_from_storage;
  }

  /**
   * Gets entities from the storage.
   *
   * @param array|null $ids
   *   If not empty, return entities that match these IDs. Return all entities
   *   when NULL.
   *
   * @return \Drupal\Core\Entity\ContentEntityInterface[]
   *   Array of entities from the storage.
   */
  protected function getFromStorage(array $ids = NULL) {
355
    $entities = [];
356

357 358 359 360 361 362
    if (!empty($ids)) {
      // Sanitize IDs. Before feeding ID array into buildQuery, check whether
      // it is empty as this would load all entities.
      $ids = $this->cleanIds($ids);
    }

363 364 365 366 367 368 369 370 371 372 373 374 375 376
    if ($ids === NULL || $ids) {
      // Build and execute the query.
      $query_result = $this->buildQuery($ids)->execute();
      $records = $query_result->fetchAllAssoc($this->idKey);

      // Map the loaded records into entity objects and according fields.
      if ($records) {
        $entities = $this->mapFromStorageRecords($records);
      }
    }

    return $entities;
  }

377
  /**
378
   * Maps from storage records to entity objects, and attaches fields.
379
   *
380
   * @param array $records
381 382
   *   Associative array of query results, keyed on the entity ID or revision
   *   ID.
383
   * @param bool $load_from_revision
384 385
   *   (optional) Flag to indicate whether revisions should be loaded or not.
   *   Defaults to FALSE.
386 387 388 389
   *
   * @return array
   *   An array of entity objects implementing the EntityInterface.
   */
390
  protected function mapFromStorageRecords(array $records, $load_from_revision = FALSE) {
391
    if (!$records) {
392
      return [];
393 394
    }

395 396 397 398 399 400 401 402
    // Get the names of the fields that are stored in the base table and, if
    // applicable, the revision table. Other entity data will be loaded in
    // loadFromSharedTables() and loadFromDedicatedTables().
    $field_names = $this->tableMapping->getFieldNames($this->baseTable);
    if ($this->revisionTable) {
      $field_names = array_unique(array_merge($field_names, $this->tableMapping->getFieldNames($this->revisionTable)));
    }

403
    $values = [];
404
    foreach ($records as $id => $record) {
405
      $values[$id] = [];
406 407 408
      // Skip the item delta and item value levels (if possible) but let the
      // field assign the value as suiting. This avoids unnecessary array
      // hierarchies and saves memory here.
409 410 411 412 413 414 415 416 417 418
      foreach ($field_names as $field_name) {
        $field_columns = $this->tableMapping->getColumnNames($field_name);
        // Handle field types that store several properties.
        if (count($field_columns) > 1) {
          foreach ($field_columns as $property_name => $column_name) {
            if (property_exists($record, $column_name)) {
              $values[$id][$field_name][LanguageInterface::LANGCODE_DEFAULT][$property_name] = $record->{$column_name};
              unset($record->{$column_name});
            }
          }
419
        }
420
        // Handle field types that store only one property.
421
        else {
422 423 424 425 426
          $column_name = reset($field_columns);
          if (property_exists($record, $column_name)) {
            $values[$id][$field_name][LanguageInterface::LANGCODE_DEFAULT] = $record->{$column_name};
            unset($record->{$column_name});
          }
427
        }
428
      }
429 430 431 432 433 434

      // Handle additional record entries that are not provided by an entity
      // field, such as 'isDefaultRevision'.
      foreach ($record as $name => $value) {
        $values[$id][$name][LanguageInterface::LANGCODE_DEFAULT] = $value;
      }
435
    }
436

437
    // Initialize translations array.
438
    $translations = array_fill_keys(array_keys($values), []);
439 440

    // Load values from shared and dedicated tables.
441
    $this->loadFromSharedTables($values, $translations, $load_from_revision);
442 443
    $this->loadFromDedicatedTables($values, $load_from_revision);

444
    $entities = [];
445 446 447 448 449
    foreach ($values as $id => $entity_values) {
      $bundle = $this->bundleKey ? $entity_values[$this->bundleKey][LanguageInterface::LANGCODE_DEFAULT] : FALSE;
      // Turn the record into an entity class.
      $entities[$id] = new $this->entityClass($entity_values, $this->entityTypeId, $bundle, array_keys($translations[$id]));
    }
450

451 452 453 454
    return $entities;
  }

  /**
455
   * Loads values for fields stored in the shared data tables.
456
   *
457
   * @param array &$values
458 459
   *   Associative array of entities values, keyed on the entity ID or the
   *   revision ID.
460 461
   * @param array &$translations
   *   List of translations, keyed on the entity ID.
462 463
   * @param bool $load_from_revision
   *   Flag to indicate whether revisions should be loaded or not.
464
   */
465 466
  protected function loadFromSharedTables(array &$values, array &$translations, $load_from_revision) {
    $record_key = !$load_from_revision ? $this->idKey : $this->revisionKey;
467 468 469 470
    if ($this->dataTable) {
      // If a revision table is available, we need all the properties of the
      // latest revision. Otherwise we fall back to the data table.
      $table = $this->revisionDataTable ?: $this->dataTable;
471
      $alias = $this->revisionDataTable ? 'revision' : 'data';
472
      $query = $this->database->select($table, $alias, ['fetch' => \PDO::FETCH_ASSOC])
473
        ->fields($alias)
474 475
        ->condition($alias . '.' . $record_key, array_keys($values), 'IN')
        ->orderBy($alias . '.' . $record_key);
476

477
      $table_mapping = $this->getTableMapping();
478
      if ($this->revisionDataTable) {
479 480
        // Find revisioned fields that are not entity keys. Exclude the langcode
        // key as the base table holds only the default language.
481
        $base_fields = array_diff($table_mapping->getFieldNames($this->baseTable), [$this->langcodeKey]);
482
        $revisioned_fields = array_diff($table_mapping->getFieldNames($this->revisionDataTable), $base_fields);
483 484 485

        // Find fields that are not revisioned or entity keys. Data fields have
        // the same value regardless of entity revision.
486 487 488 489 490
        $data_fields = array_diff($table_mapping->getFieldNames($this->dataTable), $revisioned_fields, $base_fields);
        // If there are no data fields then only revisioned fields are needed
        // else both data fields and revisioned fields are needed to map the
        // entity values.
        $all_fields = $revisioned_fields;
491
        if ($data_fields) {
492
          $all_fields = array_merge($revisioned_fields, $data_fields);
493
          $query->leftJoin($this->dataTable, 'data', "(revision.$this->idKey = data.$this->idKey and revision.$this->langcodeKey = data.$this->langcodeKey)");
494 495 496 497 498 499 500 501 502 503 504
          $column_names = [];
          // Some fields can have more then one columns in the data table so
          // column names are needed.
          foreach ($data_fields as $data_field) {
            // \Drupal\Core\Entity\Sql\TableMappingInterface:: getColumNames()
            // returns an array keyed by property names so remove the keys
            // before array_merge() to avoid losing data with fields having the
            // same columns i.e. value.
            $column_names = array_merge($column_names, array_values($table_mapping->getColumnNames($data_field)));
          }
          $query->fields('data', $column_names);
505 506
        }

507
        // Get the revision IDs.
508
        $revision_ids = [];
509 510
        foreach ($values as $entity_values) {
          $revision_ids[] = $entity_values[$this->revisionKey][LanguageInterface::LANGCODE_DEFAULT];
511
        }
512
        $query->condition('revision.' . $this->revisionKey, $revision_ids, 'IN');
513 514
      }
      else {
515
        $all_fields = $table_mapping->getFieldNames($this->dataTable);
516 517
      }

518 519
      $result = $query->execute();
      foreach ($result as $row) {
520
        $id = $row[$record_key];
521 522

        // Field values in default language are stored with
523
        // LanguageInterface::LANGCODE_DEFAULT as key.
524 525
        $langcode = empty($row[$this->defaultLangcodeKey]) ? $row[$this->langcodeKey] : LanguageInterface::LANGCODE_DEFAULT;

526 527
        $translations[$id][$langcode] = TRUE;

528
        foreach ($all_fields as $field_name) {
529 530 531
          $columns = $table_mapping->getColumnNames($field_name);
          // Do not key single-column fields by property name.
          if (count($columns) == 1) {
532
            $values[$id][$field_name][$langcode] = $row[reset($columns)];
533 534
          }
          else {
535
            foreach ($columns as $property_name => $column_name) {
536
              $values[$id][$field_name][$langcode][$property_name] = $row[$column_name];
537
            }
538 539 540 541 542 543 544
          }
        }
      }
    }
  }

  /**
545
   * {@inheritdoc}
546
   */
547
  protected function doLoadRevisionFieldItems($revision_id) {
548
    @trigger_error('"\Drupal\Core\Entity\ContentEntityStorageBase::doLoadRevisionFieldItems()" is deprecated in Drupal 8.5.x and will be removed before Drupal 9.0.0. "\Drupal\Core\Entity\ContentEntityStorageBase::doLoadMultipleRevisionsFieldItems()" should be implemented instead. See https://www.drupal.org/node/2924915.', E_USER_DEPRECATED);
549

550 551 552 553 554 555 556 557 558 559
    $revisions = $this->doLoadMultipleRevisionsFieldItems([$revision_id]);

    return !empty($revisions) ? reset($revisions) : NULL;
  }

  /**
   * {@inheritdoc}
   */
  protected function doLoadMultipleRevisionsFieldItems($revision_ids) {
    $revisions = [];
560

561 562 563 564 565 566 567 568 569 570 571 572 573
    // Sanitize IDs. Before feeding ID array into buildQuery, check whether
    // it is empty as this would load all entity revisions.
    $revision_ids = $this->cleanIds($revision_ids, 'revision');

    if (!empty($revision_ids)) {
      // Build and execute the query.
      $query_result = $this->buildQuery(NULL, $revision_ids)->execute();
      $records = $query_result->fetchAllAssoc($this->revisionKey);

      // Map the loaded records into entity objects and according fields.
      if ($records) {
        $revisions = $this->mapFromStorageRecords($records, TRUE);
      }
574
    }
575

576
    return $revisions;
577 578 579
  }

  /**
580
   * {@inheritdoc}
581
   */
582 583 584 585
  protected function doDeleteRevisionFieldItems(ContentEntityInterface $revision) {
    $this->database->delete($this->revisionTable)
      ->condition($this->revisionKey, $revision->getRevisionId())
      ->execute();
586 587 588 589 590 591 592

    if ($this->revisionDataTable) {
      $this->database->delete($this->revisionDataTable)
        ->condition($this->revisionKey, $revision->getRevisionId())
        ->execute();
    }

593
    $this->deleteRevisionFromDedicatedTables($revision);
594 595 596
  }

  /**
597
   * {@inheritdoc}
598 599 600 601
   */
  protected function buildPropertyQuery(QueryInterface $entity_query, array $values) {
    if ($this->dataTable) {
      // @todo We should not be using a condition to specify whether conditions
602 603
      //   apply to the default language. See
      //   https://www.drupal.org/node/1866330.
604 605
      // Default to the original entity language if not explicitly specified
      // otherwise.
606 607
      if (!array_key_exists($this->defaultLangcodeKey, $values)) {
        $values[$this->defaultLangcodeKey] = 1;
608 609 610
      }
      // If the 'default_langcode' flag is explicitly not set, we do not care
      // whether the queried values are in the original entity language or not.
611 612
      elseif ($values[$this->defaultLangcodeKey] === NULL) {
        unset($values[$this->defaultLangcodeKey]);
613 614 615
      }
    }

616
    parent::buildPropertyQuery($entity_query, $values);
617 618 619 620 621 622 623 624 625 626 627
  }

  /**
   * Builds the query to load the entity.
   *
   * This has full revision support. For entities requiring special queries,
   * the class can be extended, and the default query can be constructed by
   * calling parent::buildQuery(). This is usually necessary when the object
   * being loaded needs to be augmented with additional data from another
   * table, such as loading node type into comments or vocabulary machine name
   * into terms, however it can also support $conditions on different tables.
628
   * See Drupal\comment\CommentStorage::buildQuery() for an example.
629 630 631
   *
   * @param array|null $ids
   *   An array of entity IDs, or NULL to load all entities.
632 633 634
   * @param array|bool $revision_ids
   *   The IDs of the revisions to load, or FALSE if this query is asking for
   *   the default revisions. Defaults to FALSE.
635
   *
636
   * @return \Drupal\Core\Database\Query\Select
637 638
   *   A SelectQuery object for loading the entity.
   */
639
  protected function buildQuery($ids, $revision_ids = FALSE) {
640
    $query = $this->database->select($this->entityType->getBaseTable(), 'base');
641

642
    $query->addTag($this->entityTypeId . '_load_multiple');
643

644 645 646 647 648
    if ($revision_ids) {
      if (!is_array($revision_ids)) {
        @trigger_error('Passing a single revision ID to "\Drupal\Core\Entity\Sql\SqlContentEntityStorage::buildQuery()" is deprecated in Drupal 8.5.x and will be removed before Drupal 9.0.0. An array of revision IDs should be given instead. See https://www.drupal.org/node/2924915.', E_USER_DEPRECATED);
      }
      $query->join($this->revisionTable, 'revision', "revision.{$this->idKey} = base.{$this->idKey} AND revision.{$this->revisionKey} IN (:revisionIds[])", [':revisionIds[]' => (array) $revision_ids]);
649 650 651 652 653 654
    }
    elseif ($this->revisionTable) {
      $query->join($this->revisionTable, 'revision', "revision.{$this->revisionKey} = base.{$this->revisionKey}");
    }

    // Add fields from the {entity} table.
655 656
    $table_mapping = $this->getTableMapping();
    $entity_fields = $table_mapping->getAllColumns($this->baseTable);
657 658 659

    if ($this->revisionTable) {
      // Add all fields from the {entity_revision} table.
660
      $entity_revision_fields = $table_mapping->getAllColumns($this->revisionTable);
661
      $entity_revision_fields = array_combine($entity_revision_fields, $entity_revision_fields);
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
      // The ID field is provided by entity, so remove it.
      unset($entity_revision_fields[$this->idKey]);

      // Remove all fields from the base table that are also fields by the same
      // name in the revision table.
      $entity_field_keys = array_flip($entity_fields);
      foreach ($entity_revision_fields as $name) {
        if (isset($entity_field_keys[$name])) {
          unset($entity_fields[$entity_field_keys[$name]]);
        }
      }
      $query->fields('revision', $entity_revision_fields);

      // Compare revision ID of the base and revision table, if equal then this
      // is the default revision.
677
      $query->addExpression('CASE base.' . $this->revisionKey . ' WHEN revision.' . $this->revisionKey . ' THEN 1 ELSE 0 END', 'isDefaultRevision');
678 679 680 681 682 683 684 685 686 687 688 689
    }

    $query->fields('base', $entity_fields);

    if ($ids) {
      $query->condition("base.{$this->idKey}", $ids, 'IN');
    }

    return $query;
  }

  /**
690
   * {@inheritdoc}
691 692 693 694 695 696 697 698 699
   */
  public function delete(array $entities) {
    if (!$entities) {
      // If no IDs or invalid IDs were passed, do nothing.
      return;
    }

    $transaction = $this->database->startTransaction();
    try {
700
      parent::delete($entities);
701

702 703
      // Ignore replica server temporarily.
      db_ignore_replica();
704 705
    }
    catch (\Exception $e) {
706
      $transaction->rollBack();
707
      watchdog_exception($this->entityTypeId, $e);
708 709 710 711 712 713 714
      throw new EntityStorageException($e->getMessage(), $e->getCode(), $e);
    }
  }

  /**
   * {@inheritdoc}
   */
715
  protected function doDeleteFieldItems($entities) {
716
    $ids = array_keys($entities);
717

718
    $this->database->delete($this->entityType->getBaseTable())
719
      ->condition($this->idKey, $ids, 'IN')
720
      ->execute();
721

722 723
    if ($this->revisionTable) {
      $this->database->delete($this->revisionTable)
724
        ->condition($this->idKey, $ids, 'IN')
725 726
        ->execute();
    }
727

728 729
    if ($this->dataTable) {
      $this->database->delete($this->dataTable)
730
        ->condition($this->idKey, $ids, 'IN')
731 732
        ->execute();
    }
733

734 735
    if ($this->revisionDataTable) {
      $this->database->delete($this->revisionDataTable)
736
        ->condition($this->idKey, $ids, 'IN')
737 738
        ->execute();
    }
739

740
    foreach ($entities as $entity) {
741
      $this->deleteFromDedicatedTables($entity);
742 743 744 745 746 747 748 749 750 751
    }
  }

  /**
   * {@inheritdoc}
   */
  public function save(EntityInterface $entity) {
    $transaction = $this->database->startTransaction();
    try {
      $return = parent::save($entity);
752

753 754
      // Ignore replica server temporarily.
      db_ignore_replica();
755 756 757
      return $return;
    }
    catch (\Exception $e) {
758
      $transaction->rollBack();
759
      watchdog_exception($this->entityTypeId, $e);
760 761 762 763
      throw new EntityStorageException($e->getMessage(), $e->getCode(), $e);
    }
  }

764 765 766
  /**
   * {@inheritdoc}
   */
767 768 769
  protected function doSaveFieldItems(ContentEntityInterface $entity, array $names = []) {
    $full_save = empty($names);
    $update = !$full_save || !$entity->isNew();
770

771 772 773
    if ($full_save) {
      $shared_table_fields = TRUE;
      $dedicated_table_fields = TRUE;
774 775
    }
    else {
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
      $table_mapping = $this->getTableMapping();
      $storage_definitions = $this->entityManager->getFieldStorageDefinitions($this->entityTypeId);
      $shared_table_fields = FALSE;
      $dedicated_table_fields = [];

      // Collect the name of fields to be written in dedicated tables and check
      // whether shared table records need to be updated.
      foreach ($names as $name) {
        $storage_definition = $storage_definitions[$name];
        if ($table_mapping->allowsSharedTableStorage($storage_definition)) {
          $shared_table_fields = TRUE;
        }
        elseif ($table_mapping->requiresDedicatedTableStorage($storage_definition)) {
          $dedicated_table_fields[] = $name;
        }
791
      }
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
    }

    // Update shared table records if necessary.
    if ($shared_table_fields) {
      $record = $this->mapToStorageRecord($entity->getUntranslated(), $this->baseTable);
      // Create the storage record to be saved.
      if ($update) {
        $default_revision = $entity->isDefaultRevision();
        if ($default_revision) {
          $this->database
            ->update($this->baseTable)
            ->fields((array) $record)
            ->condition($this->idKey, $record->{$this->idKey})
            ->execute();
        }
        if ($this->revisionTable) {
          if ($full_save) {
            $entity->{$this->revisionKey} = $this->saveRevision($entity);
          }
          else {
            $record = $this->mapToStorageRecord($entity->getUntranslated(), $this->revisionTable);
            $entity->preSaveRevision($this, $record);
            $this->database
              ->update($this->revisionTable)
              ->fields((array) $record)
              ->condition($this->revisionKey, $record->{$this->revisionKey})
              ->execute();
          }
        }
        if ($default_revision && $this->dataTable) {
          $this->saveToSharedTables($entity);
        }
        if ($this->revisionDataTable) {
          $new_revision = $full_save && $entity->isNewRevision();
          $this->saveToSharedTables($entity, $this->revisionDataTable, $new_revision);
        }
828
      }
829 830
      else {
        $insert_id = $this->database
831
          ->insert($this->baseTable, ['return' => Database::RETURN_INSERT_ID])
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
          ->fields((array) $record)
          ->execute();
        // Even if this is a new entity the ID key might have been set, in which
        // case we should not override the provided ID. An ID key that is not set
        // to any value is interpreted as NULL (or DEFAULT) and thus overridden.
        if (!isset($record->{$this->idKey})) {
          $record->{$this->idKey} = $insert_id;
        }
        $entity->{$this->idKey} = (string) $record->{$this->idKey};
        if ($this->revisionTable) {
          $record->{$this->revisionKey} = $this->saveRevision($entity);
        }
        if ($this->dataTable) {
          $this->saveToSharedTables($entity);
        }
        if ($this->revisionDataTable) {
          $this->saveToSharedTables($entity, $this->revisionDataTable);
        }
850 851 852
      }
    }

853 854 855 856
    // Update dedicated table records if necessary.
    if ($dedicated_table_fields) {
      $names = is_array($dedicated_table_fields) ? $dedicated_table_fields : [];
      $this->saveToDedicatedTables($entity, $update, $names);
857
    }
858 859 860 861 862 863 864 865 866
  }

  /**
   * {@inheritdoc}
   */
  protected function has($id, EntityInterface $entity) {
    return !$entity->isNew();
  }

867
  /**
868
   * Saves fields that use the shared tables.
869
   *
870
   * @param \Drupal\Core\Entity\ContentEntityInterface $entity
871
   *   The entity object.
872 873
   * @param string $table_name
   *   (optional) The table name to save to. Defaults to the data table.
874 875 876
   * @param bool $new_revision
   *   (optional) Whether we are dealing with a new revision. By default fetches
   *   the information from the entity object.
877
   */
878
  protected function saveToSharedTables(ContentEntityInterface $entity, $table_name = NULL, $new_revision = NULL) {
879 880 881
    if (!isset($table_name)) {
      $table_name = $this->dataTable;
    }
882 883 884
    if (!isset($new_revision)) {
      $new_revision = $entity->isNewRevision();
    }
885
    $revision = $table_name != $this->dataTable;
886

887
    if (!$revision || !$new_revision) {
888 889 890 891 892 893 894 895 896 897 898 899
      $key = $revision ? $this->revisionKey : $this->idKey;
      $value = $revision ? $entity->getRevisionId() : $entity->id();
      // Delete and insert to handle removed values.
      $this->database->delete($table_name)
        ->condition($key, $value)
        ->execute();
    }

    $query = $this->database->insert($table_name);

    foreach ($entity->getTranslationLanguages() as $langcode => $language) {
      $translation = $entity->getTranslation($langcode);
900
      $record = $this->mapToDataStorageRecord($translation, $table_name);
901 902 903 904 905 906 907 908 909 910 911 912
      $values = (array) $record;
      $query
        ->fields(array_keys($values))
        ->values($values);
    }

    $query->execute();
  }

  /**
   * Maps from an entity object to the storage record.
   *
913
   * @param \Drupal\Core\Entity\ContentEntityInterface $entity
914
   *   The entity object.
915 916
   * @param string $table_name
   *   (optional) The table name to map records to. Defaults to the base table.
917 918 919 920
   *
   * @return \stdClass
   *   The record to store.
   */
921 922 923 924 925
  protected function mapToStorageRecord(ContentEntityInterface $entity, $table_name = NULL) {
    if (!isset($table_name)) {
      $table_name = $this->baseTable;
    }

926
    $record = new \stdClass();
927 928
    $table_mapping = $this->getTableMapping();
    foreach ($table_mapping->getFieldNames($table_name) as $field_name) {
929

930
      if (empty($this->getFieldStorageDefinitions()[$field_name])) {
931
        throw new EntityStorageException("Table mapping contains invalid field $field_name.");
932
      }
933
      $definition = $this->getFieldStorageDefinitions()[$field_name];
934 935 936 937 938 939 940
      $columns = $table_mapping->getColumnNames($field_name);

      foreach ($columns as $column_name => $schema_name) {
        // If there is no main property and only a single column, get all
        // properties from the first field item and assume that they will be
        // stored serialized.
        // @todo Give field types more control over this behavior in
941
        //   https://www.drupal.org/node/2232427.
942
        if (!$definition->getMainPropertyName() && count($columns) == 1) {
943
          $value = ($item = $entity->$field_name->first()) ? $item->getValue() : [];
944
        }
945 946
        else {
          $value = isset($entity->$field_name->$column_name) ? $entity->$field_name->$column_name : NULL;
947
        }
948 949
        if (!empty($definition->getSchema()['columns'][$column_name]['serialize'])) {
          $value = serialize($value);
950
        }
951 952 953 954 955

        // Do not set serial fields if we do not have a value. This supports all
        // SQL database drivers.
        // @see https://www.drupal.org/node/2279395
        $value = drupal_schema_get_field_value($definition->getSchema()['columns'][$column_name], $value);
956
        if (!(empty($value) && $this->isColumnSerial($table_name, $schema_name))) {
957 958
          $record->$schema_name = $value;
        }
959 960 961 962 963 964
      }
    }

    return $record;
  }

965 966 967 968 969 970 971 972 973
  /**
   * Checks whether a field column should be treated as serial.
   *
   * @param $table_name
   *   The name of the table the field column belongs to.
   * @param $schema_name
   *   The schema name of the field column.
   *
   * @return bool
974
   *   TRUE if the column is serial, FALSE otherwise.
975
   *
976 977
   * @see \Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema::processBaseTable()
   * @see \Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema::processRevisionTable()
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
   */
  protected function isColumnSerial($table_name, $schema_name) {
    $result = FALSE;

    switch ($table_name) {
      case $this->baseTable:
        $result = $schema_name == $this->idKey;
        break;

      case $this->revisionTable:
        $result = $schema_name == $this->revisionKey;
        break;
    }

    return $result;
  }

995 996 997 998 999
  /**
   * Maps from an entity object to the storage record of the field data.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity object.
1000 1001
   * @param string $table_name
   *   (optional) The table name to map records to. Defaults to the data table.
1002 1003 1004 1005
   *
   * @return \stdClass
   *   The record to store.
   */
1006 1007 1008 1009 1010
  protected function mapToDataStorageRecord(EntityInterface $entity, $table_name = NULL) {
    if (!isset($table_name)) {
      $table_name = $this->dataTable;
    }
    $record = $this->mapToStorageRecord($entity, $table_name);
1011 1012 1013 1014 1015 1016
    return $record;
  }

  /**
   * Saves an entity revision.
   *
1017
   * @param \Drupal\Core\Entity\ContentEntityInterface $entity
1018 1019 1020 1021 1022
   *   The entity object.
   *
   * @return int
   *   The revision id.
   */
1023
  protected function saveRevision(ContentEntityInterface $entity) {
1024
    $record = $this->mapToStorageRecord($entity->getUntranslated(), $this->revisionTable);
1025 1026 1027 1028

    $entity->preSaveRevision($this, $record);

    if ($entity->isNewRevision()) {
1029
      $insert_id = $this->database
1030
        ->insert($this->revisionTable, ['return' => Database::RETURN_INSERT_ID])
1031 1032
        ->fields((array) $record)
        ->execute();
1033
      // Even if this is a new revision, the revision ID key might have been
1034 1035 1036 1037
      // set in which case we should not override the provided revision ID.
      if (!isset($record->{$this->revisionKey})) {
        $record->{$this->revisionKey} = $insert_id;
      }
1038
      if ($entity->isDefaultRevision()) {
1039
        $this->database->update($this->entityType->getBaseTable())
1040
          ->fields([$this->revisionKey => $record->{$this->revisionKey}])