Completed
Push — master ( 77d7a5...e55b3e )
by Alexander
13:07
created

MigrateController::truncateDatabase()   B

Complexity

Conditions 7
Paths 24

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 7.0796

Importance

Changes 0
Metric Value
dl 0
loc 30
ccs 15
cts 17
cp 0.8824
rs 8.5066
c 0
b 0
f 0
cc 7
nc 24
nop 0
crap 7.0796
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
     * Maximum length of a migration name.
78
     * @since 2.0.13
79
     */
80
    const MAX_NAME_LENGTH = 180;
81
82
    /**
83
     * @var string the name of the table for keeping applied migration information.
84
     */
85
    public $migrationTable = '{{%migration}}';
86
    /**
87
     * {@inheritdoc}
88
     */
89
    public $templateFile = '@yii/views/migration.php';
90
    /**
91
     * @var array a set of template paths for generating migration code automatically.
92
     *
93
     * The key is the template type, the value is a path or the alias. Supported types are:
94
     * - `create_table`: table creating template
95
     * - `drop_table`: table dropping template
96
     * - `add_column`: adding new column template
97
     * - `drop_column`: dropping column template
98
     * - `create_junction`: create junction template
99
     *
100
     * @since 2.0.7
101
     */
102
    public $generatorTemplateFiles = [
103
        'create_table' => '@yii/views/createTableMigration.php',
104
        'drop_table' => '@yii/views/dropTableMigration.php',
105
        'add_column' => '@yii/views/addColumnMigration.php',
106
        'drop_column' => '@yii/views/dropColumnMigration.php',
107
        'create_junction' => '@yii/views/createTableMigration.php',
108
    ];
109
    /**
110
     * @var bool indicates whether the table names generated should consider
111
     * the `tablePrefix` setting of the DB connection. For example, if the table
112
     * name is `post` the generator wil return `{{%post}}`.
113
     * @since 2.0.8
114
     */
115
    public $useTablePrefix = false;
116
    /**
117
     * @var array column definition strings used for creating migration code.
118
     *
119
     * The format of each definition is `COLUMN_NAME:COLUMN_TYPE:COLUMN_DECORATOR`. Delimiter is `,`.
120
     * For example, `--fields="name:string(12):notNull:unique"`
121
     * produces a string column of size 12 which is not null and unique values.
122
     *
123
     * Note: primary key is added automatically and is named id by default.
124
     * If you want to use another name you may specify it explicitly like
125
     * `--fields="id_key:primaryKey,name:string(12):notNull:unique"`
126
     * @since 2.0.7
127
     */
128
    public $fields = [];
129
    /**
130
     * @var Connection|array|string the DB connection object or the application component ID of the DB connection to use
131
     * when applying migrations. Starting from version 2.0.3, this can also be a configuration array
132
     * for creating the object.
133
     */
134
    public $db = 'db';
135
    /**
136
     * @var string the comment for the table being created.
137
     * @since 2.0.14
138
     */
139
    public $comment = '';
140
141
142
    /**
143
     * {@inheritdoc}
144
     */
145 46
    public function options($actionID)
146
    {
147 46
        return array_merge(
148 46
            parent::options($actionID),
149 46
            ['migrationTable', 'db'], // global for all actions
150 46
            $actionID === 'create'
151 10
                ? ['templateFile', 'fields', 'useTablePrefix', 'comment']
152 46
                : []
153
        );
154
    }
155
156
    /**
157
     * {@inheritdoc}
158
     * @since 2.0.8
159
     */
160
    public function optionAliases()
161
    {
162
        return array_merge(parent::optionAliases(), [
163
            'C' => 'comment',
164
            'f' => 'fields',
165
            'p' => 'migrationPath',
166
            't' => 'migrationTable',
167
            'F' => 'templateFile',
168
            'P' => 'useTablePrefix',
169
            'c' => 'compact',
170
        ]);
171
    }
172
173
    /**
174
     * This method is invoked right before an action is to be executed (after all possible filters.)
175
     * It checks the existence of the [[migrationPath]].
176
     * @param \yii\base\Action $action the action to be executed.
177
     * @return bool whether the action should continue to be executed.
178
     */
179 56
    public function beforeAction($action)
180
    {
181 56
        if (parent::beforeAction($action)) {
182 56
            $this->db = Instance::ensure($this->db, Connection::className());
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: since 2.0.14. On PHP >=5.5, use `::class` instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
183 56
            return true;
184
        }
185
186
        return false;
187
    }
