-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathMigrator.php
More file actions
278 lines (254 loc) · 9.61 KB
/
Migrator.php
File metadata and controls
278 lines (254 loc) · 9.61 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
<?php
declare(strict_types=1);
/**
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @license https://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Migrations\TestSuite;
use Cake\Database\Connection;
use Cake\Datasource\ConnectionManager;
use Cake\Log\Log;
use Cake\TestSuite\ConnectionHelper;
use Exception;
use Migrations\Migrations;
use RuntimeException;
class Migrator
{
/**
* @var \Cake\TestSuite\ConnectionHelper
*/
protected ConnectionHelper $helper;
/**
* Constructor.
*/
public function __construct()
{
$this->helper = new ConnectionHelper();
}
/**
* Runs one set of migrations.
* This is useful if all your migrations are located in config/Migrations,
* or in a single directory, or in a single plugin.
*
* ## Options
*
* - `skip` A list of `fnmatch` compatible table names that should be ignored.
*
* For additional options {@see \Migrations\Migrations::migrate()}.
*
* @param array<string, mixed> $options Migrate options. Connection defaults to `test`.
* @param bool $truncateTables Truncate all tables after running migrations. Defaults to true.
* @return void
*/
public function run(
array $options = [],
bool $truncateTables = true,
): void {
$this->runMany([$options], $truncateTables);
}
/**
* Runs multiple sets of migrations.
* This is useful if your migrations are located in multiple sources, plugins or connections.
*
* For options, {@see \Migrations\Migrator::run()}.
*
* Example:
*
* $this->runMany([
* ['connection' => 'some-connection', 'source' => 'some/directory'],
* ['plugin' => 'PluginA']
* ]);
*
* @param array<array<string, mixed>> $options Array of option arrays.
* @param bool $truncateTables Truncate all tables after running migrations. Defaults to true.
* @return void
*/
public function runMany(
array $options = [],
bool $truncateTables = true,
): void {
// Don't recreate schema if we are in a phpunit separate process test.
if (isset($GLOBALS['__PHPUNIT_BOOTSTRAP'])) {
return;
}
// Detect all connections involved, and mark those with changed status.
$connectionsToDrop = [];
$connectionsList = [];
foreach ($options as $i => $migrationSet) {
$migrationSet += ['connection' => 'test'];
$skip = $migrationSet['skip'] ?? [];
unset($migrationSet['skip']);
$options[$i] = $migrationSet;
$connectionName = $migrationSet['connection'];
if (!isset($connectionsList[$connectionName])) {
$connectionsList[$connectionName] = ['name' => $connectionName, 'skip' => $skip];
}
$migrations = new Migrations();
if (!isset($connectionsToDrop[$connectionName]) && $this->shouldDropTables($migrations, $migrationSet)) {
$connectionsToDrop[$connectionName] = ['name' => $connectionName, 'skip' => $skip];
}
}
foreach ($connectionsToDrop as $item) {
$this->dropTables($item['name'], $item['skip']);
}
// Run all sets of migrations
foreach ($options as $migrationSet) {
$migrations = new Migrations();
try {
if (!$migrations->migrate($migrationSet)) {
throw new RuntimeException(
"Unable to migrate fixtures for `{$migrationSet['connection']}`.",
);
}
} catch (Exception $e) {
throw new RuntimeException(
'Could not apply migrations for ' . json_encode($migrationSet) . "\n\n" .
"Migrations failed to apply with message:\n\n" .
$e->getMessage() . "\n\n" .
'If you are using the `skip` option and running multiple sets of migrations ' .
'on the same connection, you can\'t skip tables managed by CakePHP in the connection.',
0,
$e,
);
}
}
// Truncate all connections if required in parameters
if ($truncateTables) {
foreach ($connectionsList as $item) {
$this->truncate($item['name'], $item['skip']);
}
}
}
/**
* Truncate tables after calling run([], false)
*
* For options, {@see \Migrations\Migrations::migrate()}.
*
* @param string $connection Connection name to truncate all non-phinx tables
* @param string[] $skip A fnmatch compatible list of table names to skip.
* @return void
*/
public function truncate(string $connection, array $skip = []): void
{
// Don't recreate schema if we are in a phpunit separate process test.
if (isset($GLOBALS['__PHPUNIT_BOOTSTRAP'])) {
return;
}
$tables = $this->getNonPhinxTables($connection, $skip);
if ($tables) {
$this->helper->truncateTables($connection, $tables);
}
}
/**
* Detect if migrations have changed and the database needs to be wiped.
*
* @param \Migrations\Migrations $migrations The migrations service.
* @param array $options The connection options.
* @return bool
*/
protected function shouldDropTables(Migrations $migrations, array $options): bool
{
Log::write('debug', "Reading migrations status for {$options['connection']}...");
$messages = [
'down' => [],
'missing' => [],
];
foreach ($migrations->status($options) as $migration) {
if ($migration['status'] === 'up' && ($migration['missing'] ?? false)) {
$messages['missing'][] = 'Applied but, missing Migration ' .
"source={$migration['name']} id={$migration['id']}";
}
if ($migration['status'] === 'down') {
$messages['down'][] = "Migration to reverse. source={$migration['name']} id={$migration['id']}";
}
}
$output = [];
$hasProblems = false;
$itemize = function ($item) {
return '- ' . $item;
};
if (!empty($messages['down'])) {
$hasProblems = true;
$output[] = 'Migrations needing to be reversed:';
$output = array_merge($output, array_map($itemize, $messages['down']));
$output[] = '';
}
if (!empty($messages['missing'])) {
$hasProblems = true;
$output[] = 'Applied but missing migrations:';
$output = array_merge($output, array_map($itemize, $messages['missing']));
$output[] = '';
}
if ($output) {
$output = array_merge(
['Your migration status some differences with the expected state.', ''],
$output,
['Going to drop all tables in this source, and re-apply migrations.'],
);
Log::write('debug', implode("\n", $output));
}
return $hasProblems;
}
/**
* Drops the regular tables of the provided connection
* and truncates the phinx tables.
*
* @param string $connection Connection on which tables are dropped.
* @param string[] $skip A fnmatch compatible list of tables to skip.
* @return void
*/
protected function dropTables(string $connection, array $skip = []): void
{
$dropTables = $this->getNonPhinxTables($connection, $skip);
if (count($dropTables)) {
$this->helper->dropTables($connection, $dropTables);
}
$phinxTables = $this->getPhinxTables($connection);
if (count($phinxTables)) {
$this->helper->truncateTables($connection, $phinxTables);
}
}
/**
* Get the list of tables that are phinxlog
*
* @param string $connection The connection name to operate on.
* @return string[] The list of tables that are not related to phinx in the provided connection.
*/
protected function getPhinxTables(string $connection): array
{
$connection = ConnectionManager::get($connection);
assert($connection instanceof Connection);
$tables = $connection->getSchemaCollection()->listTables();
return array_filter($tables, function ($table) {
return strpos($table, 'phinxlog') !== false;
});
}
/**
* Get the list of tables that are not phinxlog related.
*
* @param string $connection The connection name to operate on.
* @param string[] $skip A fnmatch compatible list of tables to skip.
* @return string[] The list of tables that are not related to phinx in the provided connection.
*/
protected function getNonPhinxTables(string $connection, array $skip): array
{
$connection = ConnectionManager::get($connection);
assert($connection instanceof Connection);
$tables = $connection->getSchemaCollection()->listTables();
$skip[] = '*phinxlog*';
return array_filter($tables, function ($table) use ($skip) {
foreach ($skip as $pattern) {
if (fnmatch($pattern, $table) === true) {
return false;
}
}
return true;
});
}
}