SqlContentEntityStorage.php 69.7 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\String;
11
use Drupal\Core\Cache\CacheBackendInterface;
12
use Drupal\Core\Database\Connection;
13
use Drupal\Core\Database\Database;
14 15 16 17 18 19
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\ContentEntityStorageBase;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Entity\EntityTypeInterface;
20
use Drupal\Core\Entity\Exception\FieldStorageDefinitionUpdateForbiddenException;
21
use Drupal\Core\Entity\Query\QueryInterface;
22
use Drupal\Core\Entity\Schema\FieldableEntityStorageSchemaInterface;
23
use Drupal\Core\Field\FieldDefinitionInterface;
24
use Drupal\Core\Field\FieldStorageDefinitionInterface;
25
use Drupal\Core\Language\LanguageInterface;
26 27 28
use Symfony\Component\DependencyInjection\ContainerInterface;

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

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

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

60 61 62 63 64 65 66 67 68 69 70 71 72 73
  /**
   * The entity langcode key.
   *
   * @var string|bool
   */
  protected $langcodeKey = FALSE;

  /**
   * The base table of the entity.
   *
   * @var string
   */
  protected $baseTable;

74 75 76 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
  /**
   * 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;

  /**
103
   * The entity manager.
104
   *
105
   * @var \Drupal\Core\Entity\EntityManagerInterface
106
   */
107
  protected $entityManager;
108

109 110 111
  /**
   * The entity schema handler.
   *
112
   * @var \Drupal\Core\Entity\Schema\EntityStorageSchemaInterface
113 114 115
   */
  protected $schemaHandler;

116 117 118 119 120 121 122
  /**
   * Cache backend.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface
   */
  protected $cacheBackend;

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

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

146
  /**
147
   * Constructs a SqlContentEntityStorage object.
148
   *
149 150
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type definition.
151 152
   * @param \Drupal\Core\Database\Connection $database
   *   The database connection to be used.
153 154
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager.
155 156
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
   *   The cache backend to be used.
157
   */
158
  public function __construct(EntityTypeInterface $entity_type, Connection $database, EntityManagerInterface $entity_manager, CacheBackendInterface $cache) {
159
    parent::__construct($entity_type);
160 161

    $this->database = $database;
162
    $this->entityManager = $entity_manager;
163
    $this->cacheBackend = $cache;
164 165 166 167 168 169 170 171 172 173

    // @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';
    }
174
    $translatable = $this->entityType->isTranslatable();
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
    if ($translatable) {
      $this->dataTable = $this->entityType->getDataTable() ?: $this->entityTypeId . '_field_data';
      $this->langcodeKey = $this->entityType->getKey('langcode') ?: 'langcode';
      $this->defaultLangcodeKey = $this->entityType->getKey('default_langcode') ?: 'default_langcode';
    }
    if ($revisionable && $translatable) {
      $this->revisionDataTable = $this->entityType->getRevisionDataTable() ?: $this->entityTypeId . '_field_revision';
    }
  }

  /**
   * Returns the base table name.
   *
   * @return string
   *   The table name.
   */
  public function getBaseTable() {
    return $this->baseTable;
  }

  /**
   * Returns the revision table name.
   *
   * @return string|false
   *   The table name or FALSE if it is not available.
   */
  public function getRevisionTable() {
    return $this->revisionTable;
  }

  /**
   * Returns the data table name.
   *
   * @return string|false
   *   The table name or FALSE if it is not available.
   */
  public function getDataTable() {
    return $this->dataTable;
  }

  /**
   * Returns the revision data table name.
   *
   * @return string|false
   *   The table name or FALSE if it is not available.
   */
  public function getRevisionDataTable() {
    return $this->revisionDataTable;
  }
224

