Created
December 6, 2018 21:02
-
-
Save chx/6e9980849466107e728021140668b577 to your computer and use it in GitHub Desktop.
Plain table migration source plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Drupal\sd8_migration\Plugin\migrate\source; | |
use Drupal\migrate\Plugin\migrate\source\SqlBase; | |
/** | |
* Table source from database. | |
* | |
* @MigrateSource( | |
* id = "sd8_table", | |
* source_module = "sd8" | |
* ) | |
*/ | |
class Table extends SqlBase { | |
/** | |
* @return \Drupal\Core\Database\Query\SelectInterface | |
*/ | |
public function query() { | |
$query = $this->select($this->configuration['table'], 't') | |
->fields('t'); | |
foreach (array_keys($this->getIds()) as $id) { | |
$query->orderBy($id); | |
} | |
return $query; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function getIds() { | |
if (isset($this->configuration['ids'])) { | |
return $this->configuration['ids']; | |
} | |
/** @var \Drupal\Core\Database\Query\SelectInterface $query */ | |
$query = $this->select('INFORMATION_SCHEMA.KEY_COLUMN_USAGE', 'i') | |
->fields('i', ['COLUMN_NAME']) | |
->where('TABLE_SCHEMA = SCHEMA()') | |
->condition('TABLE_NAME ', $this->configuration['table']) | |
->condition('CONSTRAINT_NAME', 'PRIMARY'); | |
// JOINing in INFORMATION_SCHEMA is hideously slow. | |
foreach ($query->orderBy('ORDINAL_POSITION')->execute() as $result) { | |
$id = $result['COLUMN_NAME']; | |
$type = $this->select('INFORMATION_SCHEMA.COLUMNS', 'c') | |
->fields('c', ['DATA_TYPE']) | |
->where('TABLE_SCHEMA = SCHEMA()') | |
->condition('TABLE_NAME ', $this->configuration['table']) | |
->condition('COLUMN_NAME', $id) | |
->execute() | |
->fetchField(); | |
$ids[$id]['type'] = $type === 'int' ? 'integer' : 'string'; | |
$ids[$id]['alias'] = 't'; | |
} | |
return $ids; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function fields() { | |
return []; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment