This repository was archived by the owner on May 16, 2020. It is now read-only.
forked from codeigniter4/CodeIgniter4
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMigrationRunner.php
More file actions
800 lines (682 loc) · 18.6 KB
/
Copy pathMigrationRunner.php
File metadata and controls
800 lines (682 loc) · 18.6 KB
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
<?php
/**
* CodeIgniter
*
* An open source application development framework for PHP
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014-2019 British Columbia Institute of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @package CodeIgniter
* @author CodeIgniter Dev Team
* @copyright 2014-2019 British Columbia Institute of Technology (https://bcit.ca/)
* @license https://opensource.org/licenses/MIT MIT License
* @link https://codeigniter.com
* @since Version 4.0.0
* @filesource
*/
namespace CodeIgniter\Database;
use Config\Services;
use CodeIgniter\CLI\CLI;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Exceptions\ConfigException;
/**
* Class MigrationRunner
*/
class MigrationRunner
{
/**
* Whether or not migrations are allowed to run.
*
* @var boolean
*/
protected $enabled = false;
/**
* The type of migrations to use (sequential or timestamp)
*
* @var string
*/
protected $type;
/**
* Name of table to store meta information
*
* @var string
*/
protected $table;
/**
* The version that current() will take us to.
*
* @var integer
*/
protected $currentVersion = 0;
/**
* The Namespace where migrations can be found.
*
* @var string
*/
protected $namespace;
/**
* The database Group to migrate.
*
* @var string
*/
protected $group;
/**
* The migration name.
*
* @var string
*/
protected $name;
/**
* The pattern used to locate migration file versions.
*
* @var string
*/
protected $regex;
/**
* The main database connection. Used to store
* migration information in.
*
* @var ConnectionInterface
*/
protected $db;
/**
* If true, will continue instead of throwing
* exceptions.
*
* @var boolean
*/
protected $silent = false;
/**
* used to return messages for CLI.
*
* @var array
*/
protected $cliMessages = [];
/**
* Tracks whether we have already ensured
* the table exists or not.
*
* @var boolean
*/
protected $tableChecked = false;
/**
* The full path to locate migration files.
*
* @var string
*/
protected $path;
//--------------------------------------------------------------------
/**
* Constructor.
*
* When passing in $db, you may pass any of the following to connect:
* - group name
* - existing connection instance
* - array of database configuration values
*
* @param BaseConfig $config
* @param \CodeIgniter\Database\ConnectionInterface|array|string $db
*
* @throws ConfigException
*/
public function __construct(BaseConfig $config, $db = null)
{
$this->enabled = $config->enabled ?? false;
$this->type = $config->type ?? 'timestamp';
$this->table = $config->table ?? 'migrations';
$this->currentVersion = $config->currentVersion ?? 0;
// Default name space is the app namespace
$this->namespace = APP_NAMESPACE;
// get default database group
$config = config('Database');
$this->group = $config->defaultGroup;
unset($config);
if (! in_array($this->type, ['sequential', 'timestamp']))
{
throw ConfigException::forInvalidMigrationType($this->type);
}
// Migration basename regex
$this->regex = ($this->type === 'timestamp') ? '/^\d{14}_(\w+)$/' : '/^\d{3}_(\w+)$/';
// If no db connection passed in, use
// default database group.
$this->db = db_connect($db);
}
//--------------------------------------------------------------------
/**
* Migrate to a schema version
*
* Calls each migration step required to get to the schema version of
* choice
*
* @param string $targetVersion Target schema version
* @param string|null $namespace
* @param string|null $group
*
* @return mixed Current version string on success, FALSE on failure or no migrations are found
* @throws ConfigException
*/
public function version(string $targetVersion, string $namespace = null, string $group = null)
{
if (! $this->enabled)
{
throw ConfigException::forDisabledMigrations();
}
$this->ensureTable();
// Set Namespace if not null
if (! is_null($namespace))
{
$this->setNamespace($namespace);
}
// Set database group if not null
if (! is_null($group))
{
$this->setGroup($group);
}
// Sequential versions need adjusting to 3 places so they can be found later.
if ($this->type === 'sequential')
{
$targetVersion = str_pad($targetVersion, 3, '0', STR_PAD_LEFT);
}
$migrations = $this->findMigrations();
if (empty($migrations))
{
return true;
}
// Get Namespace current version
// Note: We use strings, so that timestamp versions work on 32-bit systems
$currentVersion = $this->getVersion();
if ($targetVersion > $currentVersion)
{
// Moving Up
$method = 'up';
ksort($migrations);
}
else
{
// Moving Down, apply in reverse order
$method = 'down';
krsort($migrations);
}
// Check Migration consistency
$this->checkMigrations($migrations, $method, $targetVersion);
// loop migration for each namespace (module)
$migrationStatus = false;
foreach ($migrations as $version => $migration)
{
// Only include migrations within the scope
if (($method === 'up' && $version > $currentVersion && $version <= $targetVersion) || ( $method === 'down' && $version <= $currentVersion && $version > $targetVersion))
{
$migrationStatus = false;
include_once $migration->path;
// Get namespaced class name
$class = $this->namespace . '\Database\Migrations\Migration_' . ($migration->name);
$this->setName($migration->name);
// Validate the migration file structure
if (! class_exists($class, false))
{
throw new \RuntimeException(sprintf(lang('Migrations.classNotFound'), $class));
}
// Forcing migration to selected database group
$instance = new $class(\Config\Database::forge($this->group));
if (! is_callable([$instance, $method]))
{
throw new \RuntimeException(sprintf(lang('Migrations.missingMethod'), $method));
}
$instance->{$method}();
if ($method === 'up')
{
$this->addHistory($migration->version);
}
elseif ($method === 'down')
{
$this->removeHistory($migration->version);
}
$migrationStatus = true;
}
}
return ($migrationStatus) ? $targetVersion : false;
}
//--------------------------------------------------------------------
/**
* Sets the schema to the latest migration
*
* @param string|null $namespace
* @param string|null $group
*
* @return mixed Current version string on success, FALSE on failure
*/
public function latest(string $namespace = null, string $group = null)
{
$this->ensureTable();
// Set Namespace if not null
if (! is_null($namespace))
{
$this->setNamespace($namespace);
}
// Set database group if not null
if (! is_null($group))
{
$this->setGroup($group);
}
$migrations = $this->findMigrations();
$lastMigration = end($migrations)->version ?? 0;
// Calculate the last migration step from existing migration
// filenames and proceed to the standard version migration
return $this->version($lastMigration);
}
//--------------------------------------------------------------------
/**
* Sets the schema to the latest migration for all namespaces
*
* @param string|null $group
*
* @return boolean
*/
public function latestAll(string $group = null): bool
{
$this->ensureTable();
// Set database group if not null
if (! is_null($group))
{
$this->setGroup($group);
}
// Get all namespaces from the autoloader
$namespaces = Services::autoloader()->getNamespace();
foreach ($namespaces as $namespace => $paths)
{
$this->setNamespace($namespace);
$migrations = $this->findMigrations();
if (empty($migrations))
{
continue;
}
$lastMigration = end($migrations)->version;
// No New migrations to add
if ($lastMigration === $this->getVersion())
{
continue;
}
// Calculate the last migration step from existing migration
// filenames and proceed to the standard version migration
$this->version($lastMigration);
}
return true;
}
//--------------------------------------------------------------------
/**
* Sets the (APP_NAMESPACE) schema to $currentVersion in migration config file
*
* @param string|null $group
*
* @return mixed Current version string on success, FALSE on failure or no migrations are found
*/
public function current(string $group = null)
{
$this->ensureTable();
// Set database group if not null
if (! is_null($group))
{
$this->setGroup($group);
}
return $this->version($this->currentVersion);
}
//--------------------------------------------------------------------
/**
* Retrieves list of available migration scripts for one namespace
*
* @return array list of migrations as $version for one namespace
*/
public function findMigrations(): array
{
$migrations = [];
// If $this->path contains a valid directory use it.
if (! empty($this->path))
{
helper('filesystem');
$dir = rtrim($this->path, DIRECTORY_SEPARATOR) . '/';
$files = get_filenames($dir, true);
}
// Otherwise use FileLocator to search files in the subdirectory of the namespace
else
{
$locator = Services::locator(true);
$files = $locator->listNamespaceFiles($this->namespace, '/Database/Migrations/');
}
// Load all *_*.php files in the migrations path
// We can't use glob if we want it to be testable....
foreach ($files as $file)
{
if (substr($file, -4) !== '.php')
{
continue;
}
// Remove the extension
$name = basename($file, '.php');
// Filter out non-migration files
if (preg_match($this->regex, $name))
{
// Create migration object using stdClass
$migration = new \stdClass();
// Get migration version number
$migration->version = $this->getMigrationNumber($name);
$migration->name = $this->getMigrationName($name);
$migration->path = ! empty($this->path) && strpos($file, $this->path) !== 0
? $this->path . $file
: $file;
// Add to migrations[version]
$migrations[$migration->version] = $migration;
}
}
ksort($migrations);
return $migrations;
}
//--------------------------------------------------------------------
/**
* checks if the list of available migration scripts list are consistent
* if sequential check if no gaps and check if all consistent with migrations table if downgrading
* if timestamp check if consistent with migrations table if downgrading
*
* @param array $migrations
* @param string $method
* @param string $targetVersion
*
* @return boolean
*/
protected function checkMigrations(array $migrations, string $method, string $targetVersion): bool
{
// Check if no migrations found
if (empty($migrations))
{
if ($this->silent)
{
return false;
}
throw new \RuntimeException(lang('Migrations.empty'));
}
// Check if $targetVersion file is found
if ((int)$targetVersion !== 0 && ! array_key_exists($targetVersion, $migrations))
{
if ($this->silent)
{
return false;
}
throw new \RuntimeException(lang('Migrations.notFound') . $targetVersion);
}
ksort($migrations);
if ($method === 'down')
{
$history_migrations = $this->getHistory($this->group);
$history_size = count($history_migrations) - 1;
}
// Check for sequence gaps
$loop = 0;
foreach ($migrations as $migration)
{
if ($this->type === 'sequential' && abs($migration->version - $loop) > 1)
{
throw new \RuntimeException(lang('Migrations.gap') . ' ' . $migration->version);
}
// Check if all old migration files are all available to do downgrading
if ($method === 'down')
{
if ($loop <= $history_size && $history_migrations[$loop]['version'] !== $migration->version)
{
throw new \RuntimeException(lang('Migrations.gap') . ' ' . $migration->version);
}
}
$loop ++;
}
return true;
}
//--------------------------------------------------------------------
/**
* Sets the path to the base directory that will be used
* when locating migrations. If left null, the value will
* be chosen from $this->namespace's directory.
*
* @param string|null $path
*
* @return $this
*/
public function setPath(string $path = null)
{
$this->path = $path;
return $this;
}
/**
* Set namespace.
* Allows other scripts to modify on the fly as needed.
*
* @param string $namespace
*
* @return MigrationRunner
*/
public function setNamespace(string $namespace)
{
$this->namespace = $namespace;
return $this;
}
//--------------------------------------------------------------------
/**
* Set database Group.
* Allows other scripts to modify on the fly as needed.
*
* @param string $group
*
* @return MigrationRunner
*/
public function setGroup(string $group)
{
$this->group = $group;
return $this;
}
//--------------------------------------------------------------------
/**
* Set migration Name.
*
* @param string $name
*
* @return \CodeIgniter\Database\MigrationRunner
*/
public function setName(string $name)
{
$this->name = $name;
return $this;
}
//--------------------------------------------------------------------
/**
* Grabs the full migration history from the database.
*
* @param string $group
*
* @return array
*/
public function getHistory(string $group = 'default'): array
{
$this->ensureTable();
$query = $this->db->table($this->table)
->where('group', $group)
->where('namespace', $this->namespace)
->orderBy('version', 'ASC')
->get();
if (! $query)
{
return [];
}
return $query->getResultArray();
}
//--------------------------------------------------------------------
/**
* If $silent == true, then will not throw exceptions and will
* attempt to continue gracefully.
*
* @param boolean $silent
*
* @return MigrationRunner
*/
public function setSilent(bool $silent)
{
$this->silent = $silent;
return $this;
}
//--------------------------------------------------------------------
/**
* Extracts the migration number from a filename
*
* @param string $migration
*
* @return string Numeric portion of a migration filename
*/
protected function getMigrationNumber(string $migration): string
{
return sscanf($migration, '%[0-9]+', $number) ? $number : '0';
}
//--------------------------------------------------------------------
/**
* Extracts the migration class name from a filename
*
* @param string $migration
*
* @return string text portion of a migration filename
*/
protected function getMigrationName(string $migration): string
{
$parts = explode('_', $migration);
array_shift($parts);
return implode('_', $parts);
}
//--------------------------------------------------------------------
/**
* Retrieves current schema version
*
* @return string Current migration version
*/
protected function getVersion(): string
{
$this->ensureTable();
$row = $this->db->table($this->table)
->select('version')
->where('group', $this->group)
->where('namespace', $this->namespace)
->orderBy('version', 'DESC')
->get();
return $row && ! is_null($row->getRow()) ? $row->getRow()->version : '0';
}
//--------------------------------------------------------------------
/**
* Retrieves current schema version
*
* @return array Current migration version
*/
public function getCliMessages(): array
{
return $this->cliMessages;
}
//--------------------------------------------------------------------
/**
* Stores the current schema version.
*
* @param string $version
*
* @internal param string $migration Migration reached
*
* @return void
*/
protected function addHistory(string $version)
{
$this->db->table($this->table)
->insert([
'version' => $version,
'name' => $this->name,
'group' => $this->group,
'namespace' => $this->namespace,
'time' => time(),
]);
if (is_cli())
{
$this->cliMessages[] = "\t" . CLI::color(lang('Migrations.added'), 'yellow') . "($this->namespace) " . $version . '_' . $this->name;
}
}
//--------------------------------------------------------------------
/**
* Removes a single history
*
* @param string $version
* @return void
*/
protected function removeHistory(string $version)
{
$this->db->table($this->table)
->where('version', $version)
->where('group', $this->group)
->where('namespace', $this->namespace)
->delete();
if (is_cli())
{
$this->cliMessages[] = "\t" . CLI::color(lang('Migrations.removed'), 'yellow') . "($this->namespace) " . $version . '_' . $this->name;
}
}
//--------------------------------------------------------------------
/**
* Ensures that we have created our migrations table
* in the database.
*/
public function ensureTable()
{
if ($this->tableChecked || $this->db->tableExists($this->table))
{
return;
}
$forge = \Config\Database::forge($this->db);
$forge->addField([
'version' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => false,
],
'name' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => false,
],
'group' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => false,
],
'namespace' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => false,
],
'time' => [
'type' => 'INT',
'constraint' => 11,
'null' => false,
],
]);
$forge->createTable($this->table, true);
$this->tableChecked = true;
}
//--------------------------------------------------------------------
}