225
  /**
226
   * Gets the schema handler for this entity storage.
227
   *
228
   * @return \Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema
229 230 231 232
   *   The schema handler.
   */
  protected function schemaHandler() {
    if (!isset($this->schemaHandler)) {
233
      $schema_handler_class = $this->entityType->getHandlerClass('storage_schema') ?: 'Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema';
234
      $this->schemaHandler = new $schema_handler_class($this->entityManager, $this->entityType, $this, $this->database);
235
    }
236 237
    return $this->schemaHandler;
  }
238

239 240 241 242 243 244
  /**
   * {@inheritdoc}
   */
  public function getTableMapping() {
    if (!isset($this->tableMapping)) {

245
      $definitions = array_filter($this->getFieldStorageDefinitions(), function (FieldStorageDefinitionInterface $definition) {
246 247 248
        // @todo Remove the check for FieldDefinitionInterface::isMultiple() when
        //   multiple-value base fields are supported in
        //   https://drupal.org/node/2248977.
249
        return !$definition->hasCustomStorage() && !$definition->isMultiple();
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
      });
      $this->tableMapping = new DefaultTableMapping($definitions);

      $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.
265 266 267 268 269
      $revision_metadata_fields = array_intersect(array(
        'revision_timestamp',
        'revision_uid',
        'revision_log',
      ), $all_fields);
270 271

      $revisionable = $this->entityType->isRevisionable();
272
      $translatable = $this->entityType->isTranslatable();
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 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
      if (!$revisionable && !$translatable) {
        // The base layout stores all the base field values in the base table.
        $this->tableMapping->setFieldNames($this->baseTable, $all_fields);
      }
      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.
        $this->tableMapping->setFieldNames($this->baseTable, array_diff($all_fields, $revision_metadata_fields));
        $revision_key_fields = array($this->idKey, $this->revisionKey);
        $this->tableMapping->setFieldNames($this->revisionTable, array_merge($revision_key_fields, $revisionable_fields));
      }
      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.
        $this->tableMapping
          ->setFieldNames($this->baseTable, $key_fields)
          ->setFieldNames($this->dataTable, array_values(array_diff($all_fields, array($this->uuidKey))))
          // Add the denormalized 'default_langcode' field to the mapping. Its
          // value is identical to the query expression
          // "base_table.langcode = data_table.langcode"
          ->setExtraColumns($this->dataTable, array('default_langcode'));
      }
      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.
        $this->tableMapping->setFieldNames($this->baseTable, array_values(array_diff($key_fields, array($this->langcodeKey))));

        // 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));
        $this->tableMapping
          ->setFieldNames($this->dataTable, $data_fields)
          // Add the denormalized 'default_langcode' field to the mapping. Its
          // value is identical to the query expression
          // "base_langcode = data_table.langcode" where "base_langcode" is
          // the language code of the default revision.
          ->setExtraColumns($this->dataTable, array('default_langcode'));

        $revision_base_fields = array_merge(array($this->idKey, $this->revisionKey, $this->langcodeKey), $revision_metadata_fields);
        $this->tableMapping->setFieldNames($this->revisionTable, $revision_base_fields);

        $revision_data_key_fields = array($this->idKey, $this->revisionKey, $this->langcodeKey);
        $revision_data_fields = array_diff($revisionable_fields, $revision_metadata_fields);
        $this->tableMapping
          ->setFieldNames($this->revisionDataTable, array_merge($revision_data_key_fields, $revision_data_fields))
          // Add the denormalized 'default_langcode' field to the mapping. Its
          // value is identical to the query expression
          // "revision_table.langcode = data_table.langcode".
          ->setExtraColumns($this->revisionDataTable, array('default_langcode'));
334 335
      }
    }
336 337

    return $this->tableMapping;
338 339 340 341 342
  }

  /**
   * {@inheritdoc}
   */
