-
Notifications
You must be signed in to change notification settings - Fork 0
/
Migration.php
516 lines (443 loc) · 19.1 KB
/
Migration.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
<?php
namespace futuretek\migrations;
use Yii;
use yii\db\ColumnSchemaBuilder;
use yii\db\Query;
use yii\db\Schema;
/**
* Class Migration
*
* @package futuretek\migrations
* @author Lukas Cerny <[email protected]>
* @license Apache-2.0
* @link http://www.futuretek.cz
*/
class Migration
{
const BASE_MIGRATION = 'm000000_000000_base';
public $migrationTable = 'migration';
private $_log = [];
private $_lastStatus = '';
private $_migrations = [];
private $_applied = [];
public function getNewMigrations()
{
//Load applied migrations
$this->getAppliedMigrations();
$this->_migrations = [];
//Main app migrations
$this->getNewMigrationsForPath(Yii::$app->basePath . DIRECTORY_SEPARATOR . 'migrations');
$pathsExplored = [];
//Extensions migrations
foreach (Yii::$app->extensions as $extension) {
$migPath = Yii::$app->vendorPath . DIRECTORY_SEPARATOR . $extension['name'] . DIRECTORY_SEPARATOR . 'migrations';
if (is_dir($migPath)) {
$pathsExplored[] = str_replace('\\', '/', $migPath);
$this->getNewMigrationsForPath($migPath);
}
}
//Modules migrations
foreach (Yii::$app->modules as $name => $module) {
if (!is_array($module) || !array_key_exists('class', $module)) {
Yii::warning("Class for module {$name} not specified.", 'migrations');
continue;
}
$ref = new \ReflectionClass($module['class']);
$migPath = dirname($ref->getFileName()) . DIRECTORY_SEPARATOR . 'migrations';
if (is_dir($migPath) && !in_array(str_replace('\\', '/', $migPath), $pathsExplored, true)) {
$pathsExplored[] = str_replace('\\', '/', $migPath);
$this->getNewMigrationsForPath($migPath);
}
}
sort($this->_migrations);
return $this->_migrations;
}
public function getLastStatus()
{
return $this->_lastStatus;
}
public function getAppliedMigrations()
{
$history = $this->getMigrationHistory(null);
foreach ($history as $migration) {
$this->_applied[substr($migration['version'], 1, 13)] = $migration;
}
return $this->_applied;
}
public function getLog()
{
return $this->_log;
}
protected function getNewMigrationsForPath($migrationPath)
{
$handle = opendir($migrationPath);
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') {
continue;
}
$path = $migrationPath . DIRECTORY_SEPARATOR . $file;
if (preg_match('/^(m(\d{6}_\d{6})_.*?)\.php$/', $file, $matches) && is_file($path) && !array_key_exists($matches[2], $this->_applied)) {
$this->_migrations[] = [
'version' => $matches[1],
'path' => $migrationPath,
];
}
}
closedir($handle);
}
public function getNewMigrationsForModule($migrationPath, $module)
{
$handle = opendir($migrationPath);
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') {
continue;
}
$path = $migrationPath . DIRECTORY_SEPARATOR . $file;
if (preg_match('/^(m(\d{6}_\d{6})_.*?)\.php$/', $file, $matches) && is_file($path) && !array_key_exists($matches[2], $this->_applied)) {
$this->_migrations[] = [
'version' => $matches[1],
'path' => $migrationPath,
'module' => $module,
];
}
}
closedir($handle);
sort($this->_migrations);
}
protected function getMigrationHistory($limit, $module = null)
{
if (Yii::$app->db->schema->getTableSchema($this->migrationTable, true) === null) {
$this->createMigrationHistoryTable();
}
$query = new Query;
$rows = $query->select(['version', 'path', 'apply_time', 'app_version', 'module'])
->from($this->migrationTable)
->orderBy('version DESC')
->where(['module' => $module])
->limit($limit)
->createCommand()
->queryAll();
$count = count($rows);
for ($i = 0; $i < $count; $i++) {
$rows[$i]['position'] = $i + 1;
if ($rows[$i]['version'] === self::BASE_MIGRATION) {
unset($rows[$i]);
break;
}
}
return $rows;
}
protected function createMigrationHistoryTable()
{
$tableName = Yii::$app->db->schema->getRawTableName($this->migrationTable);
$this->_log[] = "Creating migration history table \"$tableName\"...";
Yii::$app->db->createCommand()->createTable(
$this->migrationTable,
[
'version' => (new ColumnSchemaBuilder(Schema::TYPE_STRING, 180))->notNull(),
'path' => (new ColumnSchemaBuilder(Schema::TYPE_STRING, 255)),
'apply_time' => new ColumnSchemaBuilder(Schema::TYPE_INTEGER),
'app_version' => (new ColumnSchemaBuilder(Schema::TYPE_STRING, 128)),
'module' => (new ColumnSchemaBuilder(Schema::TYPE_STRING, 32)),
]
)->execute();
Yii::$app->db->createCommand()->addPrimaryKey('migration_PRIMARY', $this->migrationTable, 'version')->execute();
Yii::$app->db->createCommand()->insert(
$this->migrationTable,
[
'version' => self::BASE_MIGRATION,
'path' => '',
'apply_time' => time(),
'app_version' => Yii::$app->version,
'module' => null,
]
)->execute();
$this->_log[] = 'done.';
}
protected function addMigrationHistory($version, $path, $module = null)
{
$command = Yii::$app->db->createCommand();
$command->insert(
$this->migrationTable,
[
'version' => $version,
'path' => $path,
'apply_time' => time(),
'app_version' => Yii::$app->version,
'module' => $module,
]
)->execute();
}
protected function removeMigrationHistory($version, $path, $module = null)
{
$command = Yii::$app->db->createCommand();
$command->delete(
$this->migrationTable,
[
'version' => $version,
'path' => $path,
'module' => $module,
]
)->execute();
}
/**
* Creates a new migration instance.
*
* @param string $class the migration class name
* @param string $path the migration file path
*
* @return \yii\db\Migration the migration instance
*/
protected function createMigration($class, $path)
{
$file = $path . DIRECTORY_SEPARATOR . $class . '.php';
require_once $file;
//Try to detect namespace
if (!class_exists($class) && preg_match('/namespace ([\w_\\\\]*);/', file_get_contents($file), $matches)) {
$class = $matches[1] . '\\' . $class;
}
return new $class(['db' => Yii::$app->db]);
}
/**
* Upgrades with the specified migration class.
*
* @param string $class the migration class name
* @param string $path the migration file path
* @param string $module the migration module
*
* @return bool whether the migration is successful
*/
protected function migrateUp($class, $path, $module = null)
{
if ($class === self::BASE_MIGRATION) {
$this->_lastStatus = Yii::t('fts-migrations', 'Base migration is already applied.');
return true;
}
$this->_log[] = "*** applying $class in $path" . ($module !== null ? ' for module ' . $module : '');
$start = microtime(true);
$migration = $this->createMigration($class, $path);
ob_start();
$result = $migration->up();
$this->_log[] = ob_get_contents();
ob_end_clean();
if ($result !== false) {
$this->addMigrationHistory($class, $path, $module);
$time = microtime(true) - $start;
$this->_log[] = "*** applied $class (time: " . sprintf('%.3f', $time) . 's)';
$this->_lastStatus = $module === null ? Yii::t('fts-migrations', 'Migration {name} successfully applied.', ['name' => $class]) : Yii::t('fts-migrations', 'Migration {name} for module {module} successfully applied.', ['name' => $class, 'module' => $module]);
return true;
}
$time = microtime(true) - $start;
$this->_log[] = "*** failed to apply $class (time: " . sprintf('%.3f', $time) . 's)';
$this->_lastStatus = $module === null ? Yii::t('fts-migrations', 'Failed to apply migration {name}.', ['name' => $class]) : Yii::t('fts-migrations', 'Failed to apply migration {name} for module {module}.', ['name' => $class, 'module' => $module]);
return false;
}
/**
* Downgrades with the specified migration class.
*
* @param string $class the migration class name
* @param string $path the migration file path
* @param string $module the migration module
*
* @return boolean whether the migration is successful
*/
protected function migrateDown($class, $path, $module = null)
{
if ($class === self::BASE_MIGRATION) {
return true;
}
$this->_log[] = "*** reverting $class in $path" . ($module !== null ? ' for module ' . $module : '');
$start = microtime(true);
$migration = $this->createMigration($class, $path);
if ($migration->down() !== false) {
$this->removeMigrationHistory($class, $path, $module);
$time = microtime(true) - $start;
$this->_log[] = "*** reverted $class (time: " . sprintf('%.3f', $time) . 's)';
$this->_lastStatus = $module === null ? Yii::t('fts-migrations', 'Migration {name} successfully reverted.', ['name' => $class]) : Yii::t('fts-migrations', 'Migration {name} for module {module} successfully reverted.', ['name' => $class, 'module' => $module]);
return true;
}
$time = microtime(true) - $start;
$this->_log[] = "*** failed to revert $class (time: " . sprintf('%.3f', $time) . 's)';
$this->_lastStatus = $module === null ? Yii::t('fts-migrations', 'Failed to revert migration {name}.', ['name' => $class]) : Yii::t('fts-migrations', 'Failed to revert migration {name} for module {module}.', ['name' => $class, 'module' => $module]);
return false;
}
/**
* Upgrades the application by applying new migrations.
* For example,
*
* ~~~
* yii migrate # apply all new migrations
* yii migrate 3 # apply the first 3 new migrations
* ~~~
*
* @param integer $limit the number of new migrations to be applied. If 0, it means
* applying all available new migrations.
*
* @return integer the status of the action execution. 0 means normal, other values mean abnormal.
*/
public function actionUp($limit = 0)
{
$this->getNewMigrations();
if (0 === count($this->_migrations)) {
$this->_log[] = 'No new migration found. Your system is up-to-date.';
$this->_lastStatus = Yii::t('fts-migrations', 'No new migration found. Your system is up-to-date.');
return true;
}
$total = count($this->_migrations);
$limit = (int)$limit;
if ($limit > 0) {
$this->_migrations = array_slice($this->_migrations, 0, $limit);
}
$n = count($this->_migrations);
if ($n === $total) {
$this->_log[] = "Total $n new " . ($n === 1 ? 'migration' : 'migrations') . ' to be applied:';
} else {
$this->_log[] = "Total $n out of $total new " . ($total === 1 ? 'migration' : 'migrations') . ' to be applied:';
}
foreach ($this->_migrations as $migration) {
if (!$this->migrateUp($migration['version'], $migration['path'])) {
$this->_log[] = 'Migration failed. The rest of the migrations are canceled.';
$this->_lastStatus = Yii::t('fts-migrations', 'Failed to apply migration {name}.', ['name' => $migration['version']]);
return false;
}
}
$this->_log[] = 'Migrated up successfully.';
$this->_lastStatus = Yii::t('fts-migrations', 'Successfully applied {count, plural, one{one migration} other{# migrations}}.', ['count' => count($this->_migrations)]);
return true;
}
/**
* Downgrades the application by reverting old migrations.
* For example,
*
* ~~~
* yii migrate/down # revert the last migration
* yii migrate/down 3 # revert the last 3 migrations
* yii migrate/down all # revert all migrations
* ~~~
*
* @param integer|null $limit the number of migrations to be reverted. Defaults to 1,
* meaning the last applied migration will be reverted.
*
* @return integer the status of the action execution. 0 means normal, other values mean abnormal.
*/
public function actionDown($limit = 1)
{
if ($limit === 'all') {
$limit = null;
} else {
$limit = (int)$limit;
if ($limit < 1) {
$this->_log[] = 'The step argument must be greater than 0.';
$this->_lastStatus = Yii::t('fts-migrations', 'The step argument must be greater than 0.');
return false;
}
}
$migrations = $this->getMigrationHistory($limit);
if (0 === count($migrations)) {
$this->_log[] = 'No migration has been done before.';
$this->_lastStatus = Yii::t('fts-migrations', 'No migration has been done before.');
return true;
}
$n = count($migrations);
$this->_log[] = "Total $n " . ($n === 1 ? 'migration' : 'migrations') . ' to be reverted:';
foreach ($migrations as $migration) {
$this->_log[] = ' ' . $migration['version'] . '(' . $migration['path'] . ')';
}
foreach ($migrations as $migration) {
if (!$this->migrateDown($migration['version'], $migration['path'])) {
$this->_log[] = 'Migration failed. The rest of the migrations are canceled.';
$this->_lastStatus = Yii::t('fts-migrations', 'Failed to revert migration {name}.', ['name' => $migration['version']]);
return false;
}
}
$this->_log[] = 'Migrated down successfully.';
$this->_lastStatus = Yii::t('fts-migrations', 'Successfully reverted {count, plural, one{# migration} other{# migrations}}.', ['count' => count($migrations)]);
return true;
}
/**
* Upgrades the module by applying new migrations.
*
* @param string $path the migration file path
* @param string $module the migration module
* @param integer $limit the number of new migrations to be applied. If 0, it means applying all available new migrations.
*
* @return integer the status of the action execution. 0 means normal, other values mean abnormal.
*/
public function actionModuleUp($path, $module, $limit = 0)
{
$this->getNewMigrationsForModule($path, $module);
if (0 === count($this->_migrations)) {
$this->_log[] = 'No new migration found. Your system is up-to-date.';
$this->_lastStatus = Yii::t('fts-migrations', 'No new migration found. Your system is up-to-date.');
return true;
}
$total = count($this->_migrations);
$limit = (int)$limit;
if ($limit > 0) {
$this->_migrations = array_slice($this->_migrations, 0, $limit);
}
$n = count($this->_migrations);
if ($n === $total) {
$this->_log[] = "Total $n new " . ($n === 1 ? 'migration' : 'migrations') . ' to be applied:';
} else {
$this->_log[] = "Total $n out of $total new " . ($total === 1 ? 'migration' : 'migrations') . ' to be applied:';
}
foreach ($this->_migrations as $migration) {
if (!$this->migrateUp($migration['version'], $migration['path'], $module)) {
$this->_log[] = 'Migration failed. The rest of the migrations are canceled.';
$this->_lastStatus = Yii::t('fts-migrations', 'Failed to apply migration {name}.', ['name' => $migration['version']]);
return false;
}
}
$this->_log[] = 'Migrated up successfully.';
$this->_lastStatus = Yii::t('fts-migrations', 'Successfully applied {count, plural, one{one migration} other{# migrations}}.', ['count' => count($this->_migrations)]);
return true;
}
/**
* Downgrades the module by reverting old migrations.
* For example,
*
* @param string $module the migration module
* @param integer|null $limit the number of migrations to be reverted. Defaults to 1, meaning the last applied migration will be reverted.
*
* @return integer the status of the action execution. 0 means normal, other values mean abnormal.
*/
public function actionModuleDown($module, $limit = 1)
{
if ($limit === 'all') {
$limit = null;
} else {
$limit = (int)$limit;
if ($limit < 1) {
$this->_log[] = 'The step argument must be greater than 0.';
$this->_lastStatus = Yii::t('fts-migrations', 'The step argument must be greater than 0.');
return false;
}
}
$migrations = $this->getMigrationHistory($limit, $module);
if (0 === count($migrations)) {
$this->_log[] = 'No migration has been done before.';
$this->_lastStatus = Yii::t('fts-migrations', 'No migration has been done before.');
return true;
}
$n = count($migrations);
$this->_log[] = "Total $n " . ($n === 1 ? 'migration' : 'migrations') . ' to be reverted:';
foreach ($migrations as $migration) {
$this->_log[] = ' ' . $migration['version'] . '(' . $migration['path'] . ')';
}
foreach ($migrations as $migration) {
if (!$this->migrateDown($migration['version'], $migration['path'], $module)) {
$this->_log[] = 'Migration failed. The rest of the migrations are canceled.';
$this->_lastStatus = Yii::t('fts-migrations', 'Failed to revert migration {name}.', ['name' => $migration['version']]);
return false;
}
}
$this->_log[] = 'Migrated down successfully.';
$this->_lastStatus = Yii::t('fts-migrations', 'Successfully reverted {count, plural, one{# migration} other{# migrations}}.', ['count' => count($migrations)]);
return true;
}
public function getDbVersion()
{
return (new Query())->select('version')->from($this->migrationTable)->orderBy(['version' => SORT_DESC])->limit(1)->scalar();
}
}