Completed
Push — master ( 98a71d...264831 )
by
unknown
15:42
created

MigrateController::truncateDatabase()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5.1158

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 10
cts 12
cp 0.8333
rs 8.7624
c 0
b 0
f 0
cc 5
eloc 11
nc 8
nop 0
crap 5.1158
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\console\controllers;
9
10
use Yii;
11
use yii\db\Connection;
12
use yii\db\Query;
13
use yii\di\Instance;
14
use yii\helpers\ArrayHelper;
15
use yii\helpers\Console;
16
17
/**
18
 * Manages application migrations.
19
 *
20
 * A migration means a set of persistent changes to the application environment
21
 * that is shared among different developers. For example, in an application
22
 * backed by a database, a migration may refer to a set of changes to
23
 * the database, such as creating a new table, adding a new table column.
24
 *
25
 * This command provides support for tracking the migration history, upgrading
26
 * or downloading with migrations, and creating new migration skeletons.
27
 *
28
 * The migration history is stored in a database table named
29
 * as [[migrationTable]]. The table will be automatically created the first time
30
 * this command is executed, if it does not exist. You may also manually
31
 * create it as follows:
32
 *
33
 * ```sql
34
 * CREATE TABLE migration (
35
 *     version varchar(180) PRIMARY KEY,
36
 *     apply_time integer
37
 * )
38
 * ```
39
 *
40
 * Below are some common usages of this command:
41
 *
42
 * ```
43
 * # creates a new migration named 'create_user_table'
44
 * yii migrate/create create_user_table
45
 *
46
 * # applies ALL new migrations
47
 * yii migrate
48
 *
49
 * # reverts the last applied migration
50
 * yii migrate/down
51
 * ```
52
 *
53
 * Since 2.0.10 you can use namespaced migrations. In order to enable this feature you should configure [[migrationNamespaces]]
54
 * property for the controller at application configuration:
55
 *
56
 * ```php
57
 * return [
58
 *     'controllerMap' => [
59
 *         'migrate' => [
60
 *             'class' => 'yii\console\controllers\MigrateController',
61
 *             'migrationNamespaces' => [
62
 *                 'app\migrations',
63
 *                 'some\extension\migrations',
64
 *             ],
65
 *             //'migrationPath' => null, // allows to disable not namespaced migration completely
66
 *         ],
67
 *     ],
68
 * ];
69
 * ```
70
 *
71
 * @author Qiang Xue <[email protected]>
72
 * @since 2.0
73
 */
