SqlContentEntityStorage.php 65.6 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\Core\Entity\Sql\SqlContentEntityStorage.
6 7
 */

8
namespace Drupal\Core\Entity\Sql;
9

10
use Drupal\Component\Utility\SafeMarkup;
11
use Drupal\Core\Cache\Cache;
12
use Drupal\Core\Cache\CacheBackendInterface;
13
use Drupal\Core\Database\Connection;
14
use Drupal\Core\Database\Database;
15 16
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\ContentEntityStorageBase;
17
use Drupal\Core\Entity\EntityBundleListenerInterface;
18 19 20 21
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Entity\EntityTypeInterface;
22
use Drupal\Core\Entity\Query\QueryInterface;
23
use Drupal\Core\Entity\Schema\DynamicallyFieldableEntityStorageSchemaInterface;
24
use Drupal\Core\Field\FieldDefinitionInterface;
25
use Drupal\Core\Field\FieldItemListInterface;
26
use Drupal\Core\Field\FieldStorageDefinitionInterface;
27
use Drupal\Core\Language\LanguageInterface;
28
use Drupal\field\FieldStorageConfigInterface;
29
use Drupal\Core\Language\LanguageManagerInterface;
30 31 32
use Symfony\Component\DependencyInjection\ContainerInterface;

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

  /**
   * The mapping of field columns to SQL tables.
   *
   * @var \Drupal\Core\Entity\Sql\TableMappingInterface
   */
  protected $tableMapping;
53 54 55 56 57 58 59 60 61 62

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

63 64 65 66 67 68 69
  /**
   * The entity langcode key.
   *
   * @var string|bool
   */
  protected $langcodeKey = FALSE;

70 71 72 73 74 75 76
  /**
   * The default language entity key.
   *
   * @var string
   */
  protected $defaultLangcodeKey = FALSE;

77 78 79 80 81 82 83
  /**
   * The base table of the entity.
   *
   * @var string
   */
  protected $baseTable;

84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
  /**
   * 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;

  /**
113
   * The entity manager.
114
   *
115
   * @var \Drupal\Core\Entity\EntityManagerInterface
116
   */
117
  protected $entityManager;
118

119
  /**
120
   * The entity type's storage schema object.
121
   *
122
   * @var \Drupal\Core\Entity\Schema\EntityStorageSchemaInterface
123
   */
124
  protected $storageSchema;
125

126 127 128 129 130 131 132
  /**
   * Cache backend.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface
   */
  protected $cacheBackend;

133 134 135 136 137 138 139
  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

140 141 142
  /**
   * {@inheritdoc}
   */
143
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
144
    return new static(
145
      $entity_type,
146
      $container->get('database'),
147
      $container->get('entity.manager'),
148 149
      $container->get('cache.entity'),
      $container->get('language_manager')
150 151 152
    );
  }

153 154 155 156 157 158 159 160 161 162 163
  /**
   * 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);
  }

164
  /**
165
   * Constructs a SqlContentEntityStorage object.
166
   *
167 168
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type definition.
169 170
   * @param \Drupal\Core\Database\Connection $database
   *   The database connection to be used.
171 172
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager.
173 174
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
   *   The cache backend to be used.
175 176
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager.
177
   */
178
  public function __construct(EntityTypeInterface $entity_type, Connection $database, EntityManagerInterface $entity_manager, CacheBackendInterface $cache, LanguageManagerInterface $language_manager) {
179
    parent::__construct($entity_type);
180
    $this->database = $database;
181
    $this->entityManager = $entity_manager;
182
    $this->cacheBackend = $cache;
183
    $this->languageManager = $language_manager;
184 185 186 187 188 189 190 191 192 193 194 195 196 197
    $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;
198 199 200 201 202 203 204 205 206

    // @todo Remove table names from the entity type definition in
    //   https://drupal.org/node/2232465
    $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';
    }
207
    $translatable = $this->entityType->isTranslatable();
