View source
<?php
namespace Drupal\Core\Entity\Sql;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Database\Database;
use Drupal\Core\Database\DatabaseExceptionWrapper;
use Drupal\Core\Database\SchemaException;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\ContentEntityStorageBase;
use Drupal\Core\Entity\EntityBundleListenerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Query\QueryInterface;
use Drupal\Core\Entity\Schema\DynamicallyFieldableEntityStorageSchemaInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\field\FieldStorageConfigInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class SqlContentEntityStorage extends ContentEntityStorageBase implements SqlEntityStorageInterface, DynamicallyFieldableEntityStorageSchemaInterface, EntityBundleListenerInterface {
protected $tableMapping;
protected $revisionKey = FALSE;
protected $langcodeKey = FALSE;
protected $defaultLangcodeKey = FALSE;
protected $baseTable;
protected $revisionTable;
protected $dataTable;
protected $revisionDataTable;
protected $database;
protected $storageSchema;
protected $languageManager;
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static($entity_type, $container
->get('database'), $container
->get('entity.manager'), $container
->get('cache.entity'), $container
->get('language_manager'));
}
public function getFieldStorageDefinitions() {
return $this->entityManager
->getBaseFieldDefinitions($this->entityTypeId);
}
public function __construct(EntityTypeInterface $entity_type, Connection $database, EntityManagerInterface $entity_manager, CacheBackendInterface $cache, LanguageManagerInterface $language_manager) {
parent::__construct($entity_type, $entity_manager, $cache);
$this->database = $database;
$this->languageManager = $language_manager;
$this
->initTableLayout();
}
protected function initTableLayout() {
$this->tableMapping = NULL;
$this->revisionKey = NULL;
$this->revisionTable = NULL;
$this->dataTable = NULL;
$this->revisionDataTable = NULL;
$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';
}
$translatable = $this->entityType
->isTranslatable();
if ($translatable) {
$this->dataTable = $this->entityType
->getDataTable() ?: $this->entityTypeId . '_field_data';
$this->langcodeKey = $this->entityType
->getKey('langcode');
$this->defaultLangcodeKey = $this->entityType
->getKey('default_langcode');
}
if ($revisionable && $translatable) {
$this->revisionDataTable = $this->entityType
->getRevisionDataTable() ?: $this->entityTypeId . '_field_revision';
}
}
public function getBaseTable() {
return $this->baseTable;
}
public function getRevisionTable() {
return $this->revisionTable;
}
public function getDataTable() {
return $this->dataTable;
}
public function getRevisionDataTable() {
return $this->revisionDataTable;
}
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);
}
return $this->storageSchema;
}
public function setEntityType(EntityTypeInterface $entity_type) {
if ($this->entityType
->id() == $entity_type
->id()) {
$this->entityType = $entity_type;
$this
->initTableLayout();
}
else {
throw new EntityStorageException("Unsupported entity type {$entity_type->id()}");
}
}
public function getTableMapping(array $storage_definitions = NULL) {
$table_mapping = $this->tableMapping;
if (!isset($this->tableMapping) || $storage_definitions) {
$definitions = $storage_definitions ?: $this->entityManager
->getFieldStorageDefinitions($this->entityTypeId);
$table_mapping = new DefaultTableMapping($this->entityType, $definitions);
$definitions = array_filter($definitions, function (FieldStorageDefinitionInterface $definition) use ($table_mapping) {
return $table_mapping
->allowsSharedTableStorage($definition);
});
$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();
}));
$all_fields = array_merge($key_fields, array_diff($all_fields, $key_fields));
$revision_metadata_fields = array_intersect(array(
'revision_timestamp',
'revision_uid',
'revision_log',
), $all_fields);
$revisionable = $this->entityType
->isRevisionable();
$translatable = $this->entityType
->isTranslatable();
if (!$revisionable && !$translatable) {
$table_mapping
->setFieldNames($this->baseTable, $all_fields);
}
elseif ($revisionable && !$translatable) {
$table_mapping
->setFieldNames($this->baseTable, array_diff($all_fields, $revision_metadata_fields));
$revision_key_fields = array(
$this->idKey,
$this->revisionKey,
);
$table_mapping
->setFieldNames($this->revisionTable, array_merge($revision_key_fields, $revisionable_fields));
}
elseif (!$revisionable && $translatable) {
$table_mapping
->setFieldNames($this->baseTable, $key_fields)
->setFieldNames($this->dataTable, array_values(array_diff($all_fields, array(
$this->uuidKey,
))));
}
elseif ($revisionable && $translatable) {
$table_mapping
->setFieldNames($this->baseTable, array_values($key_fields));
$data_fields = array_values(array_diff($all_fields, array(
$this->uuidKey,
), $revision_metadata_fields));
$table_mapping
->setFieldNames($this->dataTable, $data_fields);
$revision_base_fields = array_merge(array(
$this->idKey,
$this->revisionKey,
$this->langcodeKey,
), $revision_metadata_fields);
$table_mapping
->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, array(
$this->langcodeKey,
));
$table_mapping
->setFieldNames($this->revisionDataTable, array_merge($revision_data_key_fields, $revision_data_fields));
}
$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);
}
}
if (!$storage_definitions) {
$this->tableMapping = $table_mapping;
}
}
return $table_mapping;
}
protected function doLoadMultiple(array $ids = NULL) {
$entities_from_cache = $this
->getFromPersistentCache($ids);
if ($entities_from_storage = $this
->getFromStorage($ids)) {
$this
->invokeStorageLoadHook($entities_from_storage);
$this
->setPersistentCache($entities_from_storage);
}
return $entities_from_cache + $entities_from_storage;
}
protected function getFromStorage(array $ids = NULL) {
$entities = array();
if (!empty($ids)) {
$ids = $this
->cleanIds($ids);
}
if ($ids === NULL || $ids) {
$query_result = $this
->buildQuery($ids)
->execute();
$records = $query_result
->fetchAllAssoc($this->idKey);
if ($records) {
$entities = $this
->mapFromStorageRecords($records);
}
}
return $entities;
}
protected function mapFromStorageRecords(array $records, $load_from_revision = FALSE) {
if (!$records) {
return array();
}
$values = array();
foreach ($records as $id => $record) {
$values[$id] = array();
foreach ($record as $name => $value) {
if ($field_name = strstr($name, '__', TRUE)) {
$property_name = substr($name, strpos($name, '__') + 2);
$values[$id][$field_name][LanguageInterface::LANGCODE_DEFAULT][$property_name] = $value;
}
else {
$values[$id][$name][LanguageInterface::LANGCODE_DEFAULT] = $value;
}
}
}
$translations = array_fill_keys(array_keys($values), array());
$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;
$entities[$id] = new $this->entityClass($entity_values, $this->entityTypeId, $bundle, array_keys($translations[$id]));
}
return $entities;
}
protected function loadFromSharedTables(array &$values, array &$translations) {
if ($this->dataTable) {
$table = $this->revisionDataTable ?: $this->dataTable;
$alias = $this->revisionDataTable ? 'revision' : 'data';
$query = $this->database
->select($table, $alias, array(
'fetch' => \PDO::FETCH_ASSOC,
))
->fields($alias)
->condition($alias . '.' . $this->idKey, array_keys($values), 'IN')
->orderBy($alias . '.' . $this->idKey);
$table_mapping = $this
->getTableMapping();
if ($this->revisionDataTable) {
$base_fields = array_diff($table_mapping
->getFieldNames($this->baseTable), array(
$this->langcodeKey,
));
$fields = array_diff($table_mapping
->getFieldNames($this->revisionDataTable), $base_fields);
$data_fields = array_diff($table_mapping
->getFieldNames($this->dataTable), $fields, $base_fields);
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);
}
$revision_ids = array();
foreach ($values as $entity_values) {
$revision_ids[] = $entity_values[$this->revisionKey][LanguageInterface::LANGCODE_DEFAULT];
}
$query
->condition('revision.' . $this->revisionKey, $revision_ids, 'IN');
}
else {
$fields = $table_mapping
->getFieldNames($this->dataTable);
}
$result = $query
->execute();
foreach ($result as $row) {
$id = $row[$this->idKey];
$langcode = empty($row[$this->defaultLangcodeKey]) ? $row[$this->langcodeKey] : LanguageInterface::LANGCODE_DEFAULT;
$translations[$id][$langcode] = TRUE;
foreach ($fields as $field_name) {
$columns = $table_mapping
->getColumnNames($field_name);
if (count($columns) == 1) {
$values[$id][$field_name][$langcode] = $row[reset($columns)];
}
else {
foreach ($columns as $property_name => $column_name) {
$values[$id][$field_name][$langcode][$property_name] = $row[$column_name];
}
}
}
}
}
}
protected function doLoadRevisionFieldItems($revision_id) {
$revision = NULL;
$query_result = $this
->buildQuery(array(), $revision_id)
->execute();
$records = $query_result
->fetchAllAssoc($this->idKey);
if (!empty($records)) {
$entities = $this
->mapFromStorageRecords($records, TRUE);
$revision = reset($entities) ?: NULL;
}
return $revision;
}
protected function doDeleteRevisionFieldItems(ContentEntityInterface $revision) {
$this->database
->delete($this->revisionTable)
->condition($this->revisionKey, $revision
->getRevisionId())
->execute();
$this
->deleteRevisionFromDedicatedTables($revision);
}
protected function buildPropertyQuery(QueryInterface $entity_query, array $values) {
if ($this->dataTable) {
if (!array_key_exists($this->defaultLangcodeKey, $values)) {
$values[$this->defaultLangcodeKey] = 1;
}
elseif ($values[$this->defaultLangcodeKey] === NULL) {
unset($values[$this->defaultLangcodeKey]);
}
}
parent::buildPropertyQuery($entity_query, $values);
}
protected function buildQuery($ids, $revision_id = FALSE) {
$query = $this->database
->select($this->entityType
->getBaseTable(), 'base');
$query
->addTag($this->entityTypeId . '_load_multiple');
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}");
}
$table_mapping = $this
->getTableMapping();
$entity_fields = $table_mapping
->getAllColumns($this->baseTable);
if ($this->revisionTable) {
$entity_revision_fields = $table_mapping
->getAllColumns($this->revisionTable);
$entity_revision_fields = array_combine($entity_revision_fields, $entity_revision_fields);
unset($entity_revision_fields[$this->idKey]);
$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);
$query
->addExpression('CASE base.' . $this->revisionKey . ' WHEN revision.' . $this->revisionKey . ' THEN 1 ELSE 0 END', 'isDefaultRevision');
}
$query
->fields('base', $entity_fields);
if ($ids) {
$query
->condition("base.{$this->idKey}", $ids, 'IN');
}
return $query;
}
public function delete(array $entities) {
if (!$entities) {
return;
}
$transaction = $this->database
->startTransaction();
try {
parent::delete($entities);
db_ignore_replica();
} catch (\Exception $e) {
$transaction
->rollback();
watchdog_exception($this->entityTypeId, $e);
throw new EntityStorageException($e
->getMessage(), $e
->getCode(), $e);
}
}
protected function doDeleteFieldItems($entities) {
$ids = array_keys($entities);
$this->database
->delete($this->entityType
->getBaseTable())
->condition($this->idKey, $ids, 'IN')
->execute();
if ($this->revisionTable) {
$this->database
->delete($this->revisionTable)
->condition($this->idKey, $ids, 'IN')
->execute();
}
if ($this->dataTable) {
$this->database
->delete($this->dataTable)
->condition($this->idKey, $ids, 'IN')
->execute();
}
if ($this->revisionDataTable) {
$this->database
->delete($this->revisionDataTable)
->condition($this->idKey, $ids, 'IN')
->execute();
}
foreach ($entities as $entity) {
$this
->deleteFromDedicatedTables($entity);
}
}
public function save(EntityInterface $entity) {
$transaction = $this->database
->startTransaction();
try {
$return = parent::save($entity);
db_ignore_replica();
return $return;
} catch (\Exception $e) {
$transaction
->rollback();
watchdog_exception($this->entityTypeId, $e);
throw new EntityStorageException($e
->getMessage(), $e
->getCode(), $e);
}
}
protected function doSaveFieldItems(ContentEntityInterface $entity, array $names = []) {
$full_save = empty($names);
$update = !$full_save || !$entity
->isNew();
if ($full_save) {
$shared_table_fields = TRUE;
$dedicated_table_fields = TRUE;
}
else {
$table_mapping = $this
->getTableMapping();
$storage_definitions = $this->entityManager
->getFieldStorageDefinitions($this->entityTypeId);
$shared_table_fields = FALSE;
$dedicated_table_fields = [];
foreach ($names as $name) {
$storage_definition = $storage_definitions[$name];
if ($table_mapping
->allowsSharedTableStorage($storage_definition)) {
$shared_table_fields = TRUE;
}
elseif ($table_mapping
->requiresDedicatedTableStorage($storage_definition)) {
$dedicated_table_fields[] = $name;
}
}
}
if ($shared_table_fields) {
$record = $this
->mapToStorageRecord($entity
->getUntranslated(), $this->baseTable);
if ($update) {
$default_revision = $entity
->isDefaultRevision();
if ($default_revision) {
$this->database
->update($this->baseTable)
->fields((array) $record)
->condition($this->idKey, $record->{$this->idKey})
->execute();
}
if ($this->revisionTable) {
if ($full_save) {
$entity->{$this->revisionKey} = $this
->saveRevision($entity);
}
else {
$record = $this
->mapToStorageRecord($entity
->getUntranslated(), $this->revisionTable);
$entity
->preSaveRevision($this, $record);
$this->database
->update($this->revisionTable)
->fields((array) $record)
->condition($this->revisionKey, $record->{$this->revisionKey})
->execute();
}
}
if ($default_revision && $this->dataTable) {
$this
->saveToSharedTables($entity);
}
if ($this->revisionDataTable) {
$new_revision = $full_save && $entity
->isNewRevision();
$this
->saveToSharedTables($entity, $this->revisionDataTable, $new_revision);
}
}
else {
$insert_id = $this->database
->insert($this->baseTable, array(
'return' => Database::RETURN_INSERT_ID,
))
->fields((array) $record)
->execute();
if (!isset($record->{$this->idKey})) {
$record->{$this->idKey} = $insert_id;
}
$entity->{$this->idKey} = (string) $record->{$this->idKey};
if ($this->revisionTable) {
$record->{$this->revisionKey} = $this
->saveRevision($entity);
}
if ($this->dataTable) {
$this
->saveToSharedTables($entity);
}
if ($this->revisionDataTable) {
$this
->saveToSharedTables($entity, $this->revisionDataTable);
}
}
}
if ($dedicated_table_fields) {
$names = is_array($dedicated_table_fields) ? $dedicated_table_fields : [];
$this
->saveToDedicatedTables($entity, $update, $names);
}
}
protected function has($id, EntityInterface $entity) {
return !$entity
->isNew();
}
protected function saveToSharedTables(ContentEntityInterface $entity, $table_name = NULL, $new_revision = NULL) {
if (!isset($table_name)) {
$table_name = $this->dataTable;
}
if (!isset($new_revision)) {
$new_revision = $entity
->isNewRevision();
}
$revision = $table_name != $this->dataTable;
if (!$revision || !$new_revision) {
$key = $revision ? $this->revisionKey : $this->idKey;
$value = $revision ? $entity
->getRevisionId() : $entity
->id();
$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);
$record = $this
->mapToDataStorageRecord($translation, $table_name);
$values = (array) $record;
$query
->fields(array_keys($values))
->values($values);
}
$query
->execute();
}
protected function mapToStorageRecord(ContentEntityInterface $entity, $table_name = NULL) {
if (!isset($table_name)) {
$table_name = $this->baseTable;
}
$record = new \stdClass();
$table_mapping = $this
->getTableMapping();
foreach ($table_mapping
->getFieldNames($table_name) as $field_name) {
if (empty($this
->getFieldStorageDefinitions()[$field_name])) {
throw new EntityStorageException("Table mapping contains invalid field {$field_name}.");
}
$definition = $this
->getFieldStorageDefinitions()[$field_name];
$columns = $table_mapping
->getColumnNames($field_name);
foreach ($columns as $column_name => $schema_name) {
if (!$definition
->getMainPropertyName() && count($columns) == 1) {
$value = ($item = $entity->{$field_name}
->first()) ? $item
->getValue() : array();
}
else {
$value = isset($entity->{$field_name}->{$column_name}) ? $entity->{$field_name}->{$column_name} : NULL;
}
if (!empty($definition
->getSchema()['columns'][$column_name]['serialize'])) {
$value = serialize($value);
}
$value = drupal_schema_get_field_value($definition
->getSchema()['columns'][$column_name], $value);
if (!(empty($value) && $this
->isColumnSerial($table_name, $schema_name))) {
$record->{$schema_name} = $value;
}
}
}
return $record;
}
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;
}
protected function mapToDataStorageRecord(EntityInterface $entity, $table_name = NULL) {
if (!isset($table_name)) {
$table_name = $this->dataTable;
}
$record = $this
->mapToStorageRecord($entity, $table_name);
return $record;
}
protected function saveRevision(ContentEntityInterface $entity) {
$record = $this
->mapToStorageRecord($entity
->getUntranslated(), $this->revisionTable);
$entity
->preSaveRevision($this, $record);
if ($entity
->isNewRevision()) {
$insert_id = $this->database
->insert($this->revisionTable, array(
'return' => Database::RETURN_INSERT_ID,
))
->fields((array) $record)
->execute();
if (!isset($record->{$this->revisionKey})) {
$record->{$this->revisionKey} = $insert_id;
}
if ($entity
->isDefaultRevision()) {
$this->database
->update($this->entityType
->getBaseTable())
->fields(array(
$this->revisionKey => $record->{$this->revisionKey},
))
->condition($this->idKey, $record->{$this->idKey})
->execute();
}
}
else {
$this->database
->update($this->revisionTable)
->fields((array) $record)
->condition($this->revisionKey, $record->{$this->revisionKey})
->execute();
}
$entity->{$this->revisionKey}->value = $record->{$this->revisionKey};
return $record->{$this->revisionKey};
}
protected function getQueryServiceName() {
return 'entity.query.sql';
}
protected function loadFromDedicatedTables(array &$values, $load_from_revision) {
if (empty($values)) {
return;
}
$bundles = array();
$ids = array();
$default_langcodes = array();
foreach ($values as $key => $entity_values) {
$bundles[$this->bundleKey ? $entity_values[$this->bundleKey][LanguageInterface::LANGCODE_DEFAULT] : $this->entityTypeId] = TRUE;
$ids[] = !$load_from_revision ? $key : $entity_values[$this->revisionKey][LanguageInterface::LANGCODE_DEFAULT];
if ($this->langcodeKey && isset($entity_values[$this->langcodeKey][LanguageInterface::LANGCODE_DEFAULT])) {
$default_langcodes[$key] = $entity_values[$this->langcodeKey][LanguageInterface::LANGCODE_DEFAULT];
}
}
$storage_definitions = array();
$definitions = array();
$table_mapping = $this
->getTableMapping();
foreach ($bundles as $bundle => $v) {
$definitions[$bundle] = $this->entityManager
->getFieldDefinitions($this->entityTypeId, $bundle);
foreach ($definitions[$bundle] as $field_name => $field_definition) {
$storage_definition = $field_definition
->getFieldStorageDefinition();
if ($table_mapping
->requiresDedicatedTableStorage($storage_definition)) {
$storage_definitions[$field_name] = $storage_definition;
}
}
}
$langcodes = array_keys($this->languageManager
->getLanguages(LanguageInterface::STATE_ALL));
foreach ($storage_definitions as $field_name => $storage_definition) {
$table = !$load_from_revision ? $table_mapping
->getDedicatedDataTableName($storage_definition) : $table_mapping
->getDedicatedRevisionTableName($storage_definition);
$results = $this->database
->select($table, 't')
->fields('t')
->condition(!$load_from_revision ? 'entity_id' : 'revision_id', $ids, 'IN')
->condition('deleted', 0)
->condition('langcode', $langcodes, 'IN')
->orderBy('delta')
->execute();
foreach ($results as $row) {
$bundle = $row->bundle;
$langcode = LanguageInterface::LANGCODE_DEFAULT;
if ($this->langcodeKey && isset($default_langcodes[$row->entity_id]) && $row->langcode != $default_langcodes[$row->entity_id]) {
$langcode = $row->langcode;
}
if (!isset($values[$row->entity_id][$field_name][$langcode])) {
$values[$row->entity_id][$field_name][$langcode] = array();
}
if ($langcode == LanguageInterface::LANGCODE_DEFAULT || $definitions[$bundle][$field_name]
->isTranslatable()) {
if ($storage_definition
->getCardinality() == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED || count($values[$row->entity_id][$field_name][$langcode]) < $storage_definition
->getCardinality()) {
$item = array();
foreach ($storage_definition
->getColumns() as $column => $attributes) {
$column_name = $table_mapping
->getFieldColumnName($storage_definition, $column);
$item[$column] = !empty($attributes['serialize']) ? unserialize($row->{$column_name}) : $row->{$column_name};
}
$values[$row->entity_id][$field_name][$langcode][] = $item;
}
}
}
}
}
protected function saveToDedicatedTables(ContentEntityInterface $entity, $update = TRUE, $names = array()) {
$vid = $entity
->getRevisionId();
$id = $entity
->id();
$bundle = $entity
->bundle();
$entity_type = $entity
->getEntityTypeId();
$default_langcode = $entity
->getUntranslated()
->language()
->getId();
$translation_langcodes = array_keys($entity
->getTranslationLanguages());
$table_mapping = $this
->getTableMapping();
if (!isset($vid)) {
$vid = $id;
}
$original = !empty($entity->original) ? $entity->original : NULL;
$definitions = $this->entityManager
->getFieldDefinitions($entity_type, $bundle);
if ($names) {
$definitions = array_intersect_key($definitions, array_flip($names));
}
foreach ($definitions as $field_name => $field_definition) {
$storage_definition = $field_definition
->getFieldStorageDefinition();
if (!$table_mapping
->requiresDedicatedTableStorage($storage_definition)) {
continue;
}
if (!$entity
->isNewRevision() && $original && !$this
->hasFieldValueChanged($field_definition, $entity, $original)) {
continue;
}
$table_name = $table_mapping
->getDedicatedDataTableName($storage_definition);
$revision_name = $table_mapping
->getDedicatedRevisionTableName($storage_definition);
if ($update) {
if ($entity
->isDefaultRevision()) {
$this->database
->delete($table_name)
->condition('entity_id', $id)
->execute();
}
if ($this->entityType
->isRevisionable()) {
$this->database
->delete($revision_name)
->condition('entity_id', $id)
->condition('revision_id', $vid)
->execute();
}
}
$do_insert = FALSE;
$columns = array(
'entity_id',
'revision_id',
'bundle',
'delta',
'langcode',
);
foreach ($storage_definition
->getColumns() as $column => $attributes) {
$columns[] = $table_mapping
->getFieldColumnName($storage_definition, $column);
}
$query = $this->database
->insert($table_name)
->fields($columns);
if ($this->entityType
->isRevisionable()) {
$revision_query = $this->database
->insert($revision_name)
->fields($columns);
}
$langcodes = $field_definition
->isTranslatable() ? $translation_langcodes : array(
$default_langcode,
);
foreach ($langcodes as $langcode) {
$delta_count = 0;
$items = $entity
->getTranslation($langcode)
->get($field_name);
$items
->filterEmptyItems();
foreach ($items as $delta => $item) {
$do_insert = TRUE;
$record = array(
'entity_id' => $id,
'revision_id' => $vid,
'bundle' => $bundle,
'delta' => $delta,
'langcode' => $langcode,
);
foreach ($storage_definition
->getColumns() as $column => $attributes) {
$column_name = $table_mapping
->getFieldColumnName($storage_definition, $column);
$record[$column_name] = !empty($attributes['serialize']) ? serialize($item->{$column}) : $item->{$column};
}
$query
->values($record);
if ($this->entityType
->isRevisionable()) {
$revision_query
->values($record);
}
if ($storage_definition
->getCardinality() != FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED && ++$delta_count == $storage_definition
->getCardinality()) {
break;
}
}
}
if ($do_insert) {
if ($entity
->isDefaultRevision()) {
$query
->execute();
}
if ($this->entityType
->isRevisionable()) {
$revision_query
->execute();
}
}
}
}
protected function deleteFromDedicatedTables(ContentEntityInterface $entity) {
$table_mapping = $this
->getTableMapping();
foreach ($this->entityManager
->getFieldDefinitions($entity
->getEntityTypeId(), $entity
->bundle()) as $field_definition) {
$storage_definition = $field_definition
->getFieldStorageDefinition();
if (!$table_mapping
->requiresDedicatedTableStorage($storage_definition)) {
continue;
}
$table_name = $table_mapping
->getDedicatedDataTableName($storage_definition);
$revision_name = $table_mapping
->getDedicatedRevisionTableName($storage_definition);
$this->database
->delete($table_name)
->condition('entity_id', $entity
->id())
->execute();
if ($this->entityType
->isRevisionable()) {
$this->database
->delete($revision_name)
->condition('entity_id', $entity
->id())
->execute();
}
}
}
protected function deleteRevisionFromDedicatedTables(ContentEntityInterface $entity) {
$vid = $entity
->getRevisionId();
if (isset($vid)) {
$table_mapping = $this
->getTableMapping();
foreach ($this->entityManager
->getFieldDefinitions($entity
->getEntityTypeId(), $entity
->bundle()) as $field_definition) {
$storage_definition = $field_definition
->getFieldStorageDefinition();
if (!$table_mapping
->requiresDedicatedTableStorage($storage_definition)) {
continue;
}
$revision_name = $table_mapping
->getDedicatedRevisionTableName($storage_definition);
$this->database
->delete($revision_name)
->condition('entity_id', $entity
->id())
->condition('revision_id', $vid)
->execute();
}
}
}
public function requiresEntityStorageSchemaChanges(EntityTypeInterface $entity_type, EntityTypeInterface $original) {
return $this
->getStorageSchema()
->requiresEntityStorageSchemaChanges($entity_type, $original);
}
public function requiresFieldStorageSchemaChanges(FieldStorageDefinitionInterface $storage_definition, FieldStorageDefinitionInterface $original) {
return $this
->getStorageSchema()
->requiresFieldStorageSchemaChanges($storage_definition, $original);
}
public function requiresEntityDataMigration(EntityTypeInterface $entity_type, EntityTypeInterface $original) {
return $this
->getStorageSchema()
->requiresEntityDataMigration($entity_type, $original);
}
public function requiresFieldDataMigration(FieldStorageDefinitionInterface $storage_definition, FieldStorageDefinitionInterface $original) {
return $this
->getStorageSchema()
->requiresFieldDataMigration($storage_definition, $original);
}
public function onEntityTypeCreate(EntityTypeInterface $entity_type) {
$this
->wrapSchemaException(function () use ($entity_type) {
$this
->getStorageSchema()
->onEntityTypeCreate($entity_type);
});
}
public function onEntityTypeUpdate(EntityTypeInterface $entity_type, EntityTypeInterface $original) {
$this->entityType = $entity_type;
$this
->initTableLayout();
$this
->wrapSchemaException(function () use ($entity_type, $original) {
$this
->getStorageSchema()
->onEntityTypeUpdate($entity_type, $original);
});
}
public function onEntityTypeDelete(EntityTypeInterface $entity_type) {
$this
->wrapSchemaException(function () use ($entity_type) {
$this
->getStorageSchema()
->onEntityTypeDelete($entity_type);
});
}
public function onFieldStorageDefinitionCreate(FieldStorageDefinitionInterface $storage_definition) {
if ($this
->getTableMapping()
->allowsSharedTableStorage($storage_definition)) {
$this->tableMapping = NULL;
}
$this
->wrapSchemaException(function () use ($storage_definition) {
$this
->getStorageSchema()
->onFieldStorageDefinitionCreate($storage_definition);
});
}
public function onFieldStorageDefinitionUpdate(FieldStorageDefinitionInterface $storage_definition, FieldStorageDefinitionInterface $original) {
$this
->wrapSchemaException(function () use ($storage_definition, $original) {
$this
->getStorageSchema()
->onFieldStorageDefinitionUpdate($storage_definition, $original);
});
}
public function onFieldStorageDefinitionDelete(FieldStorageDefinitionInterface $storage_definition) {
$table_mapping = $this
->getTableMapping($this->entityManager
->getLastInstalledFieldStorageDefinitions($this->entityType
->id()));
if ($storage_definition instanceof FieldStorageConfigInterface && $table_mapping
->requiresDedicatedTableStorage($storage_definition)) {
$table = $table_mapping
->getDedicatedDataTableName($storage_definition);
$revision_table = $table_mapping
->getDedicatedRevisionTableName($storage_definition);
$this->database
->update($table)
->fields(array(
'deleted' => 1,
))
->execute();
if ($this->entityType
->isRevisionable()) {
$this->database
->update($revision_table)
->fields(array(
'deleted' => 1,
))
->execute();
}
}
$this
->wrapSchemaException(function () use ($storage_definition) {
$this
->getStorageSchema()
->onFieldStorageDefinitionDelete($storage_definition);
});
}
protected function wrapSchemaException(callable $callback) {
$message = 'Exception thrown while performing a schema update.';
try {
$callback();
} catch (SchemaException $e) {
$message .= ' ' . $e
->getMessage();
throw new EntityStorageException($message, 0, $e);
} catch (DatabaseExceptionWrapper $e) {
$message .= ' ' . $e
->getMessage();
throw new EntityStorageException($message, 0, $e);
}
}
public function onFieldDefinitionDelete(FieldDefinitionInterface $field_definition) {
$table_mapping = $this
->getTableMapping();
$storage_definition = $field_definition
->getFieldStorageDefinition();
if ($table_mapping
->requiresDedicatedTableStorage($storage_definition)) {
$table_name = $table_mapping
->getDedicatedDataTableName($storage_definition);
$revision_name = $table_mapping
->getDedicatedRevisionTableName($storage_definition);
$this->database
->update($table_name)
->fields(array(
'deleted' => 1,
))
->condition('bundle', $field_definition
->getTargetBundle())
->execute();
if ($this->entityType
->isRevisionable()) {
$this->database
->update($revision_name)
->fields(array(
'deleted' => 1,
))
->condition('bundle', $field_definition
->getTargetBundle())
->execute();
}
}
}
public function onBundleCreate($bundle, $entity_type_id) {
}
public function onBundleDelete($bundle, $entity_type_id) {
}
protected function readFieldItemsToPurge(FieldDefinitionInterface $field_definition, $batch_size) {
$storage_definition = $field_definition
->getFieldStorageDefinition();
$is_deleted = $this
->storageDefinitionIsDeleted($storage_definition);
$table_mapping = $this
->getTableMapping();
$table_name = $table_mapping
->getDedicatedDataTableName($storage_definition, $is_deleted);
$entity_query = $this->database
->select($table_name, 't', array(
'fetch' => \PDO::FETCH_ASSOC,
));
$or = $entity_query
->orConditionGroup();
foreach ($storage_definition
->getColumns() as $column_name => $data) {
$or
->isNotNull($table_mapping
->getFieldColumnName($storage_definition, $column_name));
}
$entity_query
->distinct(TRUE)
->fields('t', array(
'entity_id',
))
->condition('bundle', $field_definition
->getTargetBundle())
->range(0, $batch_size);
$column_map = array();
foreach ($storage_definition
->getColumns() as $column_name => $data) {
$column_map[$table_mapping
->getFieldColumnName($storage_definition, $column_name)] = $column_name;
}
$entities = array();
$items_by_entity = array();
foreach ($entity_query
->execute() as $row) {
$item_query = $this->database
->select($table_name, 't', array(
'fetch' => \PDO::FETCH_ASSOC,
))
->fields('t')
->condition('entity_id', $row['entity_id'])
->orderBy('delta');
foreach ($item_query
->execute() as $item_row) {
if (!isset($entities[$item_row['revision_id']])) {
$item_row['entity_type'] = $this->entityTypeId;
$entities[$item_row['revision_id']] = _field_create_entity_from_ids((object) $item_row);
}
$item = array();
foreach ($column_map as $db_column => $field_column) {
$item[$field_column] = $item_row[$db_column];
}
$items_by_entity[$item_row['revision_id']][] = $item;
}
}
foreach ($items_by_entity as $revision_id => $values) {
$entity_adapter = $entities[$revision_id]
->getTypedData();
$items_by_entity[$revision_id] = \Drupal::typedDataManager()
->create($field_definition, $values, $field_definition
->getName(), $entity_adapter);
}
return $items_by_entity;
}
protected function purgeFieldItems(ContentEntityInterface $entity, FieldDefinitionInterface $field_definition) {
$storage_definition = $field_definition
->getFieldStorageDefinition();
$is_deleted = $this
->storageDefinitionIsDeleted($storage_definition);
$table_mapping = $this
->getTableMapping();
$table_name = $table_mapping
->getDedicatedDataTableName($storage_definition, $is_deleted);
$revision_name = $table_mapping
->getDedicatedRevisionTableName($storage_definition, $is_deleted);
$revision_id = $this->entityType
->isRevisionable() ? $entity
->getRevisionId() : $entity
->id();
$this->database
->delete($table_name)
->condition('revision_id', $revision_id)
->execute();
if ($this->entityType
->isRevisionable()) {
$this->database
->delete($revision_name)
->condition('revision_id', $revision_id)
->execute();
}
}
public function finalizePurge(FieldStorageDefinitionInterface $storage_definition) {
$this
->getStorageSchema()
->finalizePurge($storage_definition);
}
public function countFieldData($storage_definition, $as_bool = FALSE) {
$table_mapping = $this
->getTableMapping();
if ($table_mapping
->requiresDedicatedTableStorage($storage_definition)) {
$is_deleted = $this
->storageDefinitionIsDeleted($storage_definition);
if ($this->entityType
->isRevisionable()) {
$table_name = $table_mapping
->getDedicatedRevisionTableName($storage_definition, $is_deleted);
}
else {
$table_name = $table_mapping
->getDedicatedDataTableName($storage_definition, $is_deleted);
}
$query = $this->database
->select($table_name, 't');
$or = $query
->orConditionGroup();
foreach ($storage_definition
->getColumns() as $column_name => $data) {
$or
->isNotNull($table_mapping
->getFieldColumnName($storage_definition, $column_name));
}
$query
->condition($or);
if (!$as_bool) {
$query
->fields('t', array(
'entity_id',
))
->distinct(TRUE);
}
}
elseif ($table_mapping
->allowsSharedTableStorage($storage_definition)) {
$field_name = $storage_definition
->getName();
try {
$table_name = $table_mapping
->getFieldTableName($field_name);
} catch (SqlContentEntityStorageException $e) {
$table_name = $this->dataTable ?: $this->baseTable;
}
$query = $this->database
->select($table_name, 't');
$or = $query
->orConditionGroup();
foreach (array_keys($storage_definition
->getColumns()) as $property_name) {
$or
->isNotNull($table_mapping
->getFieldColumnName($storage_definition, $property_name));
}
$query
->condition($or);
if (!$as_bool) {
$query
->fields('t', array(
$this->idKey,
))
->distinct(TRUE);
}
}
$count = 0;
if (isset($query)) {
if ($as_bool) {
$query
->range(0, 1)
->addExpression('1');
}
else {
$query = $query
->countQuery();
}
$count = $query
->execute()
->fetchField();
}
return $as_bool ? (bool) $count : (int) $count;
}
protected function storageDefinitionIsDeleted(FieldStorageDefinitionInterface $storage_definition) {
return !array_key_exists($storage_definition
->getName(), $this->entityManager
->getLastInstalledFieldStorageDefinitions($this->entityTypeId));
}
}