74
class MigrateController extends BaseMigrateController
75
{
76
    /**
77
     * @var string the name of the table for keeping applied migration information.
78
     */
79
    public $migrationTable = '{{%migration}}';
80
    /**
81
     * @inheritdoc
82
     */
83
    public $templateFile = '@yii/views/migration.php';
84
    /**
85
     * @var array a set of template paths for generating migration code automatically.
86
     *
87
     * The key is the template type, the value is a path or the alias. Supported types are:
88
     * - `create_table`: table creating template
89
     * - `drop_table`: table dropping template
90
     * - `add_column`: adding new column template
91
     * - `drop_column`: dropping column template
92
     * - `create_junction`: create junction template
93
     *
94
     * @since 2.0.7
95
     */
96
    public $generatorTemplateFiles = [
97
        'create_table' => '@yii/views/createTableMigration.php',
98
        'drop_table' => '@yii/views/dropTableMigration.php',
99
        'add_column' => '@yii/views/addColumnMigration.php',
100
        'drop_column' => '@yii/views/dropColumnMigration.php',
101
        'create_junction' => '@yii/views/createTableMigration.php',
102
    ];
103
    /**
104
     * @var bool indicates whether the table names generated should consider
105
     * the `tablePrefix` setting of the DB connection. For example, if the table
106
     * name is `post` the generator wil return `{{%post}}`.
107
     * @since 2.0.8
108
     */
109
    public $useTablePrefix = false;
110
    /**
111
     * @var array column definition strings used for creating migration code.
112
     *
113
     * The format of each definition is `COLUMN_NAME:COLUMN_TYPE:COLUMN_DECORATOR`. Delimiter is `,`.
114
     * For example, `--fields="name:string(12):notNull:unique"`
115
     * produces a string column of size 12 which is not null and unique values.
116
     *
117
     * Note: primary key is added automatically and is named id by default.
118
     * If you want to use another name you may specify it explicitly like
119
     * `--fields="id_key:primaryKey,name:string(12):notNull:unique"`
120
     * @since 2.0.7
121
     */
122
    public $fields = [];
123
    /**
124
     * @var Connection|array|string the DB connection object or the application component ID of the DB connection to use
125
     * when applying migrations. Starting from version 2.0.3, this can also be a configuration array
126
     * for creating the object.
127
     */
128
    public $db = 'db';
129
130
131
    /**
132
     * @inheritdoc
133
     */
134 24
    public function options($actionID)
135
    {
136 24
        return array_merge(
137 24
            parent::options($actionID),
138 24
            ['migrationTable', 'db'], // global for all actions
139 24
            $actionID === 'create'
140 9
                ? ['templateFile', 'fields', 'useTablePrefix']
141 24
                : []
142
        );
143
    }
144
145
    /**
146
     * @inheritdoc
147
     * @since 2.0.8
148
     */
149
    public function optionAliases()
150
    {
151
        return array_merge(parent::optionAliases(), [
152
            'f' => 'fields',
153
            'p' => 'migrationPath',
154
            't' => 'migrationTable',
155
            'F' => 'templateFile',
156
            'P' => 'useTablePrefix',
157
        ]);
158
    }
159
160
    /**
161
     * This method is invoked right before an action is to be executed (after all possible filters.)
162
     * It checks the existence of the [[migrationPath]].
163
     * @param \yii\base\Action $action the action to be executed.
164
     * @return bool whether the action should continue to be executed.
165
     */
166 33
    public function beforeAction($action)
167
    {
168 33
        if (parent::beforeAction($action)) {
169 33
            if ($action->id !== 'create') {
170 25
                $this->db = Instance::ensure($this->db, Connection::className());
171
            }
172
173 33
            return true;
174
        }
175
176
        return false;
177
    }
178
179
    /**
180
     * Creates a new migration instance.
181
     * @param string $class the migration class name
182
     * @return \yii\db\Migration the migration instance
183
     */
184 21
    protected function createMigration($class)
185
    {
186 21
        $this->includeMigrationFile($class);
187 21
        return new $class(['db' => $this->db]);
188
    }
189
190
    /**
191
     * @inheritdoc
192
     */
193 25
    protected function getMigrationHistory($limit)
194
    {
195 25
        if ($this->db->schema->getTableSchema($this->migrationTable, true) === null) {
196 19
            $this->createMigrationHistoryTable();
197
        }
198 25
        $query = (new Query())
199 25
            ->select(['version', 'apply_time'])
200 25
            ->from($this->migrationTable)
201 25
            ->orderBy(['apply_time' => SORT_DESC, 'version' => SORT_DESC]);
202
203 25
        if (empty($this->migrationNamespaces)) {
204 18
            $query->limit($limit);
205 18
            $rows = $query->all($this->db);
206 18
            $history = ArrayHelper::map($rows, 'version', 'apply_time');
207 18
            unset($history[self::BASE_MIGRATION]);
208 18
            return $history;
209
        }
210
211 7
        $rows = $query->all($this->db);
212
213 7
        $history = [];
214 7
        foreach ($rows as $key => $row) {
215 7
            if ($row['version'] === self::BASE_MIGRATION) {
216 7
                continue;
217
            }
218 4
            if (preg_match('/m?(\d{6}_?\d{6})(\D.*)?$/is', $row['version'], $matches)) {
219 4
                $time = str_replace('_', '', $matches[1]);
220 4
                $row['canonicalVersion'] = $time;
221
            } else {
222
                $row['canonicalVersion'] = $row['version'];
223
            }
224 4
            $row['apply_time'] = (int) $row['apply_time'];
225 4
            $history[] = $row;
226
        }
227
228 7
        usort($history, function ($a, $b) {
229 4
            if ($a['apply_time'] === $b['apply_time']) {
230 4
                if (($compareResult = strcasecmp($b['canonicalVersion'], $a['canonicalVersion'])) !== 0) {
231 2
                    return $compareResult;
232
                }
233
234 2
                return strcasecmp($b['version'], $a['version']);
235
            }
236
237 2
            return ($a['apply_time'] > $b['apply_time']) ? -1 : +1;
238 7
        });
239
240 7
        $history = array_slice($history, 0, $limit);
241
242 7
        $history = ArrayHelper::map($history, 'version', 'apply_time');
243
244 7
        return $history;
245
    }
246
247
    /**
248
     * Creates the migration history table.
249
     */
250 19
    protected function createMigrationHistoryTable()
251
    {
252 19
        $tableName = $this->db->schema->getRawTableName($this->migrationTable);
253 19
        $this->stdout("Creating migration history table \"$tableName\"...", Console::FG_YELLOW);
254 19
        $this->db->createCommand()->createTable($this->migrationTable, [
255 19
            'version' => 'varchar(180) NOT NULL PRIMARY KEY',
256
            'apply_time' => 'integer',
257 19
        ])->execute();
258 19
        $this->db->createCommand()->insert($this->migrationTable, [
259 19
            'version' => self::BASE_MIGRATION,
260 19
            'apply_time' => time(),
261 19
        ])->execute();
262 19
        $this->stdout("Done.\n", Console::FG_GREEN);
263 19
    }
264
265
    /**
266
     * @inheritdoc
267
     */
268 23
    protected function addMigrationHistory($version)
269
    {
270 23
        $command = $this->db->createCommand();
271 23
        $command->insert($this->migrationTable, [
272 23
            'version' => $version,
273 23
            'apply_time' => time(),
274 23
        ])->execute();
275 23
    }
276
277
    /**
278
     * @inheritdoc
279
     * @since 2.0.13
280
     */
281 1
    protected function truncateDatabase()
282
    {
283 1
        $db = $this->db;
284 1
        $schemas = $db->schema->getTableSchemas();
285
286
        // First drop all foreign keys,
287 1
        foreach ($schemas as $schema) {
288 1
            if ($schema->foreignKeys) {
289
                foreach ($schema->foreignKeys as $name => $foreignKey) {
290
                    $db->createCommand()->dropForeignKey($name, $schema->name)->execute();
291 1
                    $this->stdout("Foreign key $name dropped.\n");
292
                }
293
            }
294
        }
295
296
        // Then drop the tables:
297 1
        foreach ($schemas as $schema) {
298 1
            $db->createCommand()->dropTable($schema->name)->execute();
299 1
            $this->stdout("Table {$schema->name} dropped.\n");
300
        }
301 1
    }
302
303
    /**
304
     * @inheritdoc
305
     */
306 13
    protected function removeMigrationHistory($version)
307
    {
308 13
        $command = $this->db->createCommand();
309 13
        $command->delete($this->migrationTable, [
310 13
            'version' => $version,
311 13
        ])->execute();
312 13
    }
313
314
    /**
315
     * @inheritdoc
316
     * @since 2.0.8
317
     */
318 9
    protected function generateMigrationSourceCode($params)
319
    {
320 9
        $parsedFields = $this->parseFields();
321 9
        $fields = $parsedFields['fields'];
322 9
        $foreignKeys = $parsedFields['foreignKeys'];
323
324 9
        $name = $params['name'];
325
326 9
        $templateFile = $this->templateFile;
327 9
        $table = null;
328 9
        if (preg_match('/^create_junction(?:_table_for_|_for_|_)(.+)_and_(.+)_tables?$/', $name, $matches)) {
329 1
            $templateFile = $this->generatorTemplateFiles['create_junction'];
330 1
            $firstTable = $matches[1];
331 1
            $secondTable = $matches[2];
332
333 1
            $fields = array_merge(
334
                [
335
                    [
336 1
                        'property' => $firstTable . '_id',
337 1
                        'decorators' => 'integer()',
338
                    ],
339
                    [
340 1
                        'property' => $secondTable . '_id',
341 1
                        'decorators' => 'integer()',
342
                    ],
343
                ],
344 1
                $fields,
345
                [
346
                    [
347
                        'property' => 'PRIMARY KEY(' .
348 1
                            $firstTable . '_id, ' .
349 1
                            $secondTable . '_id)',
350
                    ],
351
                ]
352
            );
353
354 1
            $foreignKeys[$firstTable . '_id']['table'] = $firstTable;
355 1
            $foreignKeys[$secondTable . '_id']['table'] = $secondTable;
356 1
            $foreignKeys[$firstTable . '_id']['column'] = null;
357 1
            $foreignKeys[$secondTable . '_id']['column'] = null;
358 1
            $table = $firstTable . '_' . $secondTable;
359 8
        } elseif (preg_match('/^add_(.+)_columns?_to_(.+)_table$/', $name, $matches)) {
360 1
            $templateFile = $this->generatorTemplateFiles['add_column'];
361 1
            $table = $matches[2];
362 7
        } elseif (preg_match('/^drop_(.+)_columns?_from_(.+)_table$/', $name, $matches)) {
363 1
            $templateFile = $this->generatorTemplateFiles['drop_column'];
364 1
            $table = $matches[2];
365 6
        } elseif (preg_match('/^create_(.+)_table$/', $name, $matches)) {
366 1
            $this->addDefaultPrimaryKey($fields);
367 1
            $templateFile = $this->generatorTemplateFiles['create_table'];
368 1
            $table = $matches[1];
369 6
        } elseif (preg_match('/^drop_(.+)_table$/', $name, $matches)) {
370 2
            $this->addDefaultPrimaryKey($fields);
371 2
            $templateFile = $this->generatorTemplateFiles['drop_table'];
372 2
            $table = $matches[1];
373
        }
374
375 9
        foreach ($foreignKeys as $column => $foreignKey) {
376 3
            $relatedColumn = $foreignKey['column'];
377 3
            $relatedTable = $foreignKey['table'];
378
            // Since 2.0.11 if related column name is not specified,
379
            // we're trying to get it from table schema
380
            // @see https://github.com/yiisoft/yii2/issues/12748
381 3
            if ($relatedColumn === null) {
382 3
                $relatedColumn = 'id';
383
                try {
384 3
                    $this->db = Instance::ensure($this->db, Connection::className());
385 3
                    $relatedTableSchema = $this->db->getTableSchema($relatedTable);
386 3
                    if ($relatedTableSchema !== null) {
387
                        $primaryKeyCount = count($relatedTableSchema->primaryKey);
388
                        if ($primaryKeyCount === 1) {
389
                            $relatedColumn = $relatedTableSchema->primaryKey[0];
390
                        } elseif ($primaryKeyCount > 1) {
391
                            $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);
392
                        } elseif ($primaryKeyCount === 0) {
393 3
                            $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);
394
                        }
395
                    }
396
                } catch (\ReflectionException $e) {
397
                    $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);
398
                }
399
            }