208 209
    if ($translatable) {
      $this->dataTable = $this->entityType->getDataTable() ?: $this->entityTypeId . '_field_data';
210
      $this->langcodeKey = $this->entityType->getKey('langcode');
211
      $this->defaultLangcodeKey = $this->entityType->getKey('default_langcode');
212 213 214 215 216 217 218
    }
    if ($revisionable && $translatable) {
      $this->revisionDataTable = $this->entityType->getRevisionDataTable() ?: $this->entityTypeId . '_field_revision';
    }
  }

  /**
219
   * Gets the base table name.
220 221 222 223 224 225 226 227 228
   *
   * @return string
   *   The table name.
   */
  public function getBaseTable() {
    return $this->baseTable;
  }

  /**
229
   * Gets the revision table name.
230 231 232 233 234 235 236 237 238
   *
   * @return string|false
   *   The table name or FALSE if it is not available.
   */
  public function getRevisionTable() {
    return $this->revisionTable;
  }

  /**
239
   * Gets the data table name.
240 241 242 243 244 245 246 247 248
   *
   * @return string|false
   *   The table name or FALSE if it is not available.
   */
  public function getDataTable() {
    return $this->dataTable;
  }

  /**
249
   * Gets the revision data table name.
250 251 252 253 254 255 256
   *
   * @return string|false
   *   The table name or FALSE if it is not available.
   */
  public function getRevisionDataTable() {
    return $this->revisionDataTable;
  }
257

258
  /**
259
   * Gets the entity type's storage schema object.
260
   *
261
   * @return \Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema
262
   *   The schema object.
263
   */
264 265 266 267
  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);
268
    }
269
    return $this->storageSchema;
270
  }
271

272
  /**
273 274 275 276 277 278 279
   * Updates the wrapped entity type definition.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The update entity type.
   *
   * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0.
   *   See https://www.drupal.org/node/2274017.
280
   */
281 282 283 284 285 286
  public function setEntityType(EntityTypeInterface $entity_type) {
    if ($this->entityType->id() == $entity_type->id()) {
      $this->entityType = $entity_type;
      $this->initTableLayout();
    }
    else {
287
      throw new EntityStorageException(SafeMarkup::format('Unsupported entity type @id', array('@id' => $entity_type->id())));
288 289
    }
  }
290

291 292 293 294 295 296 297 298 299 300 301 302 303 304
  /**
   * {@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);
305
      $table_mapping = new DefaultTableMapping($this->entityType, $definitions);
306 307 308

      $definitions = array_filter($definitions, function (FieldStorageDefinitionInterface $definition) use ($table_mapping) {
        return $table_mapping->allowsSharedTableStorage($definition);
309 310 311 312 313 314 315 316 317 318 319 320 321 322
      });

      $key_fields = array_values(array_filter(array($this->idKey, $this->revisionKey, $this->bundleKey, $this->uuidKey, $this->langcodeKey)));
      $all_fields = array_keys($definitions);
      $revisionable_fields = array_keys(array_filter($definitions, function (FieldStorageDefinitionInterface $definition) {
        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
      //   https://drupal.org/node/2248983.
323 324 325 326 327
      $revision_metadata_fields = array_intersect(array(
        'revision_timestamp',
        'revision_uid',
        'revision_log',
      ), $all_fields);
328 329

      $revisionable = $this->entityType->isRevisionable();
330
      $translatable = $this->entityType->isTranslatable();
331 332
      if (!$revisionable && !$translatable) {
        // The base layout stores all the base field values in the base table.
333
        $table_mapping->setFieldNames($this->baseTable, $all_fields);
334 335 336 337 338 339
      }
      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.
340
        $table_mapping->setFieldNames($this->baseTable, array_diff($all_fields, $revision_metadata_fields));
341
        $revision_key_fields = array($this->idKey, $this->revisionKey);
342
        $table_mapping->setFieldNames($this->revisionTable, array_merge($revision_key_fields, $revisionable_fields));
343 344 345 346 347 348 349 350
      }
      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.
351
        $table_mapping
352
          ->setFieldNames($this->baseTable, $key_fields)
353
          ->setFieldNames($this->dataTable, array_values(array_diff($all_fields, array($this->uuidKey))));
354 355 356 357 358 359 360 361 362
      }
      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.
363
        $table_mapping->setFieldNames($this->baseTable, array_values($key_fields));
364 365 366 367 368

        // 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));
369
        $table_mapping->setFieldNames($this->dataTable, $data_fields);
370 371

        $revision_base_fields = array_merge(array($this->idKey, $this->revisionKey, $this->langcodeKey), $revision_metadata_fields);
372
        $table_mapping->setFieldNames($this->revisionTable, $revision_base_fields);
373 374

        $revision_data_key_fields = array($this->idKey, $this->revisionKey, $this->langcodeKey);
375
        $revision_data_fields = array_diff($revisionable_fields, $revision_metadata_fields, array($this->langcodeKey));
376
        $table_mapping->setFieldNames($this->revisionDataTable, array_merge($revision_data_key_fields, $revision_data_fields));
377
      }
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402

      // Add dedicated tables.
      $definitions = array_filter($definitions, function (FieldStorageDefinitionInterface $definition) use ($table_mapping) {
        return $table_mapping->requiresDedicatedTableStorage($definition);
      });
      $extra_columns = array(
        'bundle',
        'deleted',
        'entity_id',
        'revision_id',
        'langcode',
        'delta',
      );
      foreach ($definitions as $field_name => $definition) {
        foreach (array($table_mapping->getDedicatedDataTableName($definition), $table_mapping->getDedicatedRevisionTableName($definition)) as $table_name) {
          $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;
      }
403
    }
404

405
    return $table_mapping;
406 407 408 409 410
  }

  /**
   * {@inheritdoc}
   */