188
189
    /**
190
     * Creates a new migration instance.
191
     * @param string $class the migration class name
192
     * @return \yii\db\Migration the migration instance
193
     */
194 42
    protected function createMigration($class)
195
    {
196 42
        $this->includeMigrationFile($class);
197
198 42
        return Yii::createObject([
199 42
            'class' => $class,
200 42
            'db' => $this->db,
201 42
            'compact' => $this->compact,
202
        ]);
203
    }
204
205
    /**
206
     * {@inheritdoc}
207
     */
208 47
    protected function getMigrationHistory($limit)
209
    {
210 47
        if ($this->db->schema->getTableSchema($this->migrationTable, true) === null) {
211 26
            $this->createMigrationHistoryTable();
212
        }
213 47
        $query = (new Query())
214 47
            ->select(['version', 'apply_time'])
215 47
            ->from($this->migrationTable)
216 47
            ->orderBy(['apply_time' => SORT_DESC, 'version' => SORT_DESC]);
217
218 47
        if (empty($this->migrationNamespaces)) {
219 40
            $query->limit($limit);
220 40
            $rows = $query->all($this->db);
221 40
            $history = ArrayHelper::map($rows, 'version', 'apply_time');
222 40
            unset($history[self::BASE_MIGRATION]);
223 40
            return $history;
224
        }
225
226 7
        $rows = $query->all($this->db);
227
228 7
        $history = [];
229 7
        foreach ($rows as $key => $row) {
230 7
            if ($row['version'] === self::BASE_MIGRATION) {
231 7
                continue;
232
            }
233 4
            if (preg_match('/m?(\d{6}_?\d{6})(\D.*)?$/is', $row['version'], $matches)) {
234 4
                $time = str_replace('_', '', $matches[1]);
235 4
                $row['canonicalVersion'] = $time;
236
            } else {
237
                $row['canonicalVersion'] = $row['version'];
238
            }
239 4
            $row['apply_time'] = (int) $row['apply_time'];
240 4
            $history[] = $row;
241
        }
242
243 7
        usort($history, function ($a, $b) {
244 4
            if ($a['apply_time'] === $b['apply_time']) {
245 4
                if (($compareResult = strcasecmp($b['canonicalVersion'], $a['canonicalVersion'])) !== 0) {
246 2
                    return $compareResult;
247
                }
248
249 2
                return strcasecmp($b['version'], $a['version']);
250
            }
251
252 1
            return ($a['apply_time'] > $b['apply_time']) ? -1 : +1;
253 7
        });
254
255 7
        $history = array_slice($history, 0, $limit);
256
257 7
        $history = ArrayHelper::map($history, 'version', 'apply_time');
258
259 7
        return $history;
260
    }
261
262
    /**
263
     * Creates the migration history table.
264
     */
265 26
    protected function createMigrationHistoryTable()
266
    {
267 26
        $tableName = $this->db->schema->getRawTableName($this->migrationTable);
268 26
        $this->stdout("Creating migration history table \"$tableName\"...", Console::FG_YELLOW);
269 26
        $this->db->createCommand()->createTable($this->migrationTable, [
270 26
            'version' => 'varchar(' . static::MAX_NAME_LENGTH . ') NOT NULL PRIMARY KEY',
271 26
            'apply_time' => 'integer',
272 26
        ])->execute();
273 26
        $this->db->createCommand()->insert($this->migrationTable, [
274 26
            'version' => self::BASE_MIGRATION,
275 26
            'apply_time' => time(),
276 26
        ])->execute();
277 26
        $this->stdout("Done.\n", Console::FG_GREEN);
278 26
    }
279
280
    /**
281
     * {@inheritdoc}
282
     */
283 44
    protected function addMigrationHistory($version)
284
    {
285 44
        $command = $this->db->createCommand();
286 44
        $command->insert($this->migrationTable, [
287 44
            'version' => $version,
288 44
            'apply_time' => time(),
289 44
        ])->execute();
290 44
    }
291
292
    /**
293
     * {@inheritdoc}
294
     * @since 2.0.13
295
     */
296 1
    protected function truncateDatabase()
