SqlContentEntityStorage.php 62 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\field\FieldStorageConfigInterface;
23
use Drupal\Core\Language\LanguageManagerInterface;
24 25 26
use Symfony\Component\DependencyInjection\ContainerInterface;

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

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

  /**
   * 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;

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

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

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

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 105
  /**
   * 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;

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

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

120 121 122
  /**
   * {@inheritdoc}
   */
123
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
124
    return new static(
125
      $entity_type,
126
      $container->get('database'),
127
      $container->get('entity.manager'),
128 129
      $container->get('cache.entity'),
      $container->get('language_manager')
130 131 132
    );
  }

133 134 135 136 137 138 139 140 141 142 143
  /**
   * 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);
  }

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

    // @todo Remove table names from the entity type definition in
178
    //   https://www.drupal.org/node/2232465.
179 180 181 182 183 184
    $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';
    }
185
    $translatable = $this->entityType->isTranslatable();
186 187
    if ($translatable) {
      $this->dataTable = $this->entityType->getDataTable() ?: $this->entityTypeId . '_field_data';
188
      $this->langcodeKey = $this->entityType->getKey('langcode');
189
      $this->defaultLangcodeKey = $this->entityType->getKey('default_langcode');
190 191 192 193 194 195 196
    }
    if ($revisionable && $translatable) {
      $this->revisionDataTable = $this->entityType->getRevisionDataTable() ?: $this->entityTypeId . '_field_revision';
    }
  }

  /**
197
   * Gets the base table name.
198 199 200 201 202 203 204 205 206
   *
   * @return string
   *   The table name.
   */
  public function getBaseTable() {
    return $this->baseTable;
  }

  /**
207
   * Gets the revision table name.
208 209 210 211 212 213 214 215 216
   *
   * @return string|false
   *   The table name or FALSE if it is not available.
   */
  public function getRevisionTable() {
    return $this->revisionTable;
  }

  /**
217
   * Gets the data table name.
218 219 220 221 222 223 224 225 226
   *
   * @return string|false
   *   The table name or FALSE if it is not available.
   */
  public function getDataTable() {
    return $this->dataTable;
  }

  /**
227
   * Gets the revision data table name.
228 229 230 231 232 233 234
   *
   * @return string|false
   *   The table name or FALSE if it is not available.
   */
  public function getRevisionDataTable() {
    return $this->revisionDataTable;
  }
235

236
  /**
237
   * Gets the entity type's storage schema object.
238
   *
239
   * @return \Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema
240
   *   The schema object.
241
   */
242 243 244 245
  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);
246
    }
247
    return $this->storageSchema;
248
  }
249

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

