Newer
Older
Dries Buytaert
committed
<?php
namespace Drupal\migrate\Plugin\migrate\id_map;
use Drupal\Component\Utility\Unicode;
Alex Pott
committed
use Drupal\Core\Field\BaseFieldDefinition;
Angie Byron
committed
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
Dries Buytaert
committed
use Drupal\Core\Plugin\PluginBase;
use Drupal\migrate\Plugin\MigrationInterface;
Angie Byron
committed
use Drupal\migrate\Event\MigrateIdMapMessageEvent;
Dries Buytaert
committed
use Drupal\migrate\MigrateException;
use Drupal\migrate\MigrateMessageInterface;
use Drupal\migrate\Plugin\MigrateIdMapInterface;
use Drupal\migrate\Row;
Angie Byron
committed
use Drupal\migrate\Event\MigrateEvents;
use Drupal\migrate\Event\MigrateMapSaveEvent;
use Drupal\migrate\Event\MigrateMapDeleteEvent;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
Dries Buytaert
committed
/**
* Defines the sql based ID map implementation.
*
* It creates one map and one message table per migration entity to store the
* relevant information.
*
* @PluginID("sql")
*/
Angie Byron
committed
class Sql extends PluginBase implements MigrateIdMapInterface, ContainerFactoryPluginInterface {
Alex Pott
committed
/**
* Column name of hashed source id values.
*/
const SOURCE_IDS_HASH = 'source_ids_hash';
Angie Byron
committed
/**
* An event dispatcher instance to use for map events.
*
* @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
*/
protected $eventDispatcher;
Dries Buytaert
committed
/**
Dries Buytaert
committed
* The migration map table name.
Dries Buytaert
committed
*
* @var string
*/
Dries Buytaert
committed
protected $mapTableName;
/**
* The message table name.
*
* @var string
*/
protected $messageTableName;
Dries Buytaert
committed
/**
* The migrate message.
*
* @var \Drupal\migrate\MigrateMessageInterface
*/
protected $message;
/**
* The database connection for the map/message tables on the destination.
*
* @var \Drupal\Core\Database\Connection
*/
protected $database;
/**
* The select query.
*
Dries Buytaert
committed
* @var \Drupal\Core\Database\Query\SelectInterface
*/
protected $query;
/**
* The migration being done.
*
* @var \Drupal\migrate\Plugin\MigrationInterface
Dries Buytaert
committed
*/
protected $migration;
/**
* The source ID fields.
*
* @var array
*/
protected $sourceIdFields;
/**
* The destination ID fields.
*
* @var array
*/
protected $destinationIdFields;
/**
Dries Buytaert
committed
* Whether the plugin is already initialized.
Dries Buytaert
committed
*
* @var bool
Dries Buytaert
committed
*/
Dries Buytaert
committed
protected $initialized;
Dries Buytaert
committed
/**
* The result.
*
* @var null
*/
protected $result = NULL;
Dries Buytaert
committed
/**
* The source identifiers.
*
* @var array
*/
protected $sourceIds = [];
Dries Buytaert
committed
/**
* The destination identifiers.
*
* @var array
*/
protected $destinationIds = [];
Dries Buytaert
committed
Dries Buytaert
committed
/**
* The current row.
*
* @var null
*/
protected $currentRow = NULL;
/**
* The current key.
*
* @var array
*/
protected $currentKey = [];
Dries Buytaert
committed
/**
* Constructs an SQL object.
*
* Sets up the tables and builds the maps,
*
* @param array $configuration
* The configuration.
* @param string $plugin_id
* The plugin ID for the migration process to do.
* @param mixed $plugin_definition
Dries Buytaert
committed
* The configuration for the plugin.
* @param \Drupal\migrate\Plugin\MigrationInterface $migration
Dries Buytaert
committed
* The migration to do.
*/
Angie Byron
committed
public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration, EventDispatcherInterface $event_dispatcher) {
Dries Buytaert
committed
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->migration = $migration;
Angie Byron
committed
$this->eventDispatcher = $event_dispatcher;
}
/**
* {@inheritdoc}
*/
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')
);
Dries Buytaert
committed
}
Alex Pott
committed
/**
* Retrieves the hash of the source identifier values.
*
Gabor Hojtsy
committed
* @internal
Alex Pott
committed
*
* @param array $source_id_values
* The source identifiers
*
* @return string
* An hash containing the hashed values of the source identifiers.
*/
public function getSourceIDsHash(array $source_id_values) {
// When looking up the destination ID we require an array with both the
// source key and value, e.g. ['nid' => 41]. In this case, $source_id_values
// need to be ordered the same order as $this->sourceIdFields().
// However, the Migration process plugin doesn't currently have a way to get
// the source key so we presume the values have been passed through in the
// correct order.
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)));
}
Dries Buytaert
committed
/**
* The source ID fields.
*
* @return array
* The source ID fields.
*/
protected function sourceIdFields() {
if (!isset($this->sourceIdFields)) {
// Build the source and destination identifier maps.
$this->sourceIdFields = [];
Dries Buytaert
committed
$count = 1;
foreach ($this->migration->getSourcePlugin()->getIds() as $field => $schema) {
$this->sourceIdFields[$field] = 'sourceid' . $count++;
}
Dries Buytaert
committed
}
Dries Buytaert
committed
return $this->sourceIdFields;
}
/**
* The destination ID fields.
*
* @return array
* The destination ID fields.
*/
protected function destinationIdFields() {
if (!isset($this->destinationIdFields)) {
$this->destinationIdFields = [];
Dries Buytaert
committed
$count = 1;
foreach ($this->migration->getDestinationPlugin()->getIds() as $field => $schema) {
$this->destinationIdFields[$field] = 'destid' . $count++;
}
Dries Buytaert
committed
}
Dries Buytaert
committed
return $this->destinationIdFields;
Dries Buytaert
committed
}
/**
* The name of the database map table.
*
* @return string
Dries Buytaert
committed
* The map table name.
Dries Buytaert
committed
public function mapTableName() {
$this->init();
return $this->mapTableName;
}
/**
* The name of the database message table.
*
* @return string
Dries Buytaert
committed
* The message table name.
Dries Buytaert
committed
public function messageTableName() {
$this->init();
return $this->messageTableName;
}
Dries Buytaert
committed
/**
Dries Buytaert
committed
* Get the fully qualified map table name.
Dries Buytaert
committed
*
* @return string
Dries Buytaert
committed
* The fully qualified map table name.
Dries Buytaert
committed
*/
public function getQualifiedMapTableName() {
Alex Pott
committed
return $this->getDatabase()->getFullQualifiedTableName($this->mapTableName);
Dries Buytaert
committed
}
/**
* Gets the database connection.
*
* @return \Drupal\Core\Database\Connection
Dries Buytaert
committed
* The database connection object.
Dries Buytaert
committed
*/
public function getDatabase() {
Dries Buytaert
committed
if (!isset($this->database)) {
Dries Buytaert
committed
$this->database = \Drupal::database();
Dries Buytaert
committed
}
Dries Buytaert
committed
$this->init();
Dries Buytaert
committed
return $this->database;
}
Dries Buytaert
committed
/**
* Initialize the plugin.
*/
protected function init() {
if (!$this->initialized) {
$this->initialized = TRUE;
// Default generated table names, limited to 63 characters.
$machine_name = str_replace(':', '__', $this->migration->id());
$prefix_length = strlen($this->getDatabase()->tablePrefix());
$this->mapTableName = 'migrate_map_' . Unicode::strtolower($machine_name);
$this->mapTableName = Unicode::substr($this->mapTableName, 0, 63 - $prefix_length);
$this->messageTableName = 'migrate_message_' . Unicode::strtolower($machine_name);
$this->messageTableName = Unicode::substr($this->messageTableName, 0, 63 - $prefix_length);
$this->ensureTables();
}
}
Dries Buytaert
committed
/**
* {@inheritdoc}
*/
public function setMessage(MigrateMessageInterface $message) {
$this->message = $message;
}
/**
* Create the map and message tables if they don't already exist.
*/
protected function ensureTables() {
Dries Buytaert
committed
if (!$this->getDatabase()->schema()->tableExists($this->mapTableName)) {
// Generate appropriate schema info for the map and message tables,
// and map from the source field names to the map/msg field names.
$count = 1;
$source_id_schema = [];
$indexes = [];
Dries Buytaert
committed
foreach ($this->migration->getSourcePlugin()->getIds() as $id_definition) {
$mapkey = 'sourceid' . $count++;
$indexes['source'][] = $mapkey;
Dries Buytaert
committed
$source_id_schema[$mapkey] = $this->getFieldSchema($id_definition);
$source_id_schema[$mapkey]['not null'] = TRUE;
Dries Buytaert
committed
}
Dries Buytaert
committed
$source_ids_hash[static::SOURCE_IDS_HASH] = [
Alex Pott
committed
'type' => 'varchar',
'length' => '64',
'not null' => TRUE,
'description' => 'Hash of source ids. Used as primary key',
];
Alex Pott
committed
$fields = $source_ids_hash + $source_id_schema;
Dries Buytaert
committed
Dries Buytaert
committed
// Add destination identifiers to map table.
catch
committed
// @todo How do we discover the destination schema?
Dries Buytaert
committed
$count = 1;
foreach ($this->migration->getDestinationPlugin()->getIds() as $id_definition) {
Alex Pott
committed
// Allow dest identifier fields to be NULL (for IGNORED/FAILED cases).
Dries Buytaert
committed
$mapkey = 'destid' . $count++;
$fields[$mapkey] = $this->getFieldSchema($id_definition);
$fields[$mapkey]['not null'] = FALSE;
}
$fields['source_row_status'] = [
Dries Buytaert
committed
'type' => 'int',
'size' => 'tiny',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => MigrateIdMapInterface::STATUS_IMPORTED,
'description' => 'Indicates current status of the source row',
];
$fields['rollback_action'] = [
Dries Buytaert
committed
'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'] = [
Dries Buytaert
committed
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
'description' => 'UNIX timestamp of the last time this row was imported',
];
$fields['hash'] = [
Dries Buytaert
committed
'type' => 'varchar',
'length' => '64',
'not null' => FALSE,
'description' => 'Hash of source row data, for detecting changes',
];
$schema = [
Dries Buytaert
committed
'description' => 'Mappings from source identifier value(s) to destination identifier value(s).',
'fields' => $fields,
'primary key' => [static::SOURCE_IDS_HASH],
'indexes' => $indexes,
];
Dries Buytaert
committed
$this->getDatabase()->schema()->createTable($this->mapTableName, $schema);
// Now do the message table.
if (!$this->getDatabase()->schema()->tableExists($this->messageTableName())) {
$fields = [];
$fields['msgid'] = [
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
];
Alex Pott
committed
$fields += $source_ids_hash;
Dries Buytaert
committed
$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'],
];
$this->getDatabase()->schema()->createTable($this->messageTableName(), $schema);
Dries Buytaert
committed
}
}
else {
// Add any missing columns to the map table.
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',
]
);
Dries Buytaert
committed
}
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',
]
);
Dries Buytaert
committed
}
Alex Pott
committed
if (!$this->getDatabase()->schema()->fieldExists($this->mapTableName, static::SOURCE_IDS_HASH)) {
$this->getDatabase()->schema()->addField($this->mapTableName, static::SOURCE_IDS_HASH, [
Alex Pott
committed
'type' => 'varchar',
'length' => '64',
'not null' => TRUE,
'description' => 'Hash of source ids. Used as primary key',
]);
Alex Pott
committed
}
Dries Buytaert
committed
}
}
Dries Buytaert
committed
/**
catch
committed
* Creates schema from an ID definition.
Dries Buytaert
committed
*
* @param array $id_definition
* The definition of the field having the structure as the items returned by
* MigrateSourceInterface or MigrateDestinationInterface::getIds().
catch
committed
*
Dries Buytaert
committed
* @return array
* The database schema definition.
*
* @see \Drupal\migrate\Plugin\MigrateSourceInterface::getIds()
* @see \Drupal\migrate\Plugin\MigrateDestinationInterface::getIds()
Dries Buytaert
committed
*/
protected function getFieldSchema(array $id_definition) {
$type_parts = explode('.', $id_definition['type']);
if (count($type_parts) == 1) {
$type_parts[] = 'value';
}
unset($id_definition['type']);
// Get the field storage definition.
$definition = BaseFieldDefinition::create($type_parts[0]);
// Get a list of setting keys belonging strictly to the field definition.
$default_field_settings = $definition->getSettings();
// Separate field definition settings from custom settings. Custom settings
// are settings passed in $id_definition that are not part of field storage
// definition settings.
$field_settings = array_intersect_key($id_definition, $default_field_settings);
$custom_settings = array_diff_key($id_definition, $default_field_settings);
// Resolve schema from field storage definition settings.
$schema = $definition
->setSettings($field_settings)
->getColumns()[$type_parts[1]];
// Merge back custom settings.
return $schema + $custom_settings;
Dries Buytaert
committed
}
Dries Buytaert
committed
/**
* {@inheritdoc}
*/
public function getRowBySource(array $source_id_values) {
Dries Buytaert
committed
$query = $this->getDatabase()->select($this->mapTableName(), 'map')
Alex Pott
committed
->fields('map');
Alex Pott
committed
$query->condition(static::SOURCE_IDS_HASH, $this->getSourceIDsHash($source_id_values));
Dries Buytaert
committed
$result = $query->execute();
return $result->fetchAssoc();
}
/**
* {@inheritdoc}
*/
public function getRowByDestination(array $destination_id_values) {
Dries Buytaert
committed
$query = $this->getDatabase()->select($this->mapTableName(), 'map')
Alex Pott
committed
->fields('map');
Angie Byron
committed
foreach ($this->destinationIdFields() as $field_name => $destination_id) {
$query->condition("map.$destination_id", $destination_id_values[$field_name], '=');
Dries Buytaert
committed
}
$result = $query->execute();
return $result->fetchAssoc();
}
/**
* {@inheritdoc}
*/
public function getRowsNeedingUpdate($count) {
$rows = [];
Dries Buytaert
committed
$result = $this->getDatabase()->select($this->mapTableName(), 'map')
Alex Pott
committed
->fields('map')
->condition('source_row_status', MigrateIdMapInterface::STATUS_NEEDS_UPDATE)
->range(0, $count)
->execute();
Dries Buytaert
committed
foreach ($result as $row) {
$rows[] = $row;
}
return $rows;
}
/**
* {@inheritdoc}
*/
Angie Byron
committed
public function lookupSourceID(array $destination_id_values) {
$source_id_fields = $this->sourceIdFields();
$query = $this->getDatabase()->select($this->mapTableName(), 'map');
foreach ($source_id_fields as $source_field_name => $idmap_field_name) {
$query->addField('map', $idmap_field_name, $source_field_name);
}
foreach ($this->destinationIdFields() as $field_name => $destination_id) {
$query->condition("map.$destination_id", $destination_id_values[$field_name], '=');
Dries Buytaert
committed
}
$result = $query->execute();
Angie Byron
committed
return $result->fetchAssoc() ?: [];
Dries Buytaert
committed
}
/**
* {@inheritdoc}
*/
Angie Byron
committed
public function lookupDestinationId(array $source_id_values) {
Alex Pott
committed
$results = $this->lookupDestinationIds($source_id_values);
return $results ? reset($results) : [];
Alex Pott
committed
}
/**
* {@inheritdoc}
*/
public function lookupDestinationIds(array $source_id_values) {
Angie Byron
committed
if (empty($source_id_values)) {
return [];
Dries Buytaert
committed
}
Alex Pott
committed
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
// Canonicalize the keys into a hash of DB-field => value.
$is_associative = !isset($source_id_values[0]);
$conditions = [];
foreach ($this->sourceIdFields() as $field_name => $db_field) {
if ($is_associative) {
// Associative $source_id_values can have fields out of order.
if (isset($source_id_values[$field_name])) {
$conditions[$db_field] = $source_id_values[$field_name];
unset($source_id_values[$field_name]);
}
}
else {
// For non-associative $source_id_values, we assume they're the first
// few fields.
if (empty($source_id_values)) {
break;
}
$conditions[$db_field] = array_shift($source_id_values);
}
}
if (!empty($source_id_values)) {
throw new MigrateException("Extra unknown items in source IDs");
}
Dries Buytaert
committed
$query = $this->getDatabase()->select($this->mapTableName(), 'map')
Alex Pott
committed
->fields('map', $this->destinationIdFields());
if (count($this->sourceIdFields()) === count($conditions)) {
// Optimization: Use the primary key.
$query->condition(self::SOURCE_IDS_HASH, $this->getSourceIDsHash(array_values($conditions)));
}
else {
foreach ($conditions as $db_field => $value) {
$query->condition($db_field, $value);
}
}
Angie Byron
committed
Alex Pott
committed
return $query->execute()->fetchAll(\PDO::FETCH_NUM);
Dries Buytaert
committed
}
/**
* {@inheritdoc}
*/
public function saveIdMapping(Row $row, array $destination_id_values, $source_row_status = MigrateIdMapInterface::STATUS_IMPORTED, $rollback_action = MigrateIdMapInterface::ROLLBACK_DELETE) {
Dries Buytaert
committed
// Construct the source key.
$source_id_values = $row->getSourceIdValues();
// Construct the source key and initialize to empty variable keys.
Alex Pott
committed
$fields = [];
Dries Buytaert
committed
foreach ($this->sourceIdFields() as $field_name => $key_name) {
Alex Pott
committed
// A NULL key value is usually an indication of a problem.
Dries Buytaert
committed
if (!isset($source_id_values[$field_name])) {
Alex Pott
committed
$this->message->display($this->t(
'Did not save to map table due to NULL value for key field @field',
['@field' => $field_name]), 'error');
Dries Buytaert
committed
return;
}
Alex Pott
committed
$fields[$key_name] = $source_id_values[$field_name];
}
if (!$fields) {
return;
Dries Buytaert
committed
}
$fields += [
'source_row_status' => (int) $source_row_status,
Dries Buytaert
committed
'rollback_action' => (int) $rollback_action,
'hash' => $row->getHash(),
];
Dries Buytaert
committed
$count = 0;
Dries Buytaert
committed
foreach ($destination_id_values as $dest_id) {
Dries Buytaert
committed
$fields['destid' . ++$count] = $dest_id;
}
if ($count && $count != count($this->destinationIdFields())) {
$this->message->display(t('Could not save to map table due to missing destination id values'), 'error');
return;
Dries Buytaert
committed
}
if ($this->migration->getTrackLastImported()) {
Dries Buytaert
committed
$fields['last_imported'] = time();
}
Alex Pott
committed
$keys = [static::SOURCE_IDS_HASH => $this->getSourceIDsHash($source_id_values)];
// Notify anyone listening of the map row we're about to save.
$this->eventDispatcher->dispatch(MigrateEvents::MAP_SAVE, new MigrateMapSaveEvent($this, $fields));
$this->getDatabase()->merge($this->mapTableName())
->key($keys)
->fields($fields)
->execute();
Dries Buytaert
committed
}
/**
* {@inheritdoc}
*/
public function saveMessage(array $source_id_values, $message, $level = MigrationInterface::MESSAGE_ERROR) {
Angie Byron
committed
foreach ($this->sourceIdFields() as $field_name => $source_id) {
catch
committed
// If any key value is not set, we can't save.
Angie Byron
committed
if (!isset($source_id_values[$field_name])) {
Dries Buytaert
committed
return;
}
}
Alex Pott
committed
$fields[static::SOURCE_IDS_HASH] = $this->getSourceIDsHash($source_id_values);
Dries Buytaert
committed
$fields['level'] = $level;
$fields['message'] = $message;
Dries Buytaert
committed
$this->getDatabase()->insert($this->messageTableName())
Dries Buytaert
committed
->fields($fields)
->execute();
Angie Byron
committed
// Notify anyone listening of the message we've saved.
$this->eventDispatcher->dispatch(MigrateEvents::IDMAP_MESSAGE,
new MigrateIdMapMessageEvent($this->migration, $source_id_values, $message, $level));
Dries Buytaert
committed
}
Angie Byron
committed
/**
* {@inheritdoc}
*/
public function getMessageIterator(array $source_id_values = [], $level = NULL) {
$query = $this->getDatabase()->select($this->messageTableName(), 'msg')
->fields('msg');
Alex Pott
committed
if ($source_id_values) {
$query->condition(static::SOURCE_IDS_HASH, $this->getSourceIDsHash($source_id_values));
Angie Byron
committed
}
Angie Byron
committed
Angie Byron
committed
if ($level) {
$query->condition('level', $level);
}
return $query->execute();
}
Dries Buytaert
committed
/**
* {@inheritdoc}
*/
public function prepareUpdate() {
Dries Buytaert
committed
$this->getDatabase()->update($this->mapTableName())
->fields(['source_row_status' => MigrateIdMapInterface::STATUS_NEEDS_UPDATE])
->execute();
Dries Buytaert
committed
}
/**
* {@inheritdoc}
*/
public function processedCount() {
Dries Buytaert
committed
return $this->getDatabase()->select($this->mapTableName())
Dries Buytaert
committed
->countQuery()
->execute()
->fetchField();
}
/**
* {@inheritdoc}
*/
public function importedCount() {
Dries Buytaert
committed
return $this->getDatabase()->select($this->mapTableName())
->condition('source_row_status', [MigrateIdMapInterface::STATUS_IMPORTED, MigrateIdMapInterface::STATUS_NEEDS_UPDATE], 'IN')
Dries Buytaert
committed
->countQuery()
->execute()
->fetchField();
}
/**
* {@inheritdoc}
*/
public function updateCount() {
return $this->countHelper(MigrateIdMapInterface::STATUS_NEEDS_UPDATE);
}
/**
* {@inheritdoc}
*/
public function errorCount() {
return $this->countHelper(MigrateIdMapInterface::STATUS_FAILED);
}
/**
* {@inheritdoc}
*/
public function messageCount() {
Dries Buytaert
committed
return $this->countHelper(NULL, $this->messageTableName());
Dries Buytaert
committed
}
/**
* Counts records in a table.
*
* @param int $status
* An integer for the source_row_status column.
* @param string $table
* (optional) The table to work. Defaults to NULL.
*
Dries Buytaert
committed
* @return int
* The number of records.
*/
protected function countHelper($status, $table = NULL) {
Dries Buytaert
committed
$query = $this->getDatabase()->select($table ?: $this->mapTableName());
Dries Buytaert
committed
if (isset($status)) {
$query->condition('source_row_status', $status);
Dries Buytaert
committed
}
return $query->countQuery()->execute()->fetchField();
}
/**
* {@inheritdoc}
*/
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) {
Alex Pott
committed
$map_query = $this->getDatabase()->delete($this->mapTableName());
$map_query->condition(static::SOURCE_IDS_HASH, $this->getSourceIDsHash($source_id_values));
Angie Byron
committed
// Notify anyone listening of the map row we're about to delete.
$this->eventDispatcher->dispatch(MigrateEvents::MAP_DELETE, new MigrateMapDeleteEvent($this, $source_id_values));
Dries Buytaert
committed
$map_query->execute();
}
Alex Pott
committed
$message_query = $this->getDatabase()->delete($this->messageTableName());
$message_query->condition(static::SOURCE_IDS_HASH, $this->getSourceIDsHash($source_id_values));
Dries Buytaert
committed
$message_query->execute();
}
/**
* {@inheritdoc}
*/
Angie Byron
committed
public function deleteDestination(array $destination_id_values) {
Dries Buytaert
committed
$map_query = $this->getDatabase()->delete($this->mapTableName());
$message_query = $this->getDatabase()->delete($this->messageTableName());
Angie Byron
committed
$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]);
Dries Buytaert
committed
}
Angie Byron
committed
// Notify anyone listening of the map row we're about to delete.
Angie Byron
committed
$this->eventDispatcher->dispatch(MigrateEvents::MAP_DELETE, new MigrateMapDeleteEvent($this, $source_id_values));
Dries Buytaert
committed
$map_query->execute();
Alex Pott
committed
$message_query->condition(static::SOURCE_IDS_HASH, $this->getSourceIDsHash($source_id_values));
Dries Buytaert
committed
$message_query->execute();
}
}
/**
* {@inheritdoc}
*/
Angie Byron
committed
public function setUpdate(array $source_id_values) {
if (empty($source_id_values)) {
Dries Buytaert
committed
throw new MigrateException('No source identifiers provided to update.');
}
$query = $this->getDatabase()
Dries Buytaert
committed
->update($this->mapTableName())
->fields(['source_row_status' => MigrateIdMapInterface::STATUS_NEEDS_UPDATE]);
Dries Buytaert
committed
Angie Byron
committed
foreach ($this->sourceIdFields() as $field_name => $source_id) {
$query->condition($source_id, $source_id_values[$field_name]);
Dries Buytaert
committed
}
Angie Byron
committed
$query->execute();
Dries Buytaert
committed
}
/**
* {@inheritdoc}
*/
public function clearMessages() {
Dries Buytaert
committed
$this->getDatabase()->truncate($this->messageTableName())->execute();
Dries Buytaert
committed
}
/**
* {@inheritdoc}
*/
public function destroy() {
Dries Buytaert
committed
$this->getDatabase()->schema()->dropTable($this->mapTableName());
$this->getDatabase()->schema()->dropTable($this->messageTableName());
Dries Buytaert
committed
}
/**
* Implementation of \Iterator::rewind().
Dries Buytaert
committed
*
* This is called before beginning a foreach loop.
*/
public function rewind() {
$this->currentRow = NULL;
$fields = [];
Dries Buytaert
committed
foreach ($this->sourceIdFields() as $field) {
Dries Buytaert
committed
$fields[] = $field;
}
Dries Buytaert
committed
foreach ($this->destinationIdFields() as $field) {
Dries Buytaert
committed
$fields[] = $field;
}
Dries Buytaert
committed
$this->result = $this->getDatabase()->select($this->mapTableName(), 'map')
Dries Buytaert
committed
->fields('map', $fields)
Alex Pott
committed
->orderBy('destid1')
Dries Buytaert
committed
->execute();
$this->next();
}
/**
* Implementation of \Iterator::current().
Dries Buytaert
committed
*
* This is called when entering a loop iteration, returning the current row.
*/
public function current() {
return $this->currentRow;
}
/**
* Implementation of \Iterator::key().
Dries Buytaert
committed
*
* This is called when entering a loop iteration, returning the key of the
* current row. It must be a scalar - we will serialize to fulfill the
* requirement, but using getCurrentKey() is preferable.
*/
public function key() {
return serialize($this->currentKey);
}
Angie Byron
committed
/**
Jennifer Hodgdon
committed
* {@inheritdoc}
Angie Byron
committed
*/
public function currentDestination() {
if ($this->valid()) {
$result = [];
Angie Byron
committed
foreach ($this->destinationIdFields() as $destination_field_name => $idmap_field_name) {
Alex Pott
committed
if (!is_null($this->currentRow[$idmap_field_name])) {
$result[$destination_field_name] = $this->currentRow[$idmap_field_name];
}
}
return $result;
}
else {
return NULL;
}
}
/**
* @inheritdoc
*/
public function currentSource() {
if ($this->valid()) {
$result = [];
Alex Pott
committed
foreach ($this->sourceIdFields() as $field_name => $source_id) {
$result[$field_name] = $this->currentKey[$source_id];
Angie Byron
committed
}
return $result;
}
else {
return NULL;
}
}
Dries Buytaert
committed
/**
* Implementation of \Iterator::next().
Dries Buytaert
committed
*
* This is called at the bottom of the loop implicitly, as well as explicitly
* from rewind().
*/
public function next() {
catch
committed
$this->currentRow = $this->result->fetchAssoc();
$this->currentKey = [];
catch
committed
if ($this->currentRow) {
Dries Buytaert
committed
foreach ($this->sourceIdFields() as $map_field) {
catch
committed
$this->currentKey[$map_field] = $this->currentRow[$map_field];
Dries Buytaert
committed
// Leave only destination fields.
catch
committed
unset($this->currentRow[$map_field]);
Dries Buytaert
committed
}
}
}
/**
* Implementation of \Iterator::valid().
Dries Buytaert
committed
*
* This is called at the top of the loop, returning TRUE to process the loop
* and FALSE to terminate it.
*/
public function valid() {
catch
committed
return $this->currentRow !== FALSE;