Completed
Push — remove-intl-polyfills ( 129df4...a6e727 )
by Alexander
16:22 queued 12:49
created

MigrateController::addDefaultPrimaryKey()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 6
cts 6
cp 1
rs 9.6666
c 0
b 0
f 0
cc 3
eloc 5
nc 3
nop 1
crap 3
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::class);
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 2
            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 1
            $db->createCommand()->dropTable($schema->name)->execute();
314 1
            $this->stdout("Table {$schema->name} dropped.\n");
315
        }
316 1
    }
317
318
    /**
319
     * {@inheritdoc}
320
     */
321 33
    protected function removeMigrationHistory($version)
322
    {
323 33
        $command = $this->db->createCommand();
324 33
        $command->delete($this->migrationTable, [
325 33
            'version' => $version,
326 33
        ])->execute();
327 33
    }
328
329
    private $_migrationNameLimit;
330
331
    /**
332
     * {@inheritdoc}
333
     * @since 2.0.13
334
     */
335 52
    protected function getMigrationNameLimit()
336
    {
337 52
        if ($this->_migrationNameLimit !== null) {
338 8
            return $this->_migrationNameLimit;
339
        }
340 52
        $tableSchema = $this->db->schema ? $this->db->schema->getTableSchema($this->migrationTable, true) : null;
341 52
        if ($tableSchema !== null) {
342 43
            return $this->_migrationNameLimit = $tableSchema->columns['version']->size;
343
        }
344
345 9
        return static::MAX_NAME_LENGTH;
346
    }
347
348
    /**
349
     * {@inheritdoc}
350
     * @since 2.0.8
351
     */
352 9
    protected function generateMigrationSourceCode($params)
353
    {
354 9
        $parsedFields = $this->parseFields();
355 9
        $fields = $parsedFields['fields'];
356 9
        $foreignKeys = $parsedFields['foreignKeys'];
357
358 9
        $name = $params['name'];
359
360 9
        $templateFile = $this->templateFile;
361 9
        $table = null;
362 9
        if (preg_match('/^create_junction(?:_table_for_|_for_|_)(.+)_and_(.+)_tables?$/', $name, $matches)) {
363 1
            $templateFile = $this->generatorTemplateFiles['create_junction'];
364 1
            $firstTable = $matches[1];
365 1
            $secondTable = $matches[2];
366
367 1
            $fields = array_merge(
368
                [
369
                    [
370 1
                        'property' => $firstTable . '_id',
371 1
                        'decorators' => 'integer()',
372
                    ],
373
                    [
374 1
                        'property' => $secondTable . '_id',
375 1
                        'decorators' => 'integer()',
376
                    ],
377
                ],
378 1
                $fields,
379
                [
380
                    [
381
                        'property' => 'PRIMARY KEY(' .
382 1
                            $firstTable . '_id, ' .
383 1
                            $secondTable . '_id)',
384
                    ],
385
                ]
386
            );
387
388 1
            $foreignKeys[$firstTable . '_id']['table'] = $firstTable;
389 1
            $foreignKeys[$secondTable . '_id']['table'] = $secondTable;
390 1
            $foreignKeys[$firstTable . '_id']['column'] = null;
391 1
            $foreignKeys[$secondTable . '_id']['column'] = null;
392 1
            $table = $firstTable . '_' . $secondTable;
393 8
        } elseif (preg_match('/^add_(.+)_columns?_to_(.+)_table$/', $name, $matches)) {
394 1
            $templateFile = $this->generatorTemplateFiles['add_column'];
395 1
            $table = $matches[2];
396 7
        } elseif (preg_match('/^drop_(.+)_columns?_from_(.+)_table$/', $name, $matches)) {
397 1
            $templateFile = $this->generatorTemplateFiles['drop_column'];
398 1
            $table = $matches[2];
399 6
        } elseif (preg_match('/^create_(.+)_table$/', $name, $matches)) {
400 1
            $this->addDefaultPrimaryKey($fields);
401 1
            $templateFile = $this->generatorTemplateFiles['create_table'];
402 1
            $table = $matches[1];
403 6
        } elseif (preg_match('/^drop_(.+)_table$/', $name, $matches)) {
404 2
            $this->addDefaultPrimaryKey($fields);
405 2
            $templateFile = $this->generatorTemplateFiles['drop_table'];
406 2
            $table = $matches[1];
407
        }
408
409 9
        foreach ($foreignKeys as $column => $foreignKey) {
410 3
            $relatedColumn = $foreignKey['column'];
411 3
            $relatedTable = $foreignKey['table'];
412
            // Since 2.0.11 if related column name is not specified,
413
            // we're trying to get it from table schema
414
            // @see https://github.com/yiisoft/yii2/issues/12748
415 3
            if ($relatedColumn === null) {
416 3
                $relatedColumn = 'id';
417
                try {
418 3
                    $this->db = Instance::ensure($this->db, Connection::class);
419 3
                    $relatedTableSchema = $this->db->getTableSchema($relatedTable);
420 3
                    if ($relatedTableSchema !== null) {
421
                        $primaryKeyCount = count($relatedTableSchema->primaryKey);
422
                        if ($primaryKeyCount === 1) {
423
                            $relatedColumn = $relatedTableSchema->primaryKey[0];
424
                        } elseif ($primaryKeyCount > 1) {
425
                            $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);
426
                        } elseif ($primaryKeyCount === 0) {
427 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);
428
                        }
429
                    }
430
                } catch (\ReflectionException $e) {
431
                    $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);
432
                }
