123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618 |
- <?php
- namespace yii\console\controllers;
- use Yii;
- use yii\db\Connection;
- use yii\db\Query;
- use yii\di\Instance;
- use yii\helpers\ArrayHelper;
- use yii\helpers\Console;
- use yii\helpers\Inflector;
- class MigrateController extends BaseMigrateController
- {
-
- const MAX_NAME_LENGTH = 180;
-
- public $migrationTable = '{{%migration}}';
-
- public $templateFile = '@yii/views/migration.php';
-
- public $generatorTemplateFiles = [
- 'create_table' => '@yii/views/createTableMigration.php',
- 'drop_table' => '@yii/views/dropTableMigration.php',
- 'add_column' => '@yii/views/addColumnMigration.php',
- 'drop_column' => '@yii/views/dropColumnMigration.php',
- 'create_junction' => '@yii/views/createTableMigration.php',
- ];
-
- public $useTablePrefix = true;
-
- public $fields = [];
-
- public $db = 'db';
-
- public $comment = '';
-
- public function options($actionID)
- {
- return array_merge(
- parent::options($actionID),
- ['migrationTable', 'db'],
- $actionID === 'create'
- ? ['templateFile', 'fields', 'useTablePrefix', 'comment']
- : []
- );
- }
-
- public function optionAliases()
- {
- return array_merge(parent::optionAliases(), [
- 'C' => 'comment',
- 'f' => 'fields',
- 'p' => 'migrationPath',
- 't' => 'migrationTable',
- 'F' => 'templateFile',
- 'P' => 'useTablePrefix',
- 'c' => 'compact',
- ]);
- }
-
- public function beforeAction($action)
- {
- if (parent::beforeAction($action)) {
- $this->db = Instance::ensure($this->db, Connection::className());
- return true;
- }
- return false;
- }
-
- protected function createMigration($class)
- {
- $this->includeMigrationFile($class);
- return Yii::createObject([
- 'class' => $class,
- 'db' => $this->db,
- 'compact' => $this->compact,
- ]);
- }
-
- protected function getMigrationHistory($limit)
- {
- if ($this->db->schema->getTableSchema($this->migrationTable, true) === null) {
- $this->createMigrationHistoryTable();
- }
- $query = (new Query())
- ->select(['version', 'apply_time'])
- ->from($this->migrationTable)
- ->orderBy(['apply_time' => SORT_DESC, 'version' => SORT_DESC]);
- if (empty($this->migrationNamespaces)) {
- $query->limit($limit);
- $rows = $query->all($this->db);
- $history = ArrayHelper::map($rows, 'version', 'apply_time');
- unset($history[self::BASE_MIGRATION]);
- return $history;
- }
- $rows = $query->all($this->db);
- $history = [];
- foreach ($rows as $key => $row) {
- if ($row['version'] === self::BASE_MIGRATION) {
- continue;
- }
- if (preg_match('/m?(\d{6}_?\d{6})(\D.*)?$/is', $row['version'], $matches)) {
- $time = str_replace('_', '', $matches[1]);
- $row['canonicalVersion'] = $time;
- } else {
- $row['canonicalVersion'] = $row['version'];
- }
- $row['apply_time'] = (int) $row['apply_time'];
- $history[] = $row;
- }
- usort($history, function ($a, $b) {
- if ($a['apply_time'] === $b['apply_time']) {
- if (($compareResult = strcasecmp($b['canonicalVersion'], $a['canonicalVersion'])) !== 0) {
- return $compareResult;
- }
- return strcasecmp($b['version'], $a['version']);
- }
- return ($a['apply_time'] > $b['apply_time']) ? -1 : +1;
- });
- $history = array_slice($history, 0, $limit);
- $history = ArrayHelper::map($history, 'version', 'apply_time');
- return $history;
- }
-
- protected function createMigrationHistoryTable()
- {
- $tableName = $this->db->schema->getRawTableName($this->migrationTable);
- $this->stdout("Creating migration history table \"$tableName\"...", Console::FG_YELLOW);
- $this->db->createCommand()->createTable($this->migrationTable, [
- 'version' => 'varchar(' . static::MAX_NAME_LENGTH . ') NOT NULL PRIMARY KEY',
- 'apply_time' => 'integer',
- ])->execute();
- $this->db->createCommand()->insert($this->migrationTable, [
- 'version' => self::BASE_MIGRATION,
- 'apply_time' => time(),
- ])->execute();
- $this->stdout("Done.\n", Console::FG_GREEN);
- }
-
- protected function addMigrationHistory($version)
- {
- $command = $this->db->createCommand();
- $command->insert($this->migrationTable, [
- 'version' => $version,
- 'apply_time' => time(),
- ])->execute();
- }
-
- protected function truncateDatabase()
- {
- $db = $this->db;
- $schemas = $db->schema->getTableSchemas();
-
- foreach ($schemas as $schema) {
- if ($schema->foreignKeys) {
- foreach ($schema->foreignKeys as $name => $foreignKey) {
- $db->createCommand()->dropForeignKey($name, $schema->name)->execute();
- $this->stdout("Foreign key $name dropped.\n");
- }
- }
- }
-
- foreach ($schemas as $schema) {
- try {
- $db->createCommand()->dropTable($schema->name)->execute();
- $this->stdout("Table {$schema->name} dropped.\n");
- } catch (\Exception $e) {
- if ($this->isViewRelated($e->getMessage())) {
- $db->createCommand()->dropView($schema->name)->execute();
- $this->stdout("View {$schema->name} dropped.\n");
- } else {
- $this->stdout("Cannot drop {$schema->name} Table .\n");
- }
- }
- }
- }
-
- private function isViewRelated($errorMessage)
- {
- $dropViewErrors = [
- 'DROP VIEW to delete view',
- 'SQLSTATE[42S02]',
- ];
- foreach ($dropViewErrors as $dropViewError) {
- if (strpos($errorMessage, $dropViewError) !== false) {
- return true;
- }
- }
- return false;
- }
-
- protected function removeMigrationHistory($version)
- {
- $command = $this->db->createCommand();
- $command->delete($this->migrationTable, [
- 'version' => $version,
- ])->execute();
- }
- private $_migrationNameLimit;
-
- protected function getMigrationNameLimit()
- {
- if ($this->_migrationNameLimit !== null) {
- return $this->_migrationNameLimit;
- }
- $tableSchema = $this->db->schema ? $this->db->schema->getTableSchema($this->migrationTable, true) : null;
- if ($tableSchema !== null) {
- return $this->_migrationNameLimit = $tableSchema->columns['version']->size;
- }
- return static::MAX_NAME_LENGTH;
- }
-
- private function normalizeTableName($name)
- {
- if (substr($name, -1) === '_') {
- $name = substr($name, 0, -1);
- }
- if (strpos($name, '_') === 0) {
- return substr($name, 1);
- }
- return Inflector::underscore($name);
- }
-
- protected function generateMigrationSourceCode($params)
- {
- $parsedFields = $this->parseFields();
- $fields = $parsedFields['fields'];
- $foreignKeys = $parsedFields['foreignKeys'];
- $name = $params['name'];
- if ($params['namespace']) {
- $name = substr($name, strrpos($name, '\\') + 1);
- }
- $templateFile = $this->templateFile;
- $table = null;
- if (preg_match(
- '/^create_?junction_?(?:table)?_?(?:for)?(.+)_?and(.+)_?tables?$/i',
- $name,
- $matches
- )) {
- $templateFile = $this->generatorTemplateFiles['create_junction'];
- $firstTable = $this->normalizeTableName($matches[1]);
- $secondTable = $this->normalizeTableName($matches[2]);
- $fields = array_merge(
- [
- [
- 'property' => $firstTable . '_id',
- 'decorators' => 'integer()',
- ],
- [
- 'property' => $secondTable . '_id',
- 'decorators' => 'integer()',
- ],
- ],
- $fields,
- [
- [
- 'property' => 'PRIMARY KEY(' .
- $firstTable . '_id, ' .
- $secondTable . '_id)',
- ],
- ]
- );
- $foreignKeys[$firstTable . '_id']['table'] = $firstTable;
- $foreignKeys[$secondTable . '_id']['table'] = $secondTable;
- $foreignKeys[$firstTable . '_id']['column'] = null;
- $foreignKeys[$secondTable . '_id']['column'] = null;
- $table = $firstTable . '_' . $secondTable;
- } elseif (preg_match('/^add(.+)columns?_?to(.+)table$/i', $name, $matches)) {
- $templateFile = $this->generatorTemplateFiles['add_column'];
- $table = $this->normalizeTableName($matches[2]);
- } elseif (preg_match('/^drop(.+)columns?_?from(.+)table$/i', $name, $matches)) {
- $templateFile = $this->generatorTemplateFiles['drop_column'];
- $table = $this->normalizeTableName($matches[2]);
- } elseif (preg_match('/^create(.+)table$/i', $name, $matches)) {
- $this->addDefaultPrimaryKey($fields);
- $templateFile = $this->generatorTemplateFiles['create_table'];
- $table = $this->normalizeTableName($matches[1]);
- } elseif (preg_match('/^drop(.+)table$/i', $name, $matches)) {
- $this->addDefaultPrimaryKey($fields);
- $templateFile = $this->generatorTemplateFiles['drop_table'];
- $table = $this->normalizeTableName($matches[1]);
- }
- foreach ($foreignKeys as $column => $foreignKey) {
- $relatedColumn = $foreignKey['column'];
- $relatedTable = $foreignKey['table'];
-
-
-
- if ($relatedColumn === null) {
- $relatedColumn = 'id';
- try {
- $this->db = Instance::ensure($this->db, Connection::className());
- $relatedTableSchema = $this->db->getTableSchema($relatedTable);
- if ($relatedTableSchema !== null) {
- $primaryKeyCount = count($relatedTableSchema->primaryKey);
- if ($primaryKeyCount === 1) {
- $relatedColumn = $relatedTableSchema->primaryKey[0];
- } elseif ($primaryKeyCount > 1) {
- $this->stdout("Related table for field \"{$column}\" exists, but primary key is composite. Default name \"id\" will be used for related field\n", Console::FG_YELLOW);
- } elseif ($primaryKeyCount === 0) {
- $this->stdout("Related table for field \"{$column}\" exists, but does not have a primary key. Default name \"id\" will be used for related field.\n", Console::FG_YELLOW);
- }
- }
- } catch (\ReflectionException $e) {
- $this->stdout("Cannot initialize database component to try reading referenced table schema for field \"{$column}\". Default name \"id\" will be used for related field.\n", Console::FG_YELLOW);
- }
- }
- $foreignKeys[$column] = [
- 'idx' => $this->generateTableName("idx-$table-$column"),
- 'fk' => $this->generateTableName("fk-$table-$column"),
- 'relatedTable' => $this->generateTableName($relatedTable),
- 'relatedColumn' => $relatedColumn,
- ];
- }
- return $this->renderFile(Yii::getAlias($templateFile), array_merge($params, [
- 'table' => $this->generateTableName($table),
- 'fields' => $fields,
- 'foreignKeys' => $foreignKeys,
- 'tableComment' => $this->comment,
- ]));
- }
-
- protected function generateTableName($tableName)
- {
- if (!$this->useTablePrefix) {
- return $tableName;
- }
- return '{{%' . $tableName . '}}';
- }
-
- protected function parseFields()
- {
- $fields = [];
- $foreignKeys = [];
- foreach ($this->fields as $index => $field) {
- $chunks = $this->splitFieldIntoChunks($field);
- $property = array_shift($chunks);
- foreach ($chunks as $i => &$chunk) {
- if (strncmp($chunk, 'foreignKey', 10) === 0) {
- preg_match('/foreignKey\((\w*)\s?(\w*)\)/', $chunk, $matches);
- $foreignKeys[$property] = [
- 'table' => isset($matches[1])
- ? $matches[1]
- : preg_replace('/_id$/', '', $property),
- 'column' => !empty($matches[2])
- ? $matches[2]
- : null,
- ];
- unset($chunks[$i]);
- continue;
- }
- if (!preg_match('/^(.+?)\(([^(]+)\)$/', $chunk)) {
- $chunk .= '()';
- }
- }
- $fields[] = [
- 'property' => $property,
- 'decorators' => implode('->', $chunks),
- ];
- }
- return [
- 'fields' => $fields,
- 'foreignKeys' => $foreignKeys,
- ];
- }
-
- protected function splitFieldIntoChunks($field)
- {
- $hasDoubleQuotes = false;
- preg_match_all('/defaultValue\(.*?:.*?\)/', $field, $matches);
- if (isset($matches[0][0])) {
- $hasDoubleQuotes = true;
- $originalDefaultValue = $matches[0][0];
- $defaultValue = str_replace(':', '{{colon}}', $originalDefaultValue);
- $field = str_replace($originalDefaultValue, $defaultValue, $field);
- }
- $chunks = preg_split('/\s?:\s?/', $field);
- if (is_array($chunks) && $hasDoubleQuotes) {
- foreach ($chunks as $key => $chunk) {
- $chunks[$key] = str_replace($defaultValue, $originalDefaultValue, $chunk);
- }
- }
- return $chunks;
- }
-
- protected function addDefaultPrimaryKey(&$fields)
- {
- foreach ($fields as $field) {
- if (false !== strripos($field['decorators'], 'primarykey()')) {
- return;
- }
- }
- array_unshift($fields, ['property' => 'id', 'decorators' => 'primaryKey()']);
- }
- }
|