343
  protected function doLoadMultiple(array $ids = NULL) {
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 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 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 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 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
    // 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();

    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;
  }

  /**
   * 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(
      $this->entityTypeId . '_values' => TRUE,
      'entity_field_info' => TRUE,
    );
    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()) {
        $this->cacheBackend->deleteTags(array($this->entityTypeId . '_values' => TRUE));
      }
    }
  }
489

490 491 492 493 494 495 496 497 498 499 500
  /**
   * Returns the cache ID for the passed in entity ID.
   *
   * @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";
501 502 503
  }

  /**
504
   * Maps from storage records to entity objects, and attaches fields.
505
   *
506 507 508 509 510 511
   * @param array $records
   *   Associative array of query results, keyed on the entity ID.
   *
   * @return array
   *   An array of entity objects implementing the EntityInterface.
   */
512
  protected function mapFromStorageRecords(array $records) {
513 514 515 516
    if (!$records) {
      return array();
    }

517 518 519
    $entities = array();
    foreach ($records as $id => $record) {
      $entities[$id] = array();
520 521 522
      // 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.
523
      foreach ($record as $name => $value) {
524 525 526 527
        // 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);
528
          $entities[$id][$field_name][LanguageInterface::LANGCODE_DEFAULT][$property_name] = $value;
529 530 531 532
        }
        else {
          // Handle columns named directly after the field (e.g if the field
          // type only stores one property).
533
          $entities[$id][$name][LanguageInterface::LANGCODE_DEFAULT] = $value;
534
        }
535
      }
536
      // If we have no multilingual values we can instantiate entity objects
537 538 539 540
      // right now, otherwise we need to collect all the field values first.
      if (!$this->dataTable) {
        $bundle = $this->bundleKey ? $record->{$this->bundleKey} : FALSE;
        // Turn the record into an entity class.
541
        $entities[$id] = new $this->entityClass($entities[$id], $this->entityTypeId, $bundle);
542 543
      }
    }
544
    $this->attachPropertyData($entities);
545 546 547 548 549 550

    // Attach field values.
    if ($this->entityType->isFieldable()) {
      $this->loadFieldItems($entities);
    }

551 552 553 554 555 556 557 558 559
    return $entities;
  }

  /**
   * Attaches property data in all languages for translatable properties.
   *
   * @param array &$entities
   *   Associative array of entities, keyed on the entity ID.
   */
560
  protected function attachPropertyData(array &$entities) {
561 562 563 564 565 566 567 568 569 570
    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;
      $query = $this->database->select($table, 'data', array('fetch' => \PDO::FETCH_ASSOC))
        ->fields('data')
        ->condition($this->idKey, array_keys($entities))
        ->orderBy('data.' . $this->idKey);

      if ($this->revisionDataTable) {
571 572 573
        // Get the revision IDs.
        $revision_ids = array();
        foreach ($entities as $values) {
574
          $revision_ids[] = is_object($values) ? $values->getRevisionId() : $values[$this->revisionKey][LanguageInterface::LANGCODE_DEFAULT];
575
        }
576
        $query->condition($this->revisionKey, $revision_ids);
577 578 579
      }

      $data = $query->execute();
580 581

      $table_mapping = $this->getTableMapping();
582 583
      $translations = array();
      if ($this->revisionDataTable) {
584
        $data_fields = array_diff_key($table_mapping->getFieldNames($this->revisionDataTable), $table_mapping->getFieldNames($this->baseTable));
585 586
      }
      else {
587
        $data_fields = $table_mapping->getFieldNames($this->dataTable);
588 589 590 591 592 593
      }

      foreach ($data as $values) {
        $id = $values[$this->idKey];

        // Field values in default language are stored with
594 595
        // LanguageInterface::LANGCODE_DEFAULT as key.
        $langcode = empty($values['default_langcode']) ? $values['langcode'] : LanguageInterface::LANGCODE_DEFAULT;
596 597
        $translations[$id][$langcode] = TRUE;

598 599 600 601 602 603

        foreach ($data_fields as $field_name) {
          $columns = $table_mapping->getColumnNames($field_name);
          // Do not key single-column fields by property name.
          if (count($columns) == 1) {
            $entities[$id][$field_name][$langcode] = $values[reset($columns)];
604 605
          }
          else {
606 607
            foreach ($columns as $property_name => $column_name) {
              $entities[$id][$field_name][$langcode][$property_name] = $values[$column_name];
608
            }
609 610 611 612 613
          }
        }
      }

      foreach ($entities as $id => $values) {
614
        $bundle = $this->bundleKey ? $values[$this->bundleKey][LanguageInterface::LANGCODE_DEFAULT] : FALSE;
615
        // Turn the record into an entity class.
616
        $entities[$id] = new $this->entityClass($values, $this->entityTypeId, $bundle, array_keys($translations[$id]));
617 618 619 620 621
      }
    }
  }

  /**
622
   * Implements \Drupal\Core\Entity\EntityStorageInterface::loadRevision().
623 624 625 626
   */
  public function loadRevision($revision_id) {
    // Build and execute the query.
    $query_result = $this->buildQuery(array(), $revision_id)->execute();
627
    $records = $query_result->fetchAllAssoc($this->idKey);
628

629 630 631 632 633
    if (!empty($records)) {
      // Convert the raw records to entity objects.
      $entities = $this->mapFromStorageRecords($records);
      $this->postLoad($entities);
      return reset($entities);
634 635 636 637
    }
  }

  /**
638
   * Implements \Drupal\Core\Entity\EntityStorageInterface::deleteRevision().
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
   */
  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);
      $this->deleteFieldItemsRevision($revision);
      $this->invokeHook('revision_delete', $revision);
    }
  }

  /**
657
   * {@inheritdoc}
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
   */
  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.
      if (!array_key_exists('default_langcode', $values)) {
        $values['default_langcode'] = 1;
      }
      // 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.
      elseif ($values['default_langcode'] === NULL) {
        unset($values['default_langcode']);
      }
    }

675
    parent::buildPropertyQuery($entity_query, $values);
676 677 678 679 680 681 682 683 684 685 686
  }

  /**
   * 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.
687
   * See Drupal\comment\CommentStorage::buildQuery() for an example.
688 689 690 691 692 693 694
   *
   * @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).
   *
695
   * @return \Drupal\Core\Database\Query\Select
696 697 698
   *   A SelectQuery object for loading the entity.
   */
  protected function buildQuery($ids, $revision_id = FALSE) {
699
    $query = $this->database->select($this->entityType->getBaseTable(), 'base');
700

701
    $query->addTag($this->entityTypeId . '_load_multiple');
702 703 704 705 706 707 708 709 710

    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.
711 712
    $table_mapping = $this->getTableMapping();
    $entity_fields = $table_mapping->getAllColumns($this->baseTable);
713 714 715

    if ($this->revisionTable) {
      // Add all fields from the {entity_revision} table.
716
      $entity_revision_fields = $table_mapping->getAllColumns($this->revisionTable);
717
      $entity_revision_fields = array_combine($entity_revision_fields, $entity_revision_fields);
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
      // 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.
      $query->addExpression('base.' . $this->revisionKey . ' = revision.' . $this->revisionKey, 'isDefaultRevision');
    }

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

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

    return $query;
  }

  /**
746
   * Implements \Drupal\Core\Entity\EntityStorageInterface::delete().
747 748 749 750 751 752 753 754 755
   */
  public function delete(array $entities) {
    if (!$entities) {
      // If no IDs or invalid IDs were passed, do nothing.
      return;
    }

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

758 759
      // Ignore replica server temporarily.
      db_ignore_replica();
760 761 762
    }
    catch (\Exception $e) {
      $transaction->rollback();
763
      watchdog_exception($this->entityTypeId, $e);
764 765 766 767 768 769 770
      throw new EntityStorageException($e->getMessage(), $e->getCode(), $e);
    }
  }

  /**
   * {@inheritdoc}
   */