297
    {
298 1
        $db = $this->db;
299 1
        $schemas = $db->schema->getTableSchemas();
300
301
        // First drop all foreign keys,
302 1
        foreach ($schemas as $schema) {
303 1
            if ($schema->foreignKeys) {
304
                foreach ($schema->foreignKeys as $name => $foreignKey) {
305
                    $db->createCommand()->dropForeignKey($name, $schema->name)->execute();
306 1
                    $this->stdout("Foreign key $name dropped.\n");
307
                }
308
            }
309
        }
310
311
        // Then drop the tables:
312 1
        foreach ($schemas as $schema) {
313
            try {
314 1
                $db->createCommand()->dropTable($schema->name)->execute();
315 1
                $this->stdout("Table {$schema->name} dropped.\n");
316 1
            } catch (\Exception $e) {
317 1
                if (strpos($e->getMessage(), 'DROP VIEW to delete view') !== false) {
318 1
                    $db->createCommand()->dropView($schema->name)->execute();
319 1
                    $this->stdout("View {$schema->name} dropped.\n");
320
                } else {
321 1
                    $this->stdout("Cannot drop {$schema->name} Table .\n");
322
                }
323
            }
324
        }
325 1
    }
326
327
    /**
328
     * {@inheritdoc}
329
     */
330 33
    protected function removeMigrationHistory($version)
331
    {
332 33
        $command = $this->db->createCommand();
333 33
        $command->delete($this->migrationTable, [
334 33
            'version' => $version,
335 33
        ])->execute();
336 33
    }
337
338
    private $_migrationNameLimit;
339
340
    /**
341
     * {@inheritdoc}
342
     * @since 2.0.13
343
     */
344 52
    protected function getMigrationNameLimit()
345
    {
346 52
        if ($this->_migrationNameLimit !== null) {
347 8
            return $this->_migrationNameLimit;
348
        }
349 52
        $tableSchema = $this->db->schema ? $this->db->schema->getTableSchema($this->migrationTable, true) : null;
350 52
        if ($tableSchema !== null) {
351 43
            return $this->_migrationNameLimit = $tableSchema->columns['version']->size;
352
        }
353
354 9
        return static::MAX_NAME_LENGTH;
355
    }
356
357
    /**
358
     * {@inheritdoc}
359
     * @since 2.0.8
360
     */
361 9
    protected function generateMigrationSourceCode($params)
362
    {
363 9
        $parsedFields = $this->parseFields();
364 9
        $fields = $parsedFields['fields'];
365 9
        $foreignKeys = $parsedFields['foreignKeys'];
366
367 9
        $name = $params['name'];
368
369 9
        $templateFile = $this->templateFile;
370 9
        $table = null;
371 9
        if (preg_match('/^create_junction(?:_table_for_|_for_|_)(.+)_and_(.+)_tables?$/', $name, $matches)) {
372 1
            $templateFile = $this->generatorTemplateFiles['create_junction'];
373 1
            $firstTable = $matches[1];
374 1
            $secondTable = $matches[2];
375
376 1
            $fields = array_merge(
377
                [
378
                    [
379 1
                        'property' => $firstTable . '_id',
380 1
                        'decorators' => 'integer()',
381
                    ],
382
                    [
383 1
                        'property' => $secondTable . '_id',
384 1
                        'decorators' => 'integer()',
385
                    ],
386
                ],
387 1
                $fields,
388
                [
389
                    [
390
                        'property' => 'PRIMARY KEY(' .
391 1
                            $firstTable . '_id, ' .
392 1
                            $secondTable . '_id)',
393
                    ],
394
                ]
395
            );
396
397 1
            $foreignKeys[$firstTable . '_id']['table'] = $firstTable;
398 1
            $foreignKeys[$secondTable . '_id']['table'] = $secondTable;
399 1
            $foreignKeys[$firstTable . '_id']['column'] = null;
400 1
            $foreignKeys[$secondTable . '_id']['column'] = null;
401 1
            $table = $firstTable . '_' . $secondTable;
402 8
        } elseif (preg_match('/^add_(.+)_columns?_to_(.+)_table$/', $name, $matches)) {
403 1
            $templateFile = $this->generatorTemplateFiles['add_column'];
404 1
            $table = $matches[2];
405 7
        } elseif (preg_match('/^drop_(.+)_columns?_from_(.+)_table$/', $name, $matches)) {
406 1
            $templateFile = $this->generatorTemplateFiles['drop_column'];
407 1
            $table = $matches[2];
408 6
        } elseif (preg_match('/^create_(.+)_table$/', $name, $matches)) {
409 1
            $this->addDefaultPrimaryKey($fields);
410 1
            $templateFile = $this->generatorTemplateFiles['create_table'];
411 1
            $table = $matches[1];
412 6
        } elseif (preg_match('/^drop_(.+)_table$/', $name, $matches)) {
413 2
            $this->addDefaultPrimaryKey($fields);
414 2
            $templateFile = $this->generatorTemplateFiles['drop_table'];
415 2
            $table = $matches[1];
416
        }
417
418 9
        foreach ($foreignKeys as $column => $foreignKey) {
419 3
            $relatedColumn = $foreignKey['column'];
420 3
            $relatedTable = $foreignKey['table'];
421
            // Since 2.0.11 if related column name is not specified,
422
            // we're trying to get it from table schema
423
            // @see https://github.com/yiisoft/yii2/issues/12748
424 3
            if ($relatedColumn === null) {
425 3
                $relatedColumn = 'id';
426
                try {
427 3
                    $this->db = Instance::ensure($this->db, Connection::className());
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: since 2.0.14. On PHP >=5.5, use `::class` instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
428 3
                    $relatedTableSchema = $this->db->getTableSchema($relatedTable);
429 3
                    if ($relatedTableSchema !== null) {
430
                        $primaryKeyCount = count($relatedTableSchema->primaryKey);
431
                        if ($primaryKeyCount === 1) {
432
                            $relatedColumn = $relatedTableSchema->primaryKey[0];
433
                        } elseif ($primaryKeyCount > 1) {
434
                            $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);
435
                        } elseif ($primaryKeyCount === 0) {
436 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);
437
                        }
438
                    }
439
                } catch (\ReflectionException $e) {
440
                    $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);
441
                }