400 3
            $foreignKeys[$column] = [
401 3
                'idx' => $this->generateTableName("idx-$table-$column"),
402 3
                'fk' => $this->generateTableName("fk-$table-$column"),
403 3
                'relatedTable' => $this->generateTableName($relatedTable),
404 3
                'relatedColumn' => $relatedColumn,
405
            ];
406
        }
407
408 9
        return $this->renderFile(Yii::getAlias($templateFile), array_merge($params, [
0 ignored issues
show
Bug introduced by
It seems like \Yii::getAlias($templateFile) targeting yii\BaseYii::getAlias() can also be of type boolean; however, yii\base\Controller::renderFile() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
409 9
            'table' => $this->generateTableName($table),
410 9
            'fields' => $fields,
411 9
            'foreignKeys' => $foreignKeys,
412
        ]));
413
    }
414
415
    /**
416
     * If `useTablePrefix` equals true, then the table name will contain the
417
     * prefix format.
418
     *
419
     * @param string $tableName the table name to generate.
420
     * @return string
421
     * @since 2.0.8
422
     */
423 9
    protected function generateTableName($tableName)
424
    {
425 9
        if (!$this->useTablePrefix) {
426 9
            return $tableName;
427
        }
428
429 2
        return '{{%' . $tableName . '}}';
430
    }
