|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405 |
- <?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;
-
-
- class MigrateController extends BaseMigrateController
- {
-
-
- 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 = false;
-
-
- public $fields = [];
-
-
- public $db = 'db';
-
-
-
-
- public function options($actionID)
- {
- return array_merge(
- parent::options($actionID),
- ['migrationTable', 'db'],
- $actionID === 'create'
- ? ['templateFile', 'fields', 'useTablePrefix']
- : []
- );
- }
-
-
-
- public function optionAliases()
- {
- return array_merge(parent::optionAliases(), [
- 'f' => 'fields',
- 'p' => 'migrationPath',
- 't' => 'migrationTable',
- 'F' => 'templateFile',
- 'P' => 'useTablePrefix',
- ]);
- }
-
-
-
- public function beforeAction($action)
- {
- if (parent::beforeAction($action)) {
- if ($action->id !== 'create') {
- $this->db = Instance::ensure($this->db, Connection::className());
- }
- return true;
- } else {
- return false;
- }
- }
-
-
-
- protected function createMigration($class)
- {
- $class = trim($class, '\\');
- if (strpos($class, '\\') === false) {
- $file = $this->migrationPath . DIRECTORY_SEPARATOR . $class . '.php';
- require_once($file);
- }
-
- return new $class(['db' => $this->db]);
- }
-
-
-
- protected function getMigrationHistory($limit)
- {
- if ($this->db->schema->getTableSchema($this->migrationTable, true) === null) {
- $this->createMigrationHistoryTable();
- }
- $query = new Query;
- $rows = $query->select(['version', 'apply_time'])
- ->from($this->migrationTable)
- ->orderBy('apply_time DESC, version DESC')
- ->limit($limit)
- ->createCommand($this->db)
- ->queryAll();
- $history = ArrayHelper::map($rows, 'version', 'apply_time');
- unset($history[self::BASE_MIGRATION]);
-
- 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(180) 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 removeMigrationHistory($version)
- {
- $command = $this->db->createCommand();
- $command->delete($this->migrationTable, [
- 'version' => $version,
- ])->execute();
- }
-
-
-
- protected function generateMigrationSourceCode($params)
- {
- $parsedFields = $this->parseFields();
- $fields = $parsedFields['fields'];
- $foreignKeys = $parsedFields['foreignKeys'];
-
- $name = $params['name'];
-
- $templateFile = $this->templateFile;
- $table = null;
- if (preg_match('/^create_junction(?:_table_for_|_for_|_)(.+)_and_(.+)_tables?$/', $name, $matches)) {
- $templateFile = $this->generatorTemplateFiles['create_junction'];
- $firstTable = mb_strtolower($matches[1], Yii::$app->charset);
- $secondTable = mb_strtolower($matches[2], Yii::$app->charset);
-
- $fields = array_merge(
- [
- [
- 'property' => $firstTable . '_id',
- 'decorators' => 'integer()',
- ],
- [
- 'property' => $secondTable . '_id',
- 'decorators' => 'integer()',
- ],
- ],
- $fields,
- [
- [
- 'property' => 'PRIMARY KEY(' .
- $firstTable . '_id, ' .
- $secondTable . '_id)',
- ],
- ]
- );
-
- $foreignKeys[$firstTable . '_id'] = $firstTable;
- $foreignKeys[$secondTable . '_id'] = $secondTable;
- $table = $firstTable . '_' . $secondTable;
- } elseif (preg_match('/^add_(.+)_columns?_to_(.+)_table$/', $name, $matches)) {
- $templateFile = $this->generatorTemplateFiles['add_column'];
- $table = mb_strtolower($matches[2], Yii::$app->charset);
- } elseif (preg_match('/^drop_(.+)_columns?_from_(.+)_table$/', $name, $matches)) {
- $templateFile = $this->generatorTemplateFiles['drop_column'];
- $table = mb_strtolower($matches[2], Yii::$app->charset);
- } elseif (preg_match('/^create_(.+)_table$/', $name, $matches)) {
- $this->addDefaultPrimaryKey($fields);
- $templateFile = $this->generatorTemplateFiles['create_table'];
- $table = mb_strtolower($matches[1], Yii::$app->charset);
- } elseif (preg_match('/^drop_(.+)_table$/', $name, $matches)) {
- $this->addDefaultPrimaryKey($fields);
- $templateFile = $this->generatorTemplateFiles['drop_table'];
- $table = mb_strtolower($matches[1], Yii::$app->charset);
- }
-
- foreach ($foreignKeys as $column => $relatedTable) {
- $foreignKeys[$column] = [
- 'idx' => $this->generateTableName("idx-$table-$column"),
- 'fk' => $this->generateTableName("fk-$table-$column"),
- 'relatedTable' => $this->generateTableName($relatedTable),
- ];
- }
-
- return $this->renderFile(Yii::getAlias($templateFile), array_merge($params, [
- 'table' => $this->generateTableName($table),
- 'fields' => $fields,
- 'foreignKeys' => $foreignKeys,
- ]));
- }
-
-
-
- protected function generateTableName($tableName)
- {
- if (!$this->useTablePrefix) {
- return $tableName;
- }
- return '{{%' . $tableName . '}}';
- }
-
-
-
- protected function parseFields()
- {
- $fields = [];
- $foreignKeys = [];
-
- foreach ($this->fields as $index => $field) {
- $chunks = preg_split('/\s?:\s?/', $field, null);
- $property = array_shift($chunks);
-
- foreach ($chunks as $i => &$chunk) {
- if (strpos($chunk, 'foreignKey') === 0) {
- preg_match('/foreignKey\((\w*)\)/', $chunk, $matches);
- $foreignKeys[$property] = isset($matches[1])
- ? $matches[1]
- : preg_replace('/_id$/', '', $property);
-
- unset($chunks[$i]);
- continue;
- }
-
- if (!preg_match('/^(.+?)\(([^(]+)\)$/', $chunk)) {
- $chunk .= '()';
- }
- }
- $fields[] = [
- 'property' => $property,
- 'decorators' => implode('->', $chunks),
- ];
- }
-
- return [
- 'fields' => $fields,
- 'foreignKeys' => $foreignKeys,
- ];
- }
-
-
-
- protected function addDefaultPrimaryKey(&$fields)
- {
- foreach ($fields as $field) {
- if ($field['decorators'] === 'primaryKey()' || $field['decorators'] === 'bigPrimaryKey()') {
- return;
- }
- }
- array_unshift($fields, ['property' => 'id', 'decorators' => 'primaryKey()']);
- }
- }
|