411
  protected function doLoadMultiple(array $ids = NULL) {
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
    // 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.
    $entities_from_storage = $this->getFromStorage($ids);
    $this->setPersistentCache($entities_from_storage);

    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();

436 437 438 439 440 441
    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);
    }

442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
    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);

        // Call hook_entity_storage_load().
        foreach ($this->moduleHandler()->getImplementations('entity_storage_load') as $module) {
          $function = $module . '_entity_storage_load';
          $function($entities, $this->entityTypeId);
        }
        // Call hook_TYPE_storage_load().
        foreach ($this->moduleHandler()->getImplementations($this->entityTypeId . '_storage_load') as $module) {
          $function = $module . '_' . $this->entityTypeId . '_storage_load';
          $function($entities);
        }
      }
    }

    return $entities;
  }

467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
  /**
   * Ensures integer entity IDs are valid.
   *
   * The identifier sanitization provided by this method has been introduced
   * as Drupal used to rely on the database to facilitate this, which worked
   * correctly with MySQL but led to errors with other DBMS such as PostgreSQL.
   *
   * @param array $ids
   *   The entity IDs to verify.
   * @return array
   *   The sanitized list of entity IDs.
   */
  protected function cleanIds(array $ids) {
    $definitions = $this->entityManager->getBaseFieldDefinitions($this->entityTypeId);
    $id_definition = $definitions[$this->entityType->getKey('id')];
    if ($id_definition->getType() == 'integer') {
      $ids = array_filter($ids, function ($id) {
        return is_numeric($id) && $id == (int) $id;
      });
      $ids = array_map('intval', $ids);
    }
    return $ids;
  }

491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
  /**
   * Gets entities from the persistent cache backend.
   *
   * @param array|null &$ids
   *   If not empty, return entities that match these IDs. IDs that were found
   *   will be removed from the list.
   *
   * @return \Drupal\Core\Entity\ContentEntityInterface[]
   *   Array of entities from the persistent cache.
   */
  protected function getFromPersistentCache(array &$ids = NULL) {
    if (!$this->entityType->isPersistentlyCacheable() || empty($ids)) {
      return array();
    }
    $entities = array();
    // Build the list of cache entries to retrieve.
    $cid_map = array();
    foreach ($ids as $id) {
      $cid_map[$id] = $this->buildCacheId($id);
    }
    $cids = array_values($cid_map);
    if ($cache = $this->cacheBackend->getMultiple($cids)) {
      // Get the entities that were found in the cache.
      foreach ($ids as $index => $id) {
        $cid = $cid_map[$id];
        if (isset($cache[$cid])) {
          $entities[$id] = $cache[$cid]->data;
          unset($ids[$index]);
        }
      }
    }
    return $entities;
  }

  /**
   * Stores entities in the persistent cache backend.
   *
   * @param \Drupal\Core\Entity\ContentEntityInterface[] $entities
   *   Entities to store in the cache.
   */
  protected function setPersistentCache($entities) {
    if (!$this->entityType->isPersistentlyCacheable()) {
      return;
    }

    $cache_tags = array(
537 538
      $this->entityTypeId . '_values',
      'entity_field_info',
539 540 541 542 543 544 545 546 547 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
    );
    foreach ($entities as $id => $entity) {
      $this->cacheBackend->set($this->buildCacheId($id), $entity, CacheBackendInterface::CACHE_PERMANENT, $cache_tags);
    }
  }

  /**
   * Invokes hook_entity_load_uncached().
   *
   * @param \Drupal\Core\Entity\ContentEntityInterface[] $entities
   *   List of entities, keyed on the entity ID.
   */
  protected function invokeLoadUncachedHook(array &$entities) {
    if (!empty($entities)) {
      // Call hook_entity_load_uncached().
      foreach ($this->moduleHandler()->getImplementations('entity_load_uncached') as $module) {
        $function = $module . '_entity_load_uncached';
        $function($entities, $this->entityTypeId);
      }
      // Call hook_TYPE_load_uncached().
      foreach ($this->moduleHandler()->getImplementations($this->entityTypeId . '_load_uncached') as $module) {
        $function = $module . '_' . $this->entityTypeId . '_load_uncached';
        $function($entities);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function resetCache(array $ids = NULL) {
    if ($ids) {
      $cids = array();
      foreach ($ids as $id) {
        unset($this->entities[$id]);
        $cids[] = $this->buildCacheId($id);
      }
      if ($this->entityType->isPersistentlyCacheable()) {
        $this->cacheBackend->deleteMultiple($cids);
      }
    }
    else {
      $this->entities = array();
      if ($this->entityType->isPersistentlyCacheable()) {
583
        Cache::invalidateTags(array($this->entityTypeId . '_values'));
584 585 586
      }
    }
  }
587

588
  /**
589
   * Builds the cache ID for the passed in entity ID.
590 591 592 593 594 595 596 597 598
   *
   * @param int $id
   *   Entity ID for which the cache ID should be built.
   *
   * @return string
   *   Cache ID that can be passed to the cache backend.
   */
  protected function buildCacheId($id) {
    return "values:{$this->entityTypeId}:$id";
599 600 601
  }

  /**
602
   * Maps from storage records to entity objects, and attaches fields.
603
   *
604 605
   * @param array $records
   *   Associative array of query results, keyed on the entity ID.
606 607
   * @param bool $load_from_revision
   *   Flag to indicate whether revisions should be loaded or not.
608 609 610 611
   *
   * @return array
   *   An array of entity objects implementing the EntityInterface.
   */
612
  protected function mapFromStorageRecords(array $records, $load_from_revision = FALSE) {
613 614 615 616
    if (!$records) {
      return array();
    }

617
    $values = array();
618
    foreach ($records as $id => $record) {
619
      $values[$id] = array();
620 621 622
      // 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.
623
      foreach ($record as $name => $value) {
624 625 626 627
        // 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);
628
          $values[$id][$field_name][LanguageInterface::LANGCODE_DEFAULT][$property_name] = $value;
629 630 631 632
        }
        else {
          // Handle columns named directly after the field (e.g if the field
          // type only stores one property).
633
          $values[$id][$name][LanguageInterface::LANGCODE_DEFAULT] = $value;
634
        }
635 636
      }
    }
637

638 639 640 641 642 643 644 645 646 647 648 649 650
    // 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]));
    }
651

652 653 654 655
    return $entities;
  }

  /**
656
   * Loads values for fields stored in the shared data tables.
657
   *
658 659 660 661
   * @param array &$values
   *   Associative array of entities values, keyed on the entity ID.
   * @param array &$translations
   *   List of translations, keyed on the entity ID.
662
   */
663
  protected function loadFromSharedTables(array &$values, array &$translations) {
664 665 666 667
    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;
668 669 670
      $alias = $this->revisionDataTable ? 'revision' : 'data';
      $query = $this->database->select($table, $alias, array('fetch' => \PDO::FETCH_ASSOC))
        ->fields($alias)
671
        ->condition($alias . '.' . $this->idKey, array_keys($values), 'IN')
672
        ->orderBy($alias . '.' . $this->idKey);
673

674
      $table_mapping = $this->getTableMapping();
675
      if ($this->revisionDataTable) {
676 677 678 679
        // 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);
680 681 682

        // Find fields that are not revisioned or entity keys. Data fields have
        // the same value regardless of entity revision.
683
        $data_fields = array_diff($table_mapping->getFieldNames($this->dataTable), $fields, $base_fields);
684 685 686 687 688 689
        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);
        }

690 691
        // Get the revision IDs.
        $revision_ids = array();
692 693
        foreach ($values as $entity_values) {
          $revision_ids[] = $entity_values[$this->revisionKey][LanguageInterface::LANGCODE_DEFAULT];
694
        }
695
        $query->condition('revision.' . $this->revisionKey, $revision_ids, 'IN');
696 697
      }
      else {
698
        $fields = $table_mapping->getFieldNames($this->dataTable);
699 700
      }

701 702 703
      $result = $query->execute();
      foreach ($result as $row) {
        $id = $row[$this->idKey];
704 705

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

709 710
        $translations[$id][$langcode] = TRUE;

711
        foreach ($fields as $field_name) {
712 713 714
          $columns = $table_mapping->getColumnNames($field_name);
          // Do not key single-column fields by property name.
          if (count($columns) == 1) {
715
            $values[$id][$field_name][$langcode] = $row[reset($columns)];
716 717
          }
          else {
718
            foreach ($columns as $property_name => $column_name) {
719
              $values[$id][$field_name][$langcode][$property_name] = $row[$column_name];
720
            }
721 722 723 724 725 726 727
          }
        }
      }
    }
  }

  /**
728
   * {@inheritdoc}
729 730 731 732
   */
  public function loadRevision($revision_id) {
    // Build and execute the query.
    $query_result = $this->buildQuery(array(), $revision_id)->execute();
733
    $records = $query_result->fetchAllAssoc($this->idKey);
734

735 736
    if (!empty($records)) {
      // Convert the raw records to entity objects.
737
      $entities = $this->mapFromStorageRecords($records, TRUE);
738
      $this->postLoad($entities);
739 740 741 742
      $entity = reset($entities);
      if ($entity) {
        return $entity;
      }
743 744 745 746
    }
  }

  /**
747
   * Implements \Drupal\Core\Entity\EntityStorageInterface::deleteRevision().
748 749 750 751 752 753 754 755 756 757 758 759
   */
  public function deleteRevision($revision_id) {
    if ($revision = $this->loadRevision($revision_id)) {
      // Prevent deletion if this is the default revision.
      if ($revision->isDefaultRevision()) {
        throw new EntityStorageException('Default revision can not be deleted');
      }

      $this->database->delete($this->revisionTable)
        ->condition($this->revisionKey, $revision->getRevisionId())
        ->execute();
      $this->invokeFieldMethod('deleteRevision', $revision);
760
      $this->deleteRevisionFromDedicatedTables($revision);
761 762 763 764 765
      $this->invokeHook('revision_delete', $revision);
    }
  }

  /**
766
   * {@inheritdoc}
767 768 769 770 771 772 773
   */
  protected function buildPropertyQuery(QueryInterface $entity_query, array $values) {
    if ($this->dataTable) {
      // @todo We should not be using a condition to specify whether conditions
      //   apply to the default language. See http://drupal.org/node/1866330.
      // Default to the original entity language if not explicitly specified
      // otherwise.
774 775
      if (!array_key_exists($this->defaultLangcodeKey, $values)) {
        $values[$this->defaultLangcodeKey] = 1;
776 777 778
      }
      // 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.
779 780
      elseif ($values[$this->defaultLangcodeKey] === NULL) {
        unset($values[$this->defaultLangcodeKey]);
781 782 783
      }
    }

784
    parent::buildPropertyQuery($entity_query, $values);
785 786 787 788 789 790 791 792 793 794 795
  }

  /**
   * 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.
796
   * See Drupal\comment\CommentStorage::buildQuery() for an example.
797 798 799 800 801 802 803
   *
   * @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).
   *
804
   * @return \Drupal\Core\Database\Query\Select
805 806 807
   *   A SelectQuery object for loading the entity.
   */
  protected function buildQuery($ids, $revision_id = FALSE) {
808
    $query = $this->database->select($this->entityType->getBaseTable(), 'base');
809

810
    $query->addTag($this->entityTypeId . '_load_multiple');
811 812 813 814 815 816 817 818 819

    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.
820 821
    $table_mapping = $this->getTableMapping();
    $entity_fields = $table_mapping->getAllColumns($this->baseTable);
822 823 824

    if ($this->revisionTable) {
      // Add all fields from the {entity_revision} table.
825
      $entity_revision_fields = $table_mapping->getAllColumns($this->revisionTable);
826
      $entity_revision_fields = array_combine($entity_revision_fields, $entity_revision_fields);
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
      // 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.
842
      $query->addExpression('CASE base.' . $this->revisionKey . ' WHEN revision.' . $this->revisionKey . ' THEN 1 ELSE 0 END', 'isDefaultRevision');
843 844 845 846 847 848 849 850 851 852 853 854
    }

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

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

    return $query;
  }

  /**
855
   * Implements \Drupal\Core\Entity\EntityStorageInterface::delete().
856 857 858 859 860 861 862 863 864
   */
  public function delete(array $entities) {
    if (!$entities) {
      // If no IDs or invalid IDs were passed, do nothing.
      return;
    }

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

867 868
      // Ignore replica server temporarily.
      db_ignore_replica();
869 870 871
    }
    catch (\Exception $e) {
      $transaction->rollback();
872
      watchdog_exception($this->entityTypeId, $e);
873 874 875 876 877 878 879
      throw new EntityStorageException($e->getMessage(), $e->getCode(), $e);
    }
  }

  /**
   * {@inheritdoc}
   */