771 772
  protected function doDelete($entities) {
    $ids = array_keys($entities);
773

774 775 776
    $this->database->delete($this->entityType->getBaseTable())
      ->condition($this->idKey, $ids)
      ->execute();
777

778 779 780 781 782
    if ($this->revisionTable) {
      $this->database->delete($this->revisionTable)
        ->condition($this->idKey, $ids)
        ->execute();
    }
783

784 785 786 787 788
    if ($this->dataTable) {
      $this->database->delete($this->dataTable)
        ->condition($this->idKey, $ids)
        ->execute();
    }
789

790 791 792 793 794
    if ($this->revisionDataTable) {
      $this->database->delete($this->revisionDataTable)
        ->condition($this->idKey, $ids)
        ->execute();
    }
795

796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
    foreach ($entities as $entity) {
      $this->invokeFieldMethod('delete', $entity);
      $this->deleteFieldItems($entity);
    }
  }

  /**
   * {@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);
812

813 814
      // Ignore replica server temporarily.
      db_ignore_replica();
815 816 817 818
      return $return;
    }
    catch (\Exception $e) {
      $transaction->rollback();
819
      watchdog_exception($this->entityTypeId, $e);
820 821 822 823
      throw new EntityStorageException($e->getMessage(), $e->getCode(), $e);
    }
  }

824 825 826 827 828 829 830 831 832 833
  /**
   * {@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()) {
834 835 836 837 838 839
        $this->database
          ->update($this->baseTable)
          ->fields((array) $record)
          ->condition($this->idKey, $record->{$this->idKey})
          ->execute();
        $return = SAVED_UPDATED;
840 841 842 843 844 845 846
      }
      else {
        // @todo, should a different value be returned when saving an entity
        // with $isDefaultRevision = FALSE?
        $return = FALSE;
      }
      if ($this->revisionTable) {
847
        $entity->{$this->revisionKey}->value = $this->saveRevision($entity);
848 849 850 851 852
      }
      if ($this->dataTable) {
        $this->savePropertyData($entity);
      }
      if ($this->revisionDataTable) {
853
        $this->savePropertyData($entity, $this->revisionDataTable);
854 855 856 857 858 859 860 861 862
      }
      if ($this->revisionTable) {
        $entity->setNewRevision(FALSE);
      }
    }
    else {
      // Ensure the entity is still seen as new after assigning it an id,
      // while storing its data.
      $entity->enforceIsNew();
863 864 865 866 867
      $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
868 869 870
      // 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})) {
871 872 873
        $record->{$this->idKey} = $insert_id;
      }
      $return = SAVED_NEW;
874 875 876 877 878 879 880 881 882
      $entity->{$this->idKey}->value = (string) $record->{$this->idKey};
      if ($this->revisionTable) {
        $entity->setNewRevision();
        $record->{$this->revisionKey} = $this->saveRevision($entity);
      }
      if ($this->dataTable) {
        $this->savePropertyData($entity);
      }
      if ($this->revisionDataTable) {
883
        $this->savePropertyData($entity, $this->revisionDataTable);
884
      }
885

886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
      $entity->enforceIsNew(FALSE);
      if ($this->revisionTable) {
        $entity->setNewRevision(FALSE);
      }
    }
    $this->invokeFieldMethod($is_new ? 'insert' : 'update', $entity);
    $this->saveFieldItems($entity, !$is_new);

    if (!$is_new && $this->dataTable) {
      $this->invokeTranslationHooks($entity);
    }
    return $return;
  }

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

907 908 909 910 911
  /**
   * Stores the entity property language-aware data.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity object.
912 913
   * @param string $table_name
   *   (optional) The table name to save to. Defaults to the data table.
914
   */