269 270 271 272 273 274 275 276 277 278 279 280 281 282
  /**
   * {@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.
    // @todo Clean-up this in https://www.drupal.org/node/2274017 so we can
    //   easily instantiate a new table mapping whenever needed.
    if (!isset($this->tableMapping) || $storage_definitions) {
      $definitions = $storage_definitions ?: $this->entityManager->getFieldStorageDefinitions($this->entityTypeId);
283
      $table_mapping = new DefaultTableMapping($this->entityType, $definitions);
284

285
      $shared_table_definitions = array_filter($definitions, function (FieldStorageDefinitionInterface $definition) use ($table_mapping) {
286
        return $table_mapping->allowsSharedTableStorage($definition);
287 288 289
      });

      $key_fields = array_values(array_filter(array($this->idKey, $this->revisionKey, $this->bundleKey, $this->uuidKey, $this->langcodeKey)));
290 291
      $all_fields = array_keys($shared_table_definitions);
      $revisionable_fields = array_keys(array_filter($shared_table_definitions, function (FieldStorageDefinitionInterface $definition) {
292 293 294 295 296 297 298 299
        return $definition->isRevisionable();
      }));
      // Make sure the key fields come first in the list of fields.
      $all_fields = array_merge($key_fields, array_diff($all_fields, $key_fields));

      // Nodes have all three of these fields, while custom blocks only have
      // log.
      // @todo Provide automatic definitions for revision metadata fields in
300
      //   https://www.drupal.org/node/2248983.
301 302 303 304 305
      $revision_metadata_fields = array_intersect(array(
        'revision_timestamp',
        'revision_uid',
        'revision_log',
      ), $all_fields);
306 307

      $revisionable = $this->entityType->isRevisionable();
308
      $translatable = $this->entityType->isTranslatable();
309 310
      if (!$revisionable && !$translatable) {
        // The base layout stores all the base field values in the base table.
311
        $table_mapping->setFieldNames($this->baseTable, $all_fields);
312 313 314 315 316 317
      }
      elseif ($revisionable && !$translatable) {
        // The revisionable layout stores all the base field values in the base
        // table, except for revision metadata fields. Revisionable fields
        // denormalized in the base table but also stored in the revision table
        // together with the entity ID and the revision ID as identifiers.
318
        $table_mapping->setFieldNames($this->baseTable, array_diff($all_fields, $revision_metadata_fields));
319
        $revision_key_fields = array($this->idKey, $this->revisionKey);
320
        $table_mapping->setFieldNames($this->revisionTable, array_merge($revision_key_fields, $revisionable_fields));
321 322 323 324 325 326 327 328
      }
      elseif (!$revisionable && $translatable) {
        // Multilingual layouts store key field values in the base table. The
        // other base field values are stored in the data table, no matter
        // whether they are translatable or not. The data table holds also a
        // denormalized copy of the bundle field value to allow for more
        // performant queries. This means that only the UUID is not stored on
        // the data table.
329
        $table_mapping
330
          ->setFieldNames($this->baseTable, $key_fields)
331
          ->setFieldNames($this->dataTable, array_values(array_diff($all_fields, array($this->uuidKey))));
332 333 334 335 336 337 338 339 340
      }
      elseif ($revisionable && $translatable) {
        // The revisionable multilingual layout stores key field values in the
        // base table, except for language, which is stored in the revision
        // table along with revision metadata. The revision data table holds
        // data field values for all the revisionable fields and the data table
        // holds the data field values for all non-revisionable fields. The data
        // field values of revisionable fields are denormalized in the data
        // table, as well.
341
        $table_mapping->setFieldNames($this->baseTable, array_values($key_fields));
342 343 344 345 346

        // Like in the multilingual, non-revisionable case the UUID is not
        // in the data table. Additionally, do not store revision metadata
        // fields in the data table.
        $data_fields = array_values(array_diff($all_fields, array($this->uuidKey), $revision_metadata_fields));
347
        $table_mapping->setFieldNames($this->dataTable, $data_fields);
348 349

        $revision_base_fields = array_merge(array($this->idKey, $this->revisionKey, $this->langcodeKey), $revision_metadata_fields);
350
        $table_mapping->setFieldNames($this->revisionTable, $revision_base_fields);
351 352

        $revision_data_key_fields = array($this->idKey, $this->revisionKey, $this->langcodeKey);
353
        $revision_data_fields = array_diff($revisionable_fields, $revision_metadata_fields, array($this->langcodeKey));
354
        $table_mapping->setFieldNames($this->revisionDataTable, array_merge($revision_data_key_fields, $revision_data_fields));
355
      }
356 357

      // Add dedicated tables.
358
      $dedicated_table_definitions = array_filter($definitions, function (FieldStorageDefinitionInterface $definition) use ($table_mapping) {
359 360 361 362 363 364 365 366 367 368
        return $table_mapping->requiresDedicatedTableStorage($definition);
      });
      $extra_columns = array(
        'bundle',
        'deleted',
        'entity_id',
        'revision_id',
        'langcode',
        'delta',
      );
369 370 371 372 373 374
      foreach ($dedicated_table_definitions as $field_name => $definition) {
        $tables = [$table_mapping->getDedicatedDataTableName($definition)];
        if ($revisionable && $definition->isRevisionable()) {
          $tables[] = $table_mapping->getDedicatedRevisionTableName($definition);
        }
        foreach ($tables as $table_name) {
375 376 377 378 379 380 381 382 383 384
          $table_mapping->setFieldNames($table_name, array($field_name));
          $table_mapping->setExtraColumns($table_name, $extra_columns);
        }
      }

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

387
    return $table_mapping;
388 389 390 391 392
  }

  /**
   * {@inheritdoc}
   */
393
  protected function doLoadMultiple(array $ids = NULL) {
394 395 396 397 398
    // 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.
399 400 401 402
    if ($entities_from_storage = $this->getFromStorage($ids)) {
      $this->invokeStorageLoadHook($entities_from_storage);
      $this->setPersistentCache($entities_from_storage);
    }
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419

    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) {
    $entities = array();

420 421 422 423 424 425
    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);
    }

426 427 428 429 430 431 432 433 434 435 436 437 438 439
    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;
  }

440
  /**
441
   * Maps from storage records to entity objects, and attaches fields.
442
   *
443 444
   * @param array $records
   *   Associative array of query results, keyed on the entity ID.
445 446
   * @param bool $load_from_revision
   *   Flag to indicate whether revisions should be loaded or not.
447 448 449 450
   *
   * @return array
   *   An array of entity objects implementing the EntityInterface.
   */
451
  protected function mapFromStorageRecords(array $records, $load_from_revision = FALSE) {
452 453 454 455
    if (!$records) {
      return array();
    }

456
    $values = array();
457
    foreach ($records as $id => $record) {
458
      $values[$id] = array();
459 460 461
      // 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.
462
      foreach ($record as $name => $value) {
463 464 465 466
        // Handle columns named [field_name]__[column_name] (e.g for field types
        // that store several properties).
        if ($field_name = strstr($name, '__', TRUE)) {
          $property_name = substr($name, strpos($name, '__') + 2);
467
          $values[$id][$field_name][LanguageInterface::LANGCODE_DEFAULT][$property_name] = $value;
468 469 470 471
        }
        else {
          // Handle columns named directly after the field (e.g if the field
          // type only stores one property).
472
          $values[$id][$name][LanguageInterface::LANGCODE_DEFAULT] = $value;
473
        }
474 475
      }
    }
476

477 478 479 480 481 482 483 484 485 486 487 488 489
    // Initialize translations array.
    $translations = array_fill_keys(array_keys($values), array());

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

    $entities = array();
    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]));
    }
490

491 492 493 494
    return $entities;
  }

  /**
495
   * Loads values for fields stored in the shared data tables.
496
   *
497 498 499 500
   * @param array &$values
   *   Associative array of entities values, keyed on the entity ID.
   * @param array &$translations
   *   List of translations, keyed on the entity ID.
501
   */
502
  protected function loadFromSharedTables(array &$values, array &$translations) {
503 504 505 506
    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;
507 508 509
      $alias = $this->revisionDataTable ? 'revision' : 'data';
      $query = $this->database->select($table, $alias, array('fetch' => \PDO::FETCH_ASSOC))
        ->fields($alias)
510
        ->condition($alias . '.' . $this->idKey, array_keys($values), 'IN')
511
        ->orderBy($alias . '.' . $this->idKey);
512

513
      $table_mapping = $this->getTableMapping();
514
      if ($this->revisionDataTable) {
515 516 517 518
        // Find revisioned fields that are not entity keys. Exclude the langcode
        // key as the base table holds only the default language.
        $base_fields = array_diff($table_mapping->getFieldNames($this->baseTable), array($this->langcodeKey));
        $fields = array_diff($table_mapping->getFieldNames($this->revisionDataTable), $base_fields);
519 520 521

        // Find fields that are not revisioned or entity keys. Data fields have
        // the same value regardless of entity revision.
522
        $data_fields = array_diff($table_mapping->getFieldNames($this->dataTable), $fields, $base_fields);
523 524 525 526 527 528
        if ($data_fields) {
          $fields = array_merge($fields, $data_fields);
          $query->leftJoin($this->dataTable, 'data', "(revision.$this->idKey = data.$this->idKey)");
          $query->fields('data', $data_fields);
        }

529 530
        // Get the revision IDs.
        $revision_ids = array();
531 532
        foreach ($values as $entity_values) {
          $revision_ids[] = $entity_values[$this->revisionKey][LanguageInterface::LANGCODE_DEFAULT];
533
        }
534
        $query->condition('revision.' . $this->revisionKey, $revision_ids, 'IN');
535 536
      }
      else {
537
        $fields = $table_mapping->getFieldNames($this->dataTable);
538 539
      }

540 541 542
      $result = $query->execute();
      foreach ($result as $row) {
        $id = $row[$this->idKey];
543 544

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

548 549
        $translations[$id][$langcode] = TRUE;

550
        foreach ($fields as $field_name) {
551 552 553
          $columns = $table_mapping->getColumnNames($field_name);
          // Do not key single-column fields by property name.
          if (count($columns) == 1) {
554
            $values[$id][$field_name][$langcode] = $row[reset($columns)];
555 556
          }
          else {
557
            foreach ($columns as $property_name => $column_name) {
558
              $values[$id][$field_name][$langcode][$property_name] = $row[$column_name];
559
            }
560 561 562 563 564 565 566
          }
        }
      }
    }
  }

  /**
567
   * {@inheritdoc}
568
   */