880 881
  protected function doDelete($entities) {
    $ids = array_keys($entities);
882

883
    $this->database->delete($this->entityType->getBaseTable())
884
      ->condition($this->idKey, $ids, 'IN')
885
      ->execute();
886

887 888
    if ($this->revisionTable) {
      $this->database->delete($this->revisionTable)
889
        ->condition($this->idKey, $ids, 'IN')
890 891
        ->execute();
    }
892

893 894
    if ($this->dataTable) {
      $this->database->delete($this->dataTable)
895
        ->condition($this->idKey, $ids, 'IN')
896 897
        ->execute();
    }
898

899 900
    if ($this->revisionDataTable) {
      $this->database->delete($this->revisionDataTable)
901
        ->condition($this->idKey, $ids, 'IN')
902 903
        ->execute();
    }
904

905 906
    foreach ($entities as $entity) {
      $this->invokeFieldMethod('delete', $entity);
907
      $this->deleteFromDedicatedTables($entity);
908 909 910 911 912 913 914 915 916 917 918 919 920
    }
  }

  /**
   * {@inheritdoc}
   */
  public function save(EntityInterface $entity) {
    $transaction = $this->database->startTransaction();
    try {
      // Sync the changes made in the fields array to the internal values array.
      $entity->updateOriginalValues();

      $return = parent::save($entity);
921

922 923
      // Ignore replica server temporarily.
      db_ignore_replica();
924 925 926 927
      return $return;
    }
    catch (\Exception $e) {
      $transaction->rollback();
928
      watchdog_exception($this->entityTypeId, $e);
929 930 931 932
      throw new EntityStorageException($e->getMessage(), $e->getCode(), $e);
    }
  }

933 934 935 936 937 938 939 940 941 942
  /**
   * {@inheritdoc}
   */
  protected function doSave($id, EntityInterface $entity) {
    // Create the storage record to be saved.
    $record = $this->mapToStorageRecord($entity);

    $is_new = $entity->isNew();
    if (!$is_new) {
      if ($entity->isDefaultRevision()) {
943 944 945 946 947 948
        $this->database
          ->update($this->baseTable)
          ->fields((array) $record)
          ->condition($this->idKey, $record->{$this->idKey})
          ->execute();
        $return = SAVED_UPDATED;
949 950 951 952 953 954 955
      }
      else {
        // @todo, should a different value be returned when saving an entity
        // with $isDefaultRevision = FALSE?
        $return = FALSE;
      }
      if ($this->revisionTable) {
956
        $entity->{$this->revisionKey}->value = $this->saveRevision($entity);
957 958
      }
      if ($this->dataTable) {
959
        $this->saveToSharedTables($entity);
960 961
      }
      if ($this->revisionDataTable) {
962
        $this->saveToSharedTables($entity, $this->revisionDataTable);
963 964 965 966 967 968
      }
    }
    else {
      // Ensure the entity is still seen as new after assigning it an id,
      // while storing its data.
      $entity->enforceIsNew();
969 970 971 972 973
      $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
974 975 976
      // 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})) {
977 978 979
        $record->{$this->idKey} = $insert_id;
      }
      $return = SAVED_NEW;
980 981 982 983 984 985
      $entity->{$this->idKey}->value = (string) $record->{$this->idKey};
      if ($this->revisionTable) {
        $entity->setNewRevision();
        $record->{$this->revisionKey} = $this->saveRevision($entity);
      }
      if ($this->dataTable) {
986
        $this->saveToSharedTables($entity);
987 988
      }
      if ($this->revisionDataTable) {
989
        $this->saveToSharedTables($entity, $this->revisionDataTable);
990 991 992
      }
    }
    $this->invokeFieldMethod($is_new ? 'insert' : 'update', $entity);