442
            }
443 3
            $foreignKeys[$column] = [
444 3
                'idx' => $this->generateTableName("idx-$table-$column"),
445 3
                'fk' => $this->generateTableName("fk-$table-$column"),
446 3
                'relatedTable' => $this->generateTableName($relatedTable),
447 3
                'relatedColumn' => $relatedColumn,
448
            ];
449
        }
450
451 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...
452 9
            'table' => $this->generateTableName($table),
453 9
            'fields' => $fields,
454 9
            'foreignKeys' => $foreignKeys,
455 9
            'tableComment' => $this->comment,
456
        ]));
457
    }
458
459
    /**
460
     * If `useTablePrefix` equals true, then the table name will contain the
461
     * prefix format.
462
     *
463
     * @param string $tableName the table name to generate.
464
     * @return string
465
     * @since 2.0.8
466
     */
467 9
    protected function generateTableName($tableName)
468
    {
469 9
        if (!$this->useTablePrefix) {
470 9
            return $tableName;
471
        }
472
473 2
        return '{{%' . $tableName . '}}';
474
    }
475
476
    /**
477
     * Parse the command line migration fields.
478
     * @return array parse result with following fields:
479
     *
480
     * - fields: array, parsed fields
481
     * - foreignKeys: array, detected foreign keys
482
     *
483
     * @since 2.0.7
484
     */
485 9
    protected function parseFields()
486
    {
487 9
        $fields = [];
488 9
        $foreignKeys = [];
489
490 9
        foreach ($this->fields as $index => $field) {
491 4
            $chunks = preg_split('/\s?:\s?/', $field, null);
492 4
            $property = array_shift($chunks);
493
494 4
            foreach ($chunks as $i => &$chunk) {
495 4
                if (strncmp($chunk, 'foreignKey', 10) === 0) {
496 2
                    preg_match('/foreignKey\((\w*)\s?(\w*)\)/', $chunk, $matches);
497 2
                    $foreignKeys[$property] = [
498 2
                        'table' => isset($matches[1])
499 2
                            ? $matches[1]
500 2
                            : preg_replace('/_id$/', '', $property),
501 2
                        'column' => !empty($matches[2])
502
                            ? $matches[2]
503
                            : null,
504
                    ];
505
506 2
                    unset($chunks[$i]);
507 2
                    continue;
508
                }
509
510 4
                if (!preg_match('/^(.+?)\(([^(]+)\)$/', $chunk)) {
511 4
                    $chunk .= '()';
512
                }
513
            }
514 4
            $fields[] = [
515 4
                'property' => $property,
516 4
                'decorators' => implode('->', $chunks),
517
            ];
518
        }
519
520
        return [
521 9
            'fields' => $fields,
522 9
            'foreignKeys' => $foreignKeys,
523
        ];
524
    }
525
526
    /**
527
     * Adds default primary key to fields list if there's no primary key specified.
528
     * @param array $fields parsed fields
529
     * @since 2.0.7
530
     */
531 2
    protected function addDefaultPrimaryKey(&$fields)
532
    {
533 2
        foreach ($fields as $field) {
534 2
            if (false !== strripos($field['decorators'], 'primarykey()')) {
535 2
                return;
536
            }
537
        }
538 2
        array_unshift($fields, ['property' => 'id', 'decorators' => 'primaryKey()']);
539 2
    }
540
}
541