431
432
    /**
433
     * Parse the command line migration fields.
434
     * @return array parse result with following fields:
435
     *
436
     * - fields: array, parsed fields
437
     * - foreignKeys: array, detected foreign keys
438
     *
439
     * @since 2.0.7
440
     */
441 9
    protected function parseFields()
442
    {
443 9
        $fields = [];
444 9
        $foreignKeys = [];
445
446 9
        foreach ($this->fields as $index => $field) {
447 4
            $chunks = preg_split('/\s?:\s?/', $field, null);
448 4
            $property = array_shift($chunks);
449
450 4
            foreach ($chunks as $i => &$chunk) {
451 4
                if (strpos($chunk, 'foreignKey') === 0) {
452 2
                    preg_match('/foreignKey\((\w*)\s?(\w*)\)/', $chunk, $matches);
453 2
                    $foreignKeys[$property] = [
454 2
                        'table' => isset($matches[1])
455 2
                            ? $matches[1]
456 2
                            : preg_replace('/_id$/', '', $property),
457 2
                        'column' => !empty($matches[2])
458
                            ? $matches[2]
459
                            : null,
460
                    ];
461
462 2
                    unset($chunks[$i]);
463 2
                    continue;
464
                }
465
466 4
                if (!preg_match('/^(.+?)\(([^(]+)\)$/', $chunk)) {
467 4
                    $chunk .= '()';
468
                }
469
            }
470 4
            $fields[] = [
471 4
                'property' => $property,
472 4
                'decorators' => implode('->', $chunks),
473
            ];
474
        }
475
476
        return [
477 9
            'fields' => $fields,
478 9
            'foreignKeys' => $foreignKeys,
479
        ];
480
    }
481
482
    /**
483
     * Adds default primary key to fields list if there's no primary key specified.
484
     * @param array $fields parsed fields
485
     * @since 2.0.7
486
     */
487 2
    protected function addDefaultPrimaryKey(&$fields)
488
    {
489 2
        foreach ($fields as $field) {
490 2
            if (false !== strripos($field['decorators'], 'primarykey()')) {
491 2
                return;
492
            }
493
        }
494 2
        array_unshift($fields, ['property' => 'id', 'decorators' => 'primaryKey()']);
495 2
    }
496
}
497