View source
<?php
namespace Drupal\migrate\Plugin\migrate\id_map;
use Drupal\Component\Plugin\Attribute\PluginID;
use Drupal\Core\Database\DatabaseException;
use Drupal\Core\Database\DatabaseExceptionWrapper;
use Drupal\Core\Database\Exception\SchemaTableKeyTooLargeException;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\PluginBase;
use Drupal\migrate\MigrateMessage;
use Drupal\migrate\Audit\HighestIdInterface;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Event\MigrateIdMapMessageEvent;
use Drupal\migrate\MigrateException;
use Drupal\migrate\MigrateMessageInterface;
use Drupal\migrate\Plugin\MigrateIdMapInterface;
use Drupal\migrate\Plugin\MigrationPluginManagerInterface;
use Drupal\migrate\Row;
use Drupal\migrate\Event\MigrateEvents;
use Drupal\migrate\Event\MigrateMapSaveEvent;
use Drupal\migrate\Event\MigrateMapDeleteEvent;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
class Sql extends PluginBase implements MigrateIdMapInterface, ContainerFactoryPluginInterface, HighestIdInterface {
const SOURCE_IDS_HASH = 'source_ids_hash';
protected $eventDispatcher;
protected $mapTableName;
protected $messageTableName;
protected $message;
protected $database;
protected $query;
protected $migration;
protected $sourceIdFields;
protected $destinationIdFields;
protected $initialized;
protected $result;
protected $sourceIds = [];
protected $destinationIds = [];
protected $currentRow = NULL;
protected $currentKey = [];
protected $migrationPluginManager;
public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration, EventDispatcherInterface $event_dispatcher, MigrationPluginManagerInterface $migration_plugin_manager = NULL) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->migration = $migration;
$this->eventDispatcher = $event_dispatcher;
$this->message = new MigrateMessage();
if (!isset($this->database)) {
$this->database = \Drupal::database();
}
$machine_name = str_replace(':', '__', $this->migration
->id());
$prefix_length = strlen($this->database
->getPrefix());
$this->mapTableName = 'migrate_map_' . mb_strtolower($machine_name);
$this->mapTableName = mb_substr($this->mapTableName, 0, 63 - $prefix_length);
$this->messageTableName = 'migrate_message_' . mb_strtolower($machine_name);
$this->messageTableName = mb_substr($this->messageTableName, 0, 63 - $prefix_length);
if (!$migration_plugin_manager) {
@trigger_error('Calling Sql::__construct() without the $migration_manager argument is deprecated in drupal:9.5.0 and the $migration_manager argument will be required in drupal:11.0.0. See https://www.drupal.org/node/3277306', E_USER_DEPRECATED);
$migration_plugin_manager = \Drupal::service('plugin.manager.migration');
}
$this->migrationPluginManager = $migration_plugin_manager;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) {
return new static($configuration, $plugin_id, $plugin_definition, $migration, $container
->get('event_dispatcher'), $container
->get('plugin.manager.migration'));
}
public function getSourceIdsHash(array $source_id_values) {
if (!isset($source_id_values[0])) {
$source_id_values_keyed = [];
foreach ($this
->sourceIdFields() as $field_name => $source_id) {
$source_id_values_keyed[] = $source_id_values[$field_name];
}
$source_id_values = $source_id_values_keyed;
}
return hash('sha256', serialize(array_map('strval', $source_id_values)));
}
protected function sourceIdFields() {
if (!isset($this->sourceIdFields)) {
$this->sourceIdFields = [];
$count = 1;
foreach ($this->migration
->getSourcePlugin()
->getIds() as $field => $schema) {
$this->sourceIdFields[$field] = 'sourceid' . $count++;
}
}
return $this->sourceIdFields;
}
protected function destinationIdFields() {
if (!isset($this->destinationIdFields)) {
$this->destinationIdFields = [];
$count = 1;
foreach ($this->migration
->getDestinationPlugin()
->getIds() as $field => $schema) {
$this->destinationIdFields[$field] = 'destid' . $count++;
}
}
return $this->destinationIdFields;
}
public function mapTableName() {
return $this->mapTableName;
}
public function messageTableName() {
return $this->messageTableName;
}
public function getQualifiedMapTableName() {
return $this
->getDatabase()
->getFullQualifiedTableName($this->mapTableName);
}
public function getDatabase() {
$this
->init();
return $this->database;
}
protected function init() {
if (!$this->initialized) {
$this->initialized = TRUE;
$this
->ensureTables();
}
}
public function setMessage(MigrateMessageInterface $message) {
$this->message = $message;
}
protected function ensureTables() {
if (!$this
->getDatabase()
->schema()
->tableExists($this->mapTableName)) {
$count = 1;
$source_id_schema = [];
$indexes = [];
foreach ($this->migration
->getSourcePlugin()
->getIds() as $id_definition) {
$map_key = 'sourceid' . $count++;
$indexes['source'][] = $map_key;
$source_id_schema[$map_key] = $this
->getFieldSchema($id_definition);
$source_id_schema[$map_key]['not null'] = TRUE;
}
$source_ids_hash[$this::SOURCE_IDS_HASH] = [
'type' => 'varchar',
'length' => '64',
'not null' => TRUE,
'description' => 'Hash of source ids. Used as primary key',
];
$fields = $source_ids_hash + $source_id_schema;
$count = 1;
foreach ($this->migration
->getDestinationPlugin()
->getIds() as $id_definition) {
$map_key = 'destid' . $count++;
$fields[$map_key] = $this
->getFieldSchema($id_definition);
$fields[$map_key]['not null'] = FALSE;
}
$fields['source_row_status'] = [
'type' => 'int',
'size' => 'tiny',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => MigrateIdMapInterface::STATUS_IMPORTED,
'description' => 'Indicates current status of the source row',
];
$fields['rollback_action'] = [
'type' => 'int',
'size' => 'tiny',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => MigrateIdMapInterface::ROLLBACK_DELETE,
'description' => 'Flag indicating what to do for this item on rollback',
];
$fields['last_imported'] = [
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
'description' => 'UNIX timestamp of the last time this row was imported',
'size' => 'big',
];
$fields['hash'] = [
'type' => 'varchar',
'length' => '64',
'not null' => FALSE,
'description' => 'Hash of source row data, for detecting changes',
];
$chunk_size = count($source_id_schema);
while ($chunk_size >= 0) {
$indexes = [];
if ($chunk_size > 0) {
foreach (array_chunk(array_keys($source_id_schema), $chunk_size) as $key => $index_columns) {
$index_name = $key === 0 ? 'source' : "source{$key}";
$indexes[$index_name] = $index_columns;
}
}
$schema = [
'description' => 'Mappings from source identifier value(s) to destination identifier value(s).',
'fields' => $fields,
'primary key' => [
$this::SOURCE_IDS_HASH,
],
'indexes' => $indexes,
];
try {
$this
->getDatabase()
->schema()
->createTable($this->mapTableName, $schema);
break;
} catch (SchemaTableKeyTooLargeException $e) {
$chunk_size--;
if ($chunk_size <= 0) {
throw $e;
}
}
}
if (!$this
->getDatabase()
->schema()
->tableExists($this
->messageTableName())) {
$fields = [];
$fields['msgid'] = [
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
];
$fields += $source_ids_hash;
$fields['level'] = [
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 1,
];
$fields['message'] = [
'type' => 'text',
'size' => 'medium',
'not null' => TRUE,
];
$schema = [
'description' => 'Messages generated during a migration process',
'fields' => $fields,
'primary key' => [
'msgid',
],
'indexes' => [
$this::SOURCE_IDS_HASH => [
$this::SOURCE_IDS_HASH,
],
],
];
$this
->getDatabase()
->schema()
->createTable($this
->messageTableName(), $schema);
}
}
else {
if (!$this
->getDatabase()
->schema()
->fieldExists($this->mapTableName, 'rollback_action')) {
$this
->getDatabase()
->schema()
->addField($this->mapTableName, 'rollback_action', [
'type' => 'int',
'size' => 'tiny',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
'description' => 'Flag indicating what to do for this item on rollback',
]);
}
if (!$this
->getDatabase()
->schema()
->fieldExists($this->mapTableName, 'hash')) {
$this
->getDatabase()
->schema()
->addField($this->mapTableName, 'hash', [
'type' => 'varchar',
'length' => '64',
'not null' => FALSE,
'description' => 'Hash of source row data, for detecting changes',
]);
}
if (!$this
->getDatabase()
->schema()
->fieldExists($this->mapTableName, $this::SOURCE_IDS_HASH)) {
$this
->getDatabase()
->schema()
->addField($this->mapTableName, $this::SOURCE_IDS_HASH, [
'type' => 'varchar',
'length' => '64',
'not null' => TRUE,
'description' => 'Hash of source ids. Used as primary key',
]);
}
}
}
protected function getFieldSchema(array $id_definition) {
$type_parts = explode('.', $id_definition['type']);
if (count($type_parts) == 1) {
$type_parts[] = 'value';
}
unset($id_definition['type']);
$definition = BaseFieldDefinition::create($type_parts[0]);
$default_field_settings = $definition
->getSettings();
$field_settings = array_intersect_key($id_definition, $default_field_settings);
$custom_settings = array_diff_key($id_definition, $default_field_settings);
$schema = $definition
->setSettings($field_settings)
->getColumns()[$type_parts[1]];
return $schema + $custom_settings;
}
public function getRowBySource(array $source_id_values) {
$query = $this
->getDatabase()
->select($this
->mapTableName(), 'map')
->fields('map');
$query
->condition($this::SOURCE_IDS_HASH, $this
->getSourceIdsHash($source_id_values));
$result = $query
->execute();
return $result
->fetchAssoc();
}
public function getRowByDestination(array $destination_id_values) {
$query = $this
->getDatabase()
->select($this
->mapTableName(), 'map')
->fields('map');
foreach ($this
->destinationIdFields() as $field_name => $destination_id) {
if (!isset($destination_id_values[$field_name])) {
return [];
}
$query
->condition("map.{$destination_id}", $destination_id_values[$field_name], '=');
}
$result = $query
->execute()
->fetchAssoc();
return $result ? $result : [];
}
public function getRowsNeedingUpdate($count) {
$rows = [];
$result = $this
->getDatabase()
->select($this
->mapTableName(), 'map')
->fields('map')
->condition('source_row_status', MigrateIdMapInterface::STATUS_NEEDS_UPDATE)
->range(0, $count)
->execute();
foreach ($result as $row) {
$rows[] = $row;
}
return $rows;
}
public function lookupSourceId(array $destination_id_values) {
$source_id_fields = $this
->sourceIdFields();
$query = $this
->getDatabase()
->select($this
->mapTableName(), 'map');
$alias_map = [];
foreach ($source_id_fields as $source_field_name => $id_map_field_name) {
$alias = $query
->addField('map', $id_map_field_name);
$alias_map[$alias] = $source_field_name;
}
foreach ($this
->destinationIdFields() as $field_name => $destination_id) {
$query
->condition("map.{$destination_id}", $destination_id_values[$field_name], '=');
}
$result = $query
->execute()
->fetchAssoc() ?: [];
$source_ids = [];
foreach ($result as $alias => $id) {
$source_ids[$alias_map[$alias]] = $id;
}
return $source_ids;
}
public function lookupDestinationIds(array $source_id_values) {
if (empty($source_id_values)) {
return [];
}
$is_associative = !isset($source_id_values[0]);
$conditions = [];
foreach ($this
->sourceIdFields() as $field_name => $db_field) {
if ($is_associative) {
if (array_key_exists($field_name, $source_id_values)) {
if (isset($source_id_values[$field_name])) {
$conditions[$db_field] = $source_id_values[$field_name];
}
unset($source_id_values[$field_name]);
}
}
else {
if (empty($source_id_values)) {
break;
}
$conditions[$db_field] = array_shift($source_id_values);
}
}
if (!empty($source_id_values)) {
$var_dump = var_export($source_id_values, TRUE);
throw new MigrateException(sprintf("Extra unknown items for map %s in source IDs: %s", $this
->mapTableName(), $var_dump));
}
$query = $this
->getDatabase()
->select($this
->mapTableName(), 'map')
->fields('map', $this
->destinationIdFields());
if (count($this
->sourceIdFields()) === count($conditions)) {
$query
->condition($this::SOURCE_IDS_HASH, $this
->getSourceIdsHash(array_values($conditions)));
}
else {
foreach ($conditions as $db_field => $value) {
$query
->condition($db_field, $value);
}
}
try {
return $query
->execute()
->fetchAll(\PDO::FETCH_NUM);
} catch (DatabaseExceptionWrapper $e) {
return [];
}
}
public function saveIdMapping(Row $row, array $destination_id_values, $source_row_status = MigrateIdMapInterface::STATUS_IMPORTED, $rollback_action = MigrateIdMapInterface::ROLLBACK_DELETE) {
$source_id_values = $row
->getSourceIdValues();
$fields = [];
foreach ($this
->sourceIdFields() as $field_name => $key_name) {
if (!isset($source_id_values[$field_name])) {
$this->message
->display($this
->t('Did not save to map table due to NULL value for key field @field', [
'@field' => $field_name,
]), 'error');
return;
}
$fields[$key_name] = $source_id_values[$field_name];
}
if (!$fields) {
return;
}
$fields += [
'source_row_status' => (int) $source_row_status,
'rollback_action' => (int) $rollback_action,
'hash' => $row
->getHash(),
];
$count = 0;
foreach ($destination_id_values as $dest_id) {
$fields['destid' . ++$count] = $dest_id;
}
if ($count && $count != count($this
->destinationIdFields())) {
$this->message
->display($this
->t('Could not save to map table due to missing destination id values'), 'error');
return;
}
$fields['last_imported'] = time();
$this->eventDispatcher
->dispatch(new MigrateMapSaveEvent($this, $fields), MigrateEvents::MAP_SAVE);
$this
->getDatabase()
->merge($this
->mapTableName())
->key($this::SOURCE_IDS_HASH, $this
->getSourceIdsHash($source_id_values))
->fields($fields)
->execute();
}
public function saveMessage(array $source_id_values, $message, $level = MigrationInterface::MESSAGE_ERROR) {
foreach ($this
->sourceIdFields() as $field_name => $source_id) {
if (!isset($source_id_values[$field_name])) {
return;
}
}
$fields[$this::SOURCE_IDS_HASH] = $this
->getSourceIdsHash($source_id_values);
$fields['level'] = $level;
$fields['message'] = $message;
$this
->getDatabase()
->insert($this
->messageTableName())
->fields($fields)
->execute();
$this->eventDispatcher
->dispatch(new MigrateIdMapMessageEvent($this->migration, $source_id_values, $message, $level), MigrateEvents::IDMAP_MESSAGE);
}
public function getMessages(array $source_id_values = [], $level = NULL) {
$query = $this
->getDatabase()
->select($this
->messageTableName(), 'msg');
$condition = sprintf('[msg].[%s] = [map].[%s]', $this::SOURCE_IDS_HASH, $this::SOURCE_IDS_HASH);
$query
->addJoin('LEFT', $this
->mapTableName(), 'map', $condition);
foreach ($this
->sourceIdFields() as $id => $column_name) {
$query
->addField('map', $column_name, "src_{$id}");
}
foreach ($this
->destinationIdFields() as $id => $column_name) {
$query
->addField('map', $column_name, "dest_{$id}");
}
$query
->fields('msg', [
'msgid',
$this::SOURCE_IDS_HASH,
'level',
'message',
]);
if ($source_id_values) {
$query
->condition('msg.' . $this::SOURCE_IDS_HASH, $this
->getSourceIdsHash($source_id_values));
}
if ($level) {
$query
->condition('msg.level', $level);
}
return $query
->execute();
}
public function prepareUpdate() {
$this
->getDatabase()
->update($this
->mapTableName())
->fields([
'source_row_status' => MigrateIdMapInterface::STATUS_NEEDS_UPDATE,
])
->execute();
}
public function processedCount() {
return $this
->countHelper(NULL, $this
->mapTableName());
}
public function importedCount() {
return $this
->countHelper([
MigrateIdMapInterface::STATUS_IMPORTED,
MigrateIdMapInterface::STATUS_NEEDS_UPDATE,
]);
}
public function updateCount() {
return $this
->countHelper(MigrateIdMapInterface::STATUS_NEEDS_UPDATE);
}
public function errorCount() {
return $this
->countHelper(MigrateIdMapInterface::STATUS_FAILED);
}
public function messageCount() {
return $this
->countHelper(NULL, $this
->messageTableName());
}
protected function countHelper($status = NULL, $table = NULL) {
$query = $this->database
->select($table ?: $this
->mapTableName());
if (isset($status)) {
$query
->condition('source_row_status', $status, is_array($status) ? 'IN' : '=');
}
try {
$count = (int) $query
->countQuery()
->execute()
->fetchField();
} catch (DatabaseException $e) {
$count = 0;
}
return $count;
}
public function delete(array $source_id_values, $messages_only = FALSE) {
if (empty($source_id_values)) {
throw new MigrateException('Without source identifier values it is impossible to find the row to delete.');
}
if (!$messages_only) {
$map_query = $this
->getDatabase()
->delete($this
->mapTableName());
$map_query
->condition($this::SOURCE_IDS_HASH, $this
->getSourceIdsHash($source_id_values));
$this->eventDispatcher
->dispatch(new MigrateMapDeleteEvent($this, $source_id_values), MigrateEvents::MAP_DELETE);
$map_query
->execute();
}
$message_query = $this
->getDatabase()
->delete($this
->messageTableName());
$message_query
->condition($this::SOURCE_IDS_HASH, $this
->getSourceIdsHash($source_id_values));
$message_query
->execute();
}
public function deleteDestination(array $destination_id_values) {
$map_query = $this
->getDatabase()
->delete($this
->mapTableName());
$message_query = $this
->getDatabase()
->delete($this
->messageTableName());
$source_id_values = $this
->lookupSourceId($destination_id_values);
if (!empty($source_id_values)) {
foreach ($this
->destinationIdFields() as $field_name => $destination_id) {
$map_query
->condition($destination_id, $destination_id_values[$field_name]);
}
$this->eventDispatcher
->dispatch(new MigrateMapDeleteEvent($this, $source_id_values), MigrateEvents::MAP_DELETE);
$map_query
->execute();
$message_query
->condition($this::SOURCE_IDS_HASH, $this
->getSourceIdsHash($source_id_values));
$message_query
->execute();
}
}
public function setUpdate(array $source_id_values) {
if (empty($source_id_values)) {
throw new MigrateException('No source identifiers provided to update.');
}
$query = $this
->getDatabase()
->update($this
->mapTableName())
->fields([
'source_row_status' => MigrateIdMapInterface::STATUS_NEEDS_UPDATE,
]);
foreach ($this
->sourceIdFields() as $field_name => $source_id) {
$query
->condition($source_id, $source_id_values[$field_name]);
}
$query
->execute();
}
public function clearMessages() {
$this
->getDatabase()
->truncate($this
->messageTableName())
->execute();
}
public function destroy() {
$this
->getDatabase()
->schema()
->dropTable($this
->mapTableName());
$this
->getDatabase()
->schema()
->dropTable($this
->messageTableName());
}
public function rewind() {
$this->currentRow = NULL;
$fields = [];
foreach ($this
->sourceIdFields() as $field) {
$fields[] = $field;
}
foreach ($this
->destinationIdFields() as $field) {
$fields[] = $field;
}
$this->result = $this
->getDatabase()
->select($this
->mapTableName(), 'map')
->fields('map', $fields)
->orderBy('destid1')
->execute();
$this
->next();
}
public function current() {
return $this->currentRow;
}
public function key() {
return serialize($this->currentKey);
}
public function currentDestination() {
if ($this
->valid()) {
$result = [];
foreach ($this
->destinationIdFields() as $destination_field_name => $id_map_field_name) {
if (!is_null($this->currentRow[$id_map_field_name])) {
$result[$destination_field_name] = $this->currentRow[$id_map_field_name];
}
}
return $result;
}
else {
return NULL;
}
}
public function currentSource() {
if ($this
->valid()) {
$result = [];
foreach ($this
->sourceIdFields() as $field_name => $source_id) {
$result[$field_name] = $this->currentKey[$source_id];
}
return $result;
}
else {
return NULL;
}
}
public function next() {
$this->currentRow = $this->result
->fetchAssoc();
$this->currentKey = [];
if ($this->currentRow) {
foreach ($this
->sourceIdFields() as $map_field) {
$this->currentKey[$map_field] = $this->currentRow[$map_field];
unset($this->currentRow[$map_field]);
}
}
}
public function valid() {
return $this->currentRow !== FALSE;
}
protected function getMigrationPluginManager() {
@trigger_error(__METHOD__ . '() is deprecated in drupal:9.5.0 and is removed from drupal:11.0.0. Use $this->migrationPluginManager instead. See https://www.drupal.org/node/3277306', E_USER_DEPRECATED);
return $this->migrationPluginManager;
}
public function getHighestId() {
$keys = $this->migration
->getDestinationPlugin()
->getIds();
if (reset($keys)['type'] !== 'integer') {
throw new \LogicException('To determine the highest migrated ID the first ID must be an integer');
}
$map_tables = [
$this->migration
->id() => $this
->mapTableName(),
];
if ($base_id = substr($this->migration
->id(), 0, strpos($this->migration
->id(), $this::DERIVATIVE_SEPARATOR))) {
$migrations = $this->migrationPluginManager
->getDefinitions();
foreach ($migrations as $migration_id => $migration) {
if ($migration['id'] === $base_id) {
$stub = $this->migrationPluginManager
->createInstance($migration_id);
$map_tables[$migration_id] = $stub
->getIdMap()
->mapTableName();
}
}
}
$ids = [
0,
];
foreach ($map_tables as $map_table) {
if (!$this
->getDatabase()
->schema()
->tableExists($map_table)) {
continue;
}
$query = $this
->getDatabase()
->select($map_table, 'map')
->fields('map', $this
->destinationIdFields())
->range(0, 1);
foreach (array_values($this
->destinationIdFields()) as $order_field) {
$query
->orderBy($order_field, 'DESC');
}
$ids[] = $query
->execute()
->fetchField();
}
return (int) max($ids);
}
}