-
-
Notifications
You must be signed in to change notification settings - Fork 390
/
Copy pathTableMetadataStorage.php
286 lines (233 loc) · 10.3 KB
/
TableMetadataStorage.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
<?php
declare(strict_types=1);
namespace Doctrine\Migrations\Metadata\Storage;
use DateTimeImmutable;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Connections\PrimaryReadReplicaConnection;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Schema\AbstractSchemaManager;
use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Schema\TableDiff;
use Doctrine\DBAL\Types\Types;
use Doctrine\Migrations\Exception\MetadataStorageError;
use Doctrine\Migrations\Metadata\AvailableMigration;
use Doctrine\Migrations\Metadata\ExecutedMigration;
use Doctrine\Migrations\Metadata\ExecutedMigrationsList;
use Doctrine\Migrations\MigrationsRepository;
use Doctrine\Migrations\Query\Query;
use Doctrine\Migrations\Version\Comparator as MigrationsComparator;
use Doctrine\Migrations\Version\Direction;
use Doctrine\Migrations\Version\ExecutionResult;
use Doctrine\Migrations\Version\Version;
use InvalidArgumentException;
use function array_change_key_case;
use function floatval;
use function round;
use function sprintf;
use function strlen;
use function strpos;
use function strtolower;
use function uasort;
use const CASE_LOWER;
final class TableMetadataStorage implements MetadataStorage
{
private bool $isInitialized = false;
private bool $schemaUpToDate = false;
/** @var AbstractSchemaManager<AbstractPlatform> */
private readonly AbstractSchemaManager $schemaManager;
private readonly AbstractPlatform $platform;
private readonly TableMetadataStorageConfiguration $configuration;
public function __construct(
private readonly Connection $connection,
private readonly MigrationsComparator $comparator,
MetadataStorageConfiguration|null $configuration = null,
private readonly MigrationsRepository|null $migrationRepository = null,
) {
$this->schemaManager = $connection->createSchemaManager();
$this->platform = $connection->getDatabasePlatform();
if ($configuration !== null && ! ($configuration instanceof TableMetadataStorageConfiguration)) {
throw new InvalidArgumentException(sprintf(
'%s accepts only %s as configuration',
self::class,
TableMetadataStorageConfiguration::class,
));
}
$this->configuration = $configuration ?? new TableMetadataStorageConfiguration();
}
public function getExecutedMigrations(): ExecutedMigrationsList
{
if (! $this->isInitialized()) {
return new ExecutedMigrationsList([]);
}
$this->checkInitialization();
$rows = $this->connection->fetchAllAssociative(sprintf('SELECT * FROM %s', $this->configuration->getTableName()));
$migrations = [];
foreach ($rows as $row) {
$row = array_change_key_case($row, CASE_LOWER);
$version = new Version($row[strtolower($this->configuration->getVersionColumnName())]);
$executedAt = $row[strtolower($this->configuration->getExecutedAtColumnName())] ?? '';
$executedAt = $executedAt !== ''
? DateTimeImmutable::createFromFormat($this->platform->getDateTimeFormatString(), $executedAt)
: null;
$executionTime = isset($row[strtolower($this->configuration->getExecutionTimeColumnName())])
? floatval($row[strtolower($this->configuration->getExecutionTimeColumnName())] / 1000)
: null;
$migration = new ExecutedMigration(
$version,
$executedAt instanceof DateTimeImmutable ? $executedAt : null,
$executionTime,
);
$migrations[(string) $version] = $migration;
}
uasort($migrations, fn (ExecutedMigration $a, ExecutedMigration $b): int => $this->comparator->compare($a->getVersion(), $b->getVersion()));
return new ExecutedMigrationsList($migrations);
}
public function reset(): void
{
$this->checkInitialization();
$this->connection->executeStatement(
sprintf(
'DELETE FROM %s WHERE 1 = 1',
$this->platform->quoteIdentifier($this->configuration->getTableName()),
),
);
}
public function complete(ExecutionResult $result): void
{
$this->checkInitialization();
if ($result->getDirection() === Direction::DOWN) {
$this->connection->delete($this->configuration->getTableName(), [
$this->configuration->getVersionColumnName() => (string) $result->getVersion(),
]);
} else {
$this->connection->insert($this->configuration->getTableName(), [
$this->configuration->getVersionColumnName() => (string) $result->getVersion(),
$this->configuration->getExecutedAtColumnName() => $result->getExecutedAt(),
$this->configuration->getExecutionTimeColumnName() => $result->getTime() === null ? null : (int) round($result->getTime() * 1000),
], [
Types::STRING,
Types::DATETIME_IMMUTABLE,
Types::INTEGER,
]);
}
}
/** @return iterable<Query> */
public function getSql(ExecutionResult $result): iterable
{
yield new Query('-- Version ' . (string) $result->getVersion() . ' update table metadata');
if ($result->getDirection() === Direction::DOWN) {
yield new Query(sprintf(
'DELETE FROM %s WHERE %s = %s',
$this->configuration->getTableName(),
$this->configuration->getVersionColumnName(),
$this->connection->quote((string) $result->getVersion()),
));
return;
}
yield new Query(sprintf(
'INSERT INTO %s (%s, %s, %s) VALUES (%s, %s, 0)',
$this->configuration->getTableName(),
$this->configuration->getVersionColumnName(),
$this->configuration->getExecutedAtColumnName(),
$this->configuration->getExecutionTimeColumnName(),
$this->connection->quote((string) $result->getVersion()),
$this->connection->quote(($result->getExecutedAt() ?? new DateTimeImmutable())->format('Y-m-d H:i:s')),
));
}
public function ensureInitialized(): void
{
if (! $this->isInitialized()) {
$expectedSchemaChangelog = $this->getExpectedTable();
$this->schemaManager->createTable($expectedSchemaChangelog);
$this->schemaUpToDate = true;
$this->isInitialized = true;
return;
}
$this->isInitialized = true;
$expectedSchemaChangelog = $this->getExpectedTable();
$diff = $this->needsUpdate($expectedSchemaChangelog);
if ($diff === null) {
$this->schemaUpToDate = true;
return;
}
$this->schemaUpToDate = true;
$this->schemaManager->alterTable($diff);
$this->updateMigratedVersionsFromV1orV2toV3();
}
private function needsUpdate(Table $expectedTable): TableDiff|null
{
if ($this->schemaUpToDate) {
return null;
}
$currentTable = $this->schemaManager->introspectTable($this->configuration->getTableName());
$diff = $this->schemaManager->createComparator()->compareTables($currentTable, $expectedTable);
return $diff->isEmpty() ? null : $diff;
}
private function isInitialized(): bool
{
if ($this->isInitialized) {
return $this->isInitialized;
}
if ($this->connection instanceof PrimaryReadReplicaConnection) {
$this->connection->ensureConnectedToPrimary();
}
return $this->schemaManager->tablesExist([$this->configuration->getTableName()]);
}
private function checkInitialization(): void
{
if (! $this->isInitialized()) {
throw MetadataStorageError::notInitialized();
}
$expectedTable = $this->getExpectedTable();
if ($this->needsUpdate($expectedTable) !== null) {
throw MetadataStorageError::notUpToDate();
}
}
private function getExpectedTable(): Table
{
$schemaChangelog = new Table($this->configuration->getTableName());
$schemaChangelog->addColumn(
$this->configuration->getVersionColumnName(),
'string',
['notnull' => true, 'length' => $this->configuration->getVersionColumnLength()],
);
$schemaChangelog->addColumn($this->configuration->getExecutedAtColumnName(), 'datetime', ['notnull' => false]);
$schemaChangelog->addColumn($this->configuration->getExecutionTimeColumnName(), 'integer', ['notnull' => false]);
$schemaChangelog->setPrimaryKey([$this->configuration->getVersionColumnName()]);
return $schemaChangelog;
}
private function updateMigratedVersionsFromV1orV2toV3(): void
{
if ($this->migrationRepository === null) {
return;
}
$availableMigrations = $this->migrationRepository->getMigrations()->getItems();
$executedMigrations = $this->getExecutedMigrations()->getItems();
foreach ($availableMigrations as $availableMigration) {
foreach ($executedMigrations as $k => $executedMigration) {
if ($this->isAlreadyV3Format($availableMigration, $executedMigration)) {
continue;
}
$this->connection->update(
$this->configuration->getTableName(),
[
$this->configuration->getVersionColumnName() => (string) $availableMigration->getVersion(),
],
[
$this->configuration->getVersionColumnName() => (string) $executedMigration->getVersion(),
],
);
unset($executedMigrations[$k]);
}
}
}
private function isAlreadyV3Format(AvailableMigration $availableMigration, ExecutedMigration $executedMigration): bool
{
return (string) $availableMigration->getVersion() === (string) $executedMigration->getVersion()
|| strpos(
(string) $availableMigration->getVersion(),
(string) $executedMigration->getVersion(),
) !== strlen((string) $availableMigration->getVersion()) -
strlen((string) $executedMigration->getVersion());
}
}