915 916 917 918 919
  protected function savePropertyData(EntityInterface $entity, $table_name = NULL) {
    if (!isset($table_name)) {
      $table_name = $this->dataTable;
    }
    $revision = $table_name != $this->dataTable;
920 921 922 923 924 925 926 927 928 929 930 931 932 933

    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);
934
      $record = $this->mapToDataStorageRecord($translation, $table_name);
935 936 937 938 939 940 941 942 943
      $values = (array) $record;
      $query
        ->fields(array_keys($values))
        ->values($values);
    }

    $query->execute();
  }

944 945 946 947 948 949 950 951 952 953
  /**
   * {@inheritdoc}
   */
  protected function invokeHook($hook, EntityInterface $entity) {
    if ($hook == 'presave') {
      $this->invokeFieldMethod('preSave', $entity);
    }
    parent::invokeHook($hook, $entity);
  }

954 955 956
  /**
   * Maps from an entity object to the storage record.
   *
957
   * @param \Drupal\Core\Entity\ContentEntityInterface $entity
958
   *   The entity object.
959 960
   * @param string $table_name
   *   (optional) The table name to map records to. Defaults to the base table.
961 962 963 964
   *
   * @return \stdClass
   *   The record to store.
   */
965 966 967 968 969
  protected function mapToStorageRecord(ContentEntityInterface $entity, $table_name = NULL) {
    if (!isset($table_name)) {
      $table_name = $this->baseTable;
    }

970
    $record = new \stdClass();
971 972
    $table_mapping = $this->getTableMapping();
    foreach ($table_mapping->getFieldNames($table_name) as $field_name) {
973

974
      if (empty($this->getFieldStorageDefinitions()[$field_name])) {
975
        throw new EntityStorageException(String::format('Table mapping contains invalid field %field.', array('%field' => $field_name)));
976
      }
977
      $definition = $this->getFieldStorageDefinitions()[$field_name];
978 979 980 981 982 983 984 985 986 987
      $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) {
          $value = $entity->$field_name->first()->getValue();
988
        }
989 990
        else {
          $value = isset($entity->$field_name->$column_name) ? $entity->$field_name->$column_name : NULL;
991
        }
992 993
        if (!empty($definition->getSchema()['columns'][$column_name]['serialize'])) {
          $value = serialize($value);
994
        }
995 996 997 998 999

        // 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);
1000
        if (!(empty($value) && $this->isColumnSerial($table_name, $schema_name))) {
1001 1002
          $record->$schema_name = $value;
        }
1003 1004 1005 1006 1007 1008
      }
    }

    return $record;
  }

1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
  /**
   * 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
   *   TRUE if the the column is serial, FALSE otherwise.
   *
1020 1021
   * @see \Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema::processBaseTable()
   * @see \Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema::processRevisionTable()
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
   */
  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;
  }

1039 1040 1041 1042 1043
  /**
   * Maps from an entity object to the storage record of the field data.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity object.
1044 1045
   * @param string $table_name
   *   (optional) The table name to map records to. Defaults to the data table.
1046 1047 1048 1049
   *
   * @return \stdClass
   *   The record to store.
   */
1050 1051 1052 1053 1054
  protected function mapToDataStorageRecord(EntityInterface $entity, $table_name = NULL) {
    if (!isset($table_name)) {
      $table_name = $this->dataTable;
    }
    $record = $this->mapToStorageRecord($entity, $table_name);
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
    $record->langcode = $entity->language()->id;
    $record->default_langcode = intval($record->langcode == $entity->getUntranslated()->language()->id);
    return $record;
  }

  /**
   * Saves an entity revision.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity object.
   *
   * @return int
   *   The revision id.
   */
  protected function saveRevision(EntityInterface $entity) {
1070
    $record = $this->mapToStorageRecord($entity, $this->revisionTable);
1071 1072 1073 1074

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

    if ($entity->isNewRevision()) {
1075 1076 1077 1078
      $insert_id = $this->database
        ->insert($this->revisionTable, array('return' => Database::RETURN_INSERT_ID))
        ->fields((array) $record)
        ->execute();
1079
      // Even if this is a new revision, the revision ID key might have been
1080 1081 1082 1083
      // set in which case we should not override the provided revision ID.
      if (!isset($record->{$this->revisionKey})) {
        $record->{$this->revisionKey} = $insert_id;
      }
1084
      if ($entity->isDefaultRevision()) {
1085
        $this->database->update($this->entityType->getBaseTable())
1086 1087 1088 1089 1090 1091
          ->fields(array($this->revisionKey => $record->{$this->revisionKey}))
          ->condition($this->idKey, $record->{$this->idKey})
          ->execute();
      }
    }
    else {
1092 1093 1094 1095 1096
      $this->database
        ->update($this->revisionTable)
        ->fields((array) $record)
        ->condition($this->revisionKey, $record->{$this->revisionKey})
        ->execute();
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
    }

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

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

  /**
   * {@inheritdoc}
   */
  public function getQueryServiceName() {
    return 'entity.query.sql';
  }

  /**
1113 1114 1115 1116 1117 1118 1119
   * Loads values of configurable fields for a group of entities.
   *
   * Loads all fields for each entity object in a group of a single entity type.
   * The loaded field values are added directly to the entity objects.
   *
   * @param \Drupal\Core\Entity\ContentEntityInterface[] $entities
   *   An array of entities keyed by entity ID.
1120
   */
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
  protected function loadFieldItems(array $entities) {
    if (empty($entities) || !$this->entityType->isFieldable()) {
      return;
    }

    $age = static::FIELD_LOAD_CURRENT;
    foreach ($entities as $entity) {
      if (!$entity->isDefaultRevision()) {
        $age = static::FIELD_LOAD_REVISION;
        break;
      }
    }
1133 1134
    $load_current = $age == static::FIELD_LOAD_CURRENT;

1135
    // Collect entities ids, bundles and languages.
1136 1137
    $bundles = array();
    $ids = array();
1138
    $default_langcodes = array();
1139 1140 1141
    foreach ($entities as $key => $entity) {
      $bundles[$entity->bundle()] = TRUE;
      $ids[] = $load_current ? $key : $entity->getRevisionId();
1142
      $default_langcodes[$key] = $entity->getUntranslated()->language()->id;
1143 1144 1145
    }

    // Collect impacted fields.
1146
    $storage_definitions = array();
1147
    $definitions = array();
1148
    $table_mapping = $this->getTableMapping();
1149
    foreach ($bundles as $bundle => $v) {
1150
      $definitions[$bundle] = $this->entityManager->getFieldDefinitions($this->entityTypeId, $bundle);
1151 1152 1153 1154
      foreach ($definitions[$bundle] as $field_name => $field_definition) {
        $storage_definition = $field_definition->getFieldStorageDefinition();
        if ($this->usesDedicatedTable($storage_definition)) {
          $storage_definitions[$field_name] = $storage_definition;
1155
        }
1156 1157 1158 1159
      }
    }

    // Load field data.
1160
    $langcodes = array_keys(language_list(LanguageInterface::STATE_ALL));
1161
    foreach ($storage_definitions as $field_name => $storage_definition) {
1162
      $table = $load_current ? $table_mapping->getDedicatedDataTableName($storage_definition) : $table_mapping->getDedicatedRevisionTableName($storage_definition);
1163

1164 1165 1166
      // Ensure that only values having valid languages are retrieved. Since we
      // are loading values for multiple entities, we cannot limit the query to
      // the available translations.
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
      $results = $this->database->select($table, 't')
        ->fields('t')
        ->condition($load_current ? 'entity_id' : 'revision_id', $ids, 'IN')
        ->condition('deleted', 0)
        ->condition('langcode', $langcodes, 'IN')
        ->orderBy('delta')
        ->execute();

      $delta_count = array();
      foreach ($results as $row) {
1177
        $bundle = $entities[$row->entity_id]->bundle();
1178

1179 1180
        // Ensure that records for non-translatable fields having invalid
        // languages are skipped.
1181
        if ($row->langcode == $default_langcodes[$row->entity_id] || $definitions[$bundle][$field_name]->isTranslatable()) {
1182 1183
          if (!isset($delta_count[$row->entity_id][$row->langcode])) {
            $delta_count[$row->entity_id][$row->langcode] = 0;
1184 1185
          }

1186
          if ($storage_definition->getCardinality() == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED || $delta_count[$row->entity_id][$row->langcode] < $storage_definition->getCardinality()) {
1187 1188 1189
            $item = array();
            // For each column declared by the field, populate the item from the
            // prefixed database column.
1190
            foreach ($storage_definition->getColumns() as $column => $attributes) {
1191
              $column_name = $table_mapping->getFieldColumnName($storage_definition, $column);
1192 1193 1194 1195 1196 1197 1198 1199
              // Unserialize the value if specified in the column schema.
              $item[$column] = (!empty($attributes['serialize'])) ? unserialize($row->$column_name) : $row->$column_name;
            }

            // Add the item to the field values for the entity.
            $entities[$row->entity_id]->getTranslation($row->langcode)->{$field_name}[$delta_count[$row->entity_id][$row->langcode]] = $item;
            $delta_count[$row->entity_id][$row->langcode]++;
          }
1200 1201 1202 1203 1204 1205
        }
      }
    }
  }

  /**
1206 1207 1208 1209 1210 1211
   * Saves values of configurable fields for an entity.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity.
   * @param bool $update
   *   TRUE if the entity is being updated, FALSE if it is being inserted.
1212
   */
1213
  protected function saveFieldItems(EntityInterface $entity, $update = TRUE) {
1214 1215 1216
    $vid = $entity->getRevisionId();
    $id = $entity->id();
    $bundle = $entity->bundle();
1217
    $entity_type = $entity->getEntityTypeId();
1218 1219
    $default_langcode = $entity->getUntranslated()->language()->id;
    $translation_langcodes = array_keys($entity->getTranslationLanguages());
1220
    $table_mapping = $this->getTableMapping();
1221

1222 1223 1224 1225
    if (!isset($vid)) {
      $vid = $id;
    }

1226 1227 1228
    foreach ($this->entityManager->getFieldDefinitions($entity_type, $bundle) as $field_name => $field_definition) {
      $storage_definition = $field_definition->getFieldStorageDefinition();
      if (!$this->usesDedicatedTable($storage_definition)) {
1229 1230
        continue;
      }
1231 1232
      $table_name = $table_mapping->getDedicatedDataTableName($storage_definition);
      $revision_name = $table_mapping->getDedicatedRevisionTableName($storage_definition);
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251

      // Delete and insert, rather than update, in case a value was added.
      if ($update) {
        // Only overwrite the field's base table if saving the default revision
        // of an entity.
        if ($entity->isDefaultRevision()) {
          $this->database->delete($table_name)
            ->condition('entity_id', $id)
            ->execute();
        }
        $this->database->delete($revision_name)
          ->condition('entity_id', $id)
          ->condition('revision_id', $vid)
          ->execute();
      }

      // Prepare the multi-insert query.
      $do_insert = FALSE;
      $columns = array('entity_id', 'revision_id', 'bundle', 'delta', 'langcode');
1252
      foreach ($storage_definition->getColumns() as $column => $attributes) {
1253
        $columns[] = $table_mapping->getFieldColumnName($storage_definition, $column);
1254 1255 1256 1257
      }
      $query = $this->database->insert($table_name)->fields($columns);
      $revision_query = $this->database->insert($revision_name)->fields($columns);

1258
      $langcodes = $field_definition->isTranslatable() ? $translation_langcodes : array($default_langcode);