569 570 571
  protected function doLoadRevisionFieldItems($revision_id) {
    $revision = NULL;

572 573
    // Build and execute the query.
    $query_result = $this->buildQuery(array(), $revision_id)->execute();
574
    $records = $query_result->fetchAllAssoc($this->idKey);
575

576 577
    if (!empty($records)) {
      // Convert the raw records to entity objects.
578
      $entities = $this->mapFromStorageRecords($records, TRUE);
579
      $revision = reset($entities) ?: NULL;
580
    }
581 582

    return $revision;
583 584 585
  }

  /**
586
   * {@inheritdoc}
587
   */
588 589 590 591 592
  protected function doDeleteRevisionFieldItems(ContentEntityInterface $revision) {
    $this->database->delete($this->revisionTable)
      ->condition($this->revisionKey, $revision->getRevisionId())
      ->execute();
    $this->deleteRevisionFromDedicatedTables($revision);
593 594 595
  }

  /**
596
   * {@inheritdoc}
597 598 599 600
   */
  protected function buildPropertyQuery(QueryInterface $entity_query, array $values) {
    if ($this->dataTable) {
      // @todo We should not be using a condition to specify whether conditions
601 602
      //   apply to the default language. See
      //   https://www.drupal.org/node/1866330.
603 604
      // Default to the original entity language if not explicitly specified
      // otherwise.
605 606
      if (!array_key_exists($this->defaultLangcodeKey, $values)) {
        $values[$this->defaultLangcodeKey] = 1;
607 608 609
      }
      // 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.
610 611
      elseif ($values[$this->defaultLangcodeKey] === NULL) {
        unset($values[$this->defaultLangcodeKey]);
612 613 614
      }
    }

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

  /**
   * 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.
627
   * See Drupal\comment\CommentStorage::buildQuery() for an example.
628 629 630 631 632 633 634
   *
   * @param array|null $ids
   *   An array of entity IDs, or NULL to load all entities.
   * @param $revision_id
   *   The ID of the revision to load, or FALSE if this query is asking for the
   *   most current revision(s).
   *
635
   * @return \Drupal\Core\Database\Query\Select
636 637 638
   *   A SelectQuery object for loading the entity.
   */
  protected function buildQuery($ids, $revision_id = FALSE) {
639
    $query = $this->database->select($this->entityType->getBaseTable(), 'base');
640

641
    $query->addTag($this->entityTypeId . '_load_multiple');
642 643 644 645 646 647 648 649 650

    if ($revision_id) {
      $query->join($this->revisionTable, 'revision', "revision.{$this->idKey} = base.{$this->idKey} AND revision.{$this->revisionKey} = :revisionId", array(':revisionId' => $revision_id));
    }
    elseif ($this->revisionTable) {
      $query->join($this->revisionTable, 'revision', "revision.{$this->revisionKey} = base.{$this->revisionKey}");
    }

    // Add fields from the {entity} table.
651 652
    $table_mapping = $this->getTableMapping();
    $entity_fields = $table_mapping->getAllColumns($this->baseTable);
653 654 655

    if ($this->revisionTable) {
      // Add all fields from the {entity_revision} table.
656
      $entity_revision_fields = $table_mapping->getAllColumns($this->revisionTable);
657
      $entity_revision_fields = array_combine($entity_revision_fields, $entity_revision_fields);
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
      // 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.
673
      $query->addExpression('CASE base.' . $this->revisionKey . ' WHEN revision.' . $this->revisionKey . ' THEN 1 ELSE 0 END', 'isDefaultRevision');
674 675 676 677 678 679 680 681 682 683 684 685
    }

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

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

    return $query;
  }

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

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

698 699
      // Ignore replica server temporarily.
      db_ignore_replica();
700 701 702
    }
    catch (\Exception $e) {
      $transaction->rollback();
703
      watchdog_exception($this->entityTypeId, $e);
704 705 706 707 708 709 710
      throw new EntityStorageException($e->getMessage(), $e->getCode(), $e);
    }
  }

  /**
   * {@inheritdoc}
   */
711
  protected function doDeleteFieldItems($entities) {
712
    $ids = array_keys($entities);
713

714
    $this->database->delete($this->entityType->getBaseTable())
715
      ->condition($this->idKey, $ids, 'IN')
716
      ->execute();
717

718 719
    if ($this->revisionTable) {
      $this->database->delete($this->revisionTable)
720
        ->condition($this->idKey, $ids, 'IN')
721 722
        ->execute();
    }
723

724 725
    if ($this->dataTable) {
      $this->database->delete($this->dataTable)
726
        ->condition($this->idKey, $ids, 'IN')
727 728
        ->execute();
    }
729

730 731
    if ($this->revisionDataTable) {
      $this->database->delete($this->revisionDataTable)
732
        ->condition($this->idKey, $ids, 'IN')
733 734
        ->execute();
    }
735

736
    foreach ($entities as $entity) {
737
      $this->deleteFromDedicatedTables($entity);
738 739 740 741 742 743 744 745 746 747
    }
  }

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

