-
-
Notifications
You must be signed in to change notification settings - Fork 384
/
MigrateCommand.php
296 lines (233 loc) · 10.4 KB
/
MigrateCommand.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
<?php
declare(strict_types=1);
namespace Doctrine\Migrations\Tools\Console\Command;
use Doctrine\Migrations\Exception\NoMigrationsFoundWithCriteria;
use Doctrine\Migrations\Exception\NoMigrationsToExecute;
use Doctrine\Migrations\Exception\UnknownMigrationVersion;
use Doctrine\Migrations\Metadata\ExecutedMigrationsList;
use Doctrine\Migrations\Tools\Console\ConsoleInputMigratorConfigurationFactory;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use function count;
use function dirname;
use function getcwd;
use function in_array;
use function is_dir;
use function is_string;
use function is_writable;
use function sprintf;
use function str_starts_with;
/**
* The MigrateCommand class is responsible for executing a migration from the current version to another
* version up or down. It will calculate all the migration versions that need to be executed and execute them.
*/
#[AsCommand(name: 'migrations:migrate', description: 'Execute a migration to a specified version or the latest available version.')]
final class MigrateCommand extends DoctrineCommand
{
/** @var string|null */
protected static $defaultName = 'migrations:migrate';
protected function configure(): void
{
$this
->setAliases(['migrate'])
->setDescription(
'Execute a migration to a specified version or the latest available version.',
)
->addArgument(
'version',
InputArgument::OPTIONAL,
'The version FQCN or alias (first, prev, next, latest) to migrate to.',
'latest',
)
->addOption(
'write-sql',
null,
InputOption::VALUE_OPTIONAL,
'The path to output the migration SQL file. Defaults to current working directory.',
false,
)
->addOption(
'dry-run',
null,
InputOption::VALUE_NONE,
'Execute the migration as a dry run.',
)
->addOption(
'query-time',
null,
InputOption::VALUE_NONE,
'Time all the queries individually.',
)
->addOption(
'allow-no-migration',
null,
InputOption::VALUE_NONE,
'Do not throw an exception if no migration is available.',
)
->addOption(
'all-or-nothing',
null,
InputOption::VALUE_OPTIONAL,
'Wrap the entire migration in a transaction.',
ConsoleInputMigratorConfigurationFactory::ABSENT_CONFIG_VALUE,
)
->setHelp(<<<'EOT'
The <info>%command.name%</info> command executes a migration to a specified version or the latest available version:
<info>%command.full_name%</info>
You can show more information about the process by increasing the verbosity level. To see the
executed queries, set the level to debug with <comment>-vv</comment>:
<info>%command.full_name% -vv</info>
You can optionally manually specify the version you wish to migrate to:
<info>%command.full_name% FQCN</info>
You can specify the version you wish to migrate to using an alias:
<info>%command.full_name% prev</info>
<info>These alias are defined: first, latest, prev, current and next</info>
You can specify the version you wish to migrate to using an number against the current version:
<info>%command.full_name% current+3</info>
You can also execute the migration as a <comment>--dry-run</comment>:
<info>%command.full_name% FQCN --dry-run</info>
You can output the prepared SQL statements to a file with <comment>--write-sql</comment>:
<info>%command.full_name% FQCN --write-sql</info>
Or you can also execute the migration without a warning message which you need to interact with:
<info>%command.full_name% --no-interaction</info>
You can also time all the different queries if you wanna know which one is taking so long:
<info>%command.full_name% --query-time</info>
Use the --all-or-nothing option to wrap the entire migration in a transaction.
EOT);
parent::configure();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$migratorConfigurationFactory = $this->getDependencyFactory()->getConsoleInputMigratorConfigurationFactory();
$migratorConfiguration = $migratorConfigurationFactory->getMigratorConfiguration($input);
$databaseName = (string) $this->getDependencyFactory()->getConnection()->getDatabase();
$question = sprintf(
'WARNING! You are about to execute a migration in database "%s" that could result in schema changes and data loss. Are you sure you wish to continue?',
$databaseName === '' ? '<unnamed>' : $databaseName,
);
if (! $migratorConfiguration->isDryRun() && ! $this->canExecute($question, $input)) {
$this->io->error('Migration cancelled!');
return 3;
}
$this->getDependencyFactory()->getMetadataStorage()->ensureInitialized();
$allowNoMigration = $input->getOption('allow-no-migration');
$versionAlias = $input->getArgument('version');
$path = $input->getOption('write-sql') ?? getcwd();
if (is_string($path) && ! $this->isPathWritable($path)) {
$this->io->error(sprintf('The path "%s" not writeable!', $path));
return 1;
}
$migrationRepository = $this->getDependencyFactory()->getMigrationRepository();
if (count($migrationRepository->getMigrations()) === 0) {
$message = sprintf(
'The version "%s" couldn\'t be reached, there are no registered migrations.',
$versionAlias,
);
if ($allowNoMigration) {
$this->io->warning($message);
return 0;
}
$this->io->error($message);
return 1;
}
try {
$version = $this->getDependencyFactory()->getVersionAliasResolver()->resolveVersionAlias($versionAlias);
} catch (UnknownMigrationVersion) {
$this->io->error(sprintf(
'Unknown version: %s',
OutputFormatter::escape($versionAlias),
));
return 1;
} catch (NoMigrationsToExecute | NoMigrationsFoundWithCriteria) {
return $this->exitForAlias($versionAlias);
}
$planCalculator = $this->getDependencyFactory()->getMigrationPlanCalculator();
$statusCalculator = $this->getDependencyFactory()->getMigrationStatusCalculator();
$executedUnavailableMigrations = $statusCalculator->getExecutedUnavailableMigrations();
if ($this->checkExecutedUnavailableMigrations($executedUnavailableMigrations, $input) === false) {
return 3;
}
$plan = $planCalculator->getPlanUntilVersion($version);
if (count($plan) === 0) {
return $this->exitForAlias($versionAlias);
}
$this->getDependencyFactory()->getLogger()->notice(
'Migrating' . ($migratorConfiguration->isDryRun() ? ' (dry-run)' : '') . ' {direction} to {to}',
[
'direction' => $plan->getDirection(),
'to' => (string) $version,
],
);
$migrator = $this->getDependencyFactory()->getMigrator();
$sql = $migrator->migrate($plan, $migratorConfiguration);
if (is_string($path)) {
$writer = $this->getDependencyFactory()->getQueryWriter();
$writer->write($path, $plan->getDirection(), $sql);
}
$this->io->success(sprintf(
'Successfully migrated to version: %s',
$version,
));
$this->io->newLine();
return 0;
}
private function checkExecutedUnavailableMigrations(
ExecutedMigrationsList $executedUnavailableMigrations,
InputInterface $input,
): bool {
if (count($executedUnavailableMigrations) !== 0) {
$this->io->warning(sprintf(
'You have %s previously executed migrations in the database that are not registered migrations.',
count($executedUnavailableMigrations),
));
foreach ($executedUnavailableMigrations->getItems() as $executedUnavailableMigration) {
$this->io->text(sprintf(
'<comment>>></comment> %s (<comment>%s</comment>)',
$executedUnavailableMigration->getExecutedAt()?->format('Y-m-d H:i:s'),
$executedUnavailableMigration->getVersion(),
));
}
$question = 'Are you sure you wish to continue?';
if (! $this->canExecute($question, $input)) {
$this->io->error('Migration cancelled!');
return false;
}
}
return true;
}
private function exitForAlias(string $versionAlias): int
{
$version = $this->getDependencyFactory()->getVersionAliasResolver()->resolveVersionAlias('current');
// Allow meaningful message when latest version already reached.
if (in_array($versionAlias, ['current', 'latest', 'first'], true)) {
$message = sprintf(
'Already at the %s version ("%s")',
$versionAlias,
(string) $version,
);
$this->io->success($message);
} elseif (in_array($versionAlias, ['next', 'prev'], true) || str_starts_with($versionAlias, 'current')) {
$message = sprintf(
'The version "%s" couldn\'t be reached, you are at version "%s"',
$versionAlias,
(string) $version,
);
$this->io->error($message);
} else {
$message = sprintf(
'You are already at version "%s"',
(string) $version,
);
$this->io->success($message);
}
return 0;
}
private function isPathWritable(string $path): bool
{
return is_writable($path) || is_dir($path) || is_writable(dirname($path));
}
}