433
            }
434 3
            $foreignKeys[$column] = [
435 3
                'idx' => $this->generateTableName("idx-$table-$column"),
436 3
                'fk' => $this->generateTableName("fk-$table-$column"),
437 3
                'relatedTable' => $this->generateTableName($relatedTable),
438 3
                'relatedColumn' => $relatedColumn,
439
            ];
440
        }
441
442 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...
443 9
            'table' => $this->generateTableName($table),
444 9
            'fields' => $fields,
445 9
            'foreignKeys' => $foreignKeys,
446 9
            'tableComment' => $this->comment,
447
        ]));
448
    }
449
450
    /**
451
     * If `useTablePrefix` equals true, then the table name will contain the
452
     * prefix format.
453
     *
454
     * @param string $tableName the table name to generate.
455
     * @return string
456
     * @since 2.0.8
457
     */
458 9
    protected function generateTableName($tableName)
459
    {
460 9
        if (!$this->useTablePrefix) {
461 9
            return $tableName;
462
        }
463
464 2
        return '{{%' . $tableName . '}}';
465
    }
466
467
    /**
468
     * Parse the command line migration fields.
469
     * @return array parse result with following fields:
470
     *
471
     * - fields: array, parsed fields
472
     * - foreignKeys: array, detected foreign keys
473
     *
474
     * @since 2.0.7
475
     */
476 9
    protected function parseFields()
477
    {
478 9
        $fields = [];
479 9
        $foreignKeys = [];
480
481 9
        foreach ($this->fields as $index => $field) {
482 4
            $chunks = preg_split('/\s?:\s?/', $field, null);
483 4
            $property = array_shift($chunks);
484
485 4
            foreach ($chunks as $i => &$chunk) {
486 4
                if (strncmp($chunk, 'foreignKey', 10) === 0) {
487 2
                    preg_match('/foreignKey\((\w*)\s?(\w*)\)/', $chunk, $matches);
488 2
                    $foreignKeys[$property] = [
489 2
                        'table' => $matches[1]
490 2
                            ?? preg_replace('/_id$/', '', $property),
491 2
                        'column' => !empty($matches[2])
492
                            ? $matches[2]
493
                            : null,
494
                    ];
495
496 2
                    unset($chunks[$i]);
497 2
                    continue;
498
                }
499
500 4
                if (!preg_match('/^(.+?)\(([^(]+)\)$/', $chunk)) {
501 4
                    $chunk .= '()';
502
                }
503
            }
504 4
            $fields[] = [
505 4
                'property' => $property,
506 4
                'decorators' => implode('->', $chunks),
507
            ];
508
        }
509
510
        return [
511 9
            'fields' => $fields,
512 9
            'foreignKeys' => $foreignKeys,
513
        ];
514
    }
515
516
    /**
517
     * Adds default primary key to fields list if there's no primary key specified.
518
     * @param array $fields parsed fields
519
     * @since 2.0.7
520
     */
521 2
    protected function addDefaultPrimaryKey(&$fields)
522
    {
523 2
        foreach ($fields as $field) {
524 2
            if (false !== strripos($field['decorators'], 'primarykey()')) {
525 2
                return;
526
            }
527
        }
528 2
        array_unshift($fields, ['property' => 'id', 'decorators' => 'primaryKey()']);
529 2
    }
530
}
531