749 750
      // Ignore replica server temporarily.
      db_ignore_replica();
751 752 753 754
      return $return;
    }
    catch (\Exception $e) {
      $transaction->rollback();
755
      watchdog_exception($this->entityTypeId, $e);
756 757 758 759
      throw new EntityStorageException($e->getMessage(), $e->getCode(), $e);
    }
  }

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

767 768 769
    if ($full_save) {
      $shared_table_fields = TRUE;
      $dedicated_table_fields = TRUE;
770 771
    }
    else {
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
      $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;
        }
787
      }
788 789 790 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
    }

    // 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);
        }
824
      }
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
      else {
        $insert_id = $this->database
          ->insert($this->baseTable, array('return' => Database::RETURN_INSERT_ID))
          ->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);
        }
846 847 848
      }
    }

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

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

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

883
    if (!$revision || !$new_revision) {
884 885 886 887 888 889 890 891 892 893 894 895
      $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);
896
      $record = $this->mapToDataStorageRecord($translation, $table_name);
897 898 899 900 901 902 903 904 905 906 907 908
      $values = (array) $record;
      $query
        ->fields(array_keys($values))
        ->values($values);
    }

    $query->execute();
  }

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

922
    $record = new \stdClass();
923 924
    $table_mapping = $this->getTableMapping();
    foreach ($table_mapping->getFieldNames($table_name) as $field_name) {
925

926
      if (empty($this->getFieldStorageDefinitions()[$field_name])) {
927
        throw new EntityStorageException("Table mapping contains invalid field $field_name.");
928
      }
929
      $definition = $this->getFieldStorageDefinitions()[$field_name];
930 931 932 933 934 935 936
      $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
937
        //   https://www.drupal.org/node/2232427.
938
        if (!$definition->getMainPropertyName() && count($columns) == 1) {
939
          $value = ($item = $entity->$field_name->first()) ? $item->getValue() : array();
940
        }
941 942
        else {
          $value = isset($entity->$field_name->$column_name) ? $entity->$field_name->$column_name : NULL;
943
        }
944 945
        if (!empty($definition->getSchema()['columns'][$column_name]['serialize'])) {
          $value = serialize($value);
946
        }
947 948 949 950 951

        // 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);
952
        if (!(empty($value) && $this->isColumnSerial($table_name, $schema_name))) {
953 954
          $record->$schema_name = $value;
        }
955 956 957 958 959 960
      }
    }

    return $record;
  }

961 962 963 964 965 966 967 968 969
  /**
   * 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
970
   *   TRUE if the column is serial, FALSE otherwise.
971
   *
972 973
   * @see \Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema::processBaseTable()
   * @see \Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema::processRevisionTable()
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
   */
  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;
  }

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

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

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

    if ($entity->isNewRevision()) {
1025 1026 1027 1028
      $insert_id = $this->database
        ->insert($this->revisionTable, array('return' => Database::RETURN_INSERT_ID))
        ->fields((array) $record)
        ->execute();
1029
      // Even if this is a new revision, the revision ID key might have been
1030 1031 1032 1033
      // set in which case we should not override the provided revision ID.
      if (!isset($record->{$this->revisionKey})) {
        $record->{$this->revisionKey} = $insert_id;
      }
1034
      if ($entity->isDefaultRevision()) {
1035
        $this->database->update($this->entityType->getBaseTable())
1036 1037 1038 1039 1040 1041
          ->fields(array($this->revisionKey => $record->{$this->revisionKey}))
          ->condition($this->idKey, $record->{$this->idKey})
          ->execute();
      }
    }
    else {
1042 1043 1044 1045 1046
      $this->database
        ->update($this->revisionTable)
        ->fields((array) $record)
        ->condition($this->revisionKey, $record->{$this->revisionKey})
        ->execute();
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
    }

    // Make sure to update the new revision key for the entity.
    $entity->{$this->revisionKey}->value = $record->{$this->revisionKey};

    return $record->{$this->revisionKey};
  }

  /**
   * {@inheritdoc}
   */