993
    $this->saveToDedicatedTables($entity, !$is_new);
994 995 996 997

    if (!$is_new && $this->dataTable) {
      $this->invokeTranslationHooks($entity);
    }
998 999 1000 1001
    $entity->enforceIsNew(FALSE);
    if ($this->revisionTable) {
      $entity->setNewRevision(FALSE);
    }
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
    return $return;
  }

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

1012
  /**
1013
   * Saves fields that use the shared tables.
1014
   *
1015
   * @param \Drupal\Core\Entity\ContentEntityInterface $entity
1016
   *   The entity object.
1017 1018
   * @param string $table_name
   *   (optional) The table name to save to. Defaults to the data table.
1019
   */
1020
  protected function saveToSharedTables(ContentEntityInterface $entity, $table_name = NULL) {
1021 1022 1023 1024
    if (!isset($table_name)) {
      $table_name = $this->dataTable;
    }
    $revision = $table_name != $this->dataTable;
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038

    if (!$revision || !$entity->isNewRevision()) {
      $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);
1039
      $record = $this->mapToDataStorageRecord($translation, $table_name);
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
      $values = (array) $record;
      $query
        ->fields(array_keys($values))
        ->values($values);
    }

    $query->execute();
  }

  /**
   * Maps from an entity object to the storage record.
   *
1052
   * @param \Drupal\Core\Entity\ContentEntityInterface $entity
1053
   *   The entity object.
1054 1055
   * @param string $table_name
   *   (optional) The table name to map records to. Defaults to the base table.
1056 1057 1058 1059
   *
   * @return \stdClass
   *   The record to store.
   */
1060 1061 1062 1063 1064
  protected function mapToStorageRecord(ContentEntityInterface $entity, $table_name = NULL) {
    if (!isset($table_name)) {
      $table_name = $this->baseTable;
    }

1065
    $record = new \stdClass();
1066 1067
    $table_mapping = $this->getTableMapping();
    foreach ($table_mapping->getFieldNames($table_name) as $field_name) {
1068

1069
      if (empty($this->getFieldStorageDefinitions()[$field_name])) {
1070
        throw new EntityStorageException(SafeMarkup::format('Table mapping contains invalid field %field.', array('%field' => $field_name)));
1071
      }
1072
      $definition = $this->getFieldStorageDefinitions()[$field_name];
1073 1074 1075 1076 1077 1078 1079 1080 1081
      $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
        //   https://drupal.org/node/2232427.
        if (!$definition->getMainPropertyName() && count($columns) == 1) {
1082
          $value = ($item = $entity->$field_name->first()) ? $item->getValue() : array();
1083
        }
1084 1085
        else {
          $value = isset($entity->$field_name->$column_name) ? $entity->$field_name->$column_name : NULL;
1086
        }
1087 1088
        if (!empty($definition->getSchema()['columns'][$column_name]['serialize'])) {
          $value = serialize($value);
1089
        }
1090 1091 1092 1093 1094

        // 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);
1095
        if (!(empty($value) && $this->isColumnSerial($table_name, $schema_name))) {
1096 1097
          $record->$schema_name = $value;
        }
1098 1099 1100 1101 1102 1103
      }
    }

    return $record;
  }

1104 1105 1106 1107 1108 1109 1110 1111 1112
  /**
   * 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
1113
   *   TRUE if the column is serial, FALSE otherwise.
1114
   *
1115 1116
   * @see \Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema::processBaseTable()
   * @see \Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema::processRevisionTable()
1117 1118 1119 1120