-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
MigrationInfoServiceImpl.java
630 lines (438 loc) · 19.9 KB
/
MigrationInfoServiceImpl.java
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
/*
* Copyright © Red Gate Software Ltd 2010-2020
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flywaydb.core.internal.info;
import org.flywaydb.core.api.*;
import org.flywaydb.core.api.configuration.Configuration;
import org.flywaydb.core.api.output.ValidateOutput;
import org.flywaydb.core.api.resolver.Context;
import org.flywaydb.core.api.resolver.MigrationResolver;
import org.flywaydb.core.api.resolver.ResolvedMigration;
import org.flywaydb.core.api.output.InfoResult;
import org.flywaydb.core.api.output.CommandResultFactory;
import org.flywaydb.core.api.output.OperationResult;
import org.flywaydb.core.internal.database.base.Database;
import org.flywaydb.core.internal.database.base.Schema;
import org.flywaydb.core.internal.schemahistory.AppliedMigration;
import org.flywaydb.core.internal.schemahistory.SchemaHistory;
import org.flywaydb.core.internal.util.Pair;
import java.util.*;
/**
* Default implementation of MigrationInfoService.
*/
public class MigrationInfoServiceImpl implements MigrationInfoService, OperationResult {
/**
* The migration resolver for available migrations.
*/
private final MigrationResolver migrationResolver;
/**
* Database-specific functionality.
*/
private final Database database;
private final Context context;
/**
* The schema history table for applied migrations.
*/
private final SchemaHistory schemaHistory;
/**
* The target version up to which to retrieve the info.
*/
private MigrationVersion target;
/**
* The migrations to retrieve info for.
*/
private MigrationPattern[] cherryPick;
/**
* Allows migrations to be run "out of order".
* <p>If you already have versions 1 and 3 applied, and now a version 2 is found,
* it will be applied too instead of being ignored.</p>
* <p>(default: {@code false})</p>
*/
private boolean outOfOrder;
/**
* Whether pending migrations are allowed.
*/
private final boolean pending;
/**
* Whether missing migrations are allowed.
*/
private final boolean missing;
/**
* Whether ignored migrations are allowed.
*/
private final boolean ignored;
/**
* Whether future migrations are allowed.
*/
private final boolean future;
/**
* The migrations infos calculated at the last refresh.
*/
private List<MigrationInfoImpl> migrationInfos;
/**
* Whether all of the specified schemas are empty or not.
*/
private Boolean allSchemasEmpty;
/**
* Creates a new MigrationInfoServiceImpl.
*
* @param migrationResolver The migration resolver for available migrations.
* @param schemaHistory The schema history table for applied migrations.
* @param configuration The current configuration.
* @param target The target version up to which to retrieve the info.
* @param outOfOrder Allows migrations to be run "out of order".
* @param cherryPick The migrations to consider when migration.
* @param pending Whether pending migrations are allowed.
* @param missing Whether missing migrations are allowed.
* @param ignored Whether ignored migrations are allowed.
* @param future Whether future migrations are allowed.
*/
public MigrationInfoServiceImpl(MigrationResolver migrationResolver,
SchemaHistory schemaHistory, Database database, final Configuration configuration,
MigrationVersion target, boolean outOfOrder, MigrationPattern[] cherryPick,
boolean pending, boolean missing, boolean ignored, boolean future) {
this.migrationResolver = migrationResolver;
this.schemaHistory = schemaHistory;
this.context = new Context() {
@Override
public Configuration getConfiguration() {
return configuration;
}
};
this.database = database;
this.target = target;
this.outOfOrder = outOfOrder;
this.cherryPick = cherryPick;
this.pending = pending;
this.missing = missing;
this.ignored = ignored || cherryPick != null;
this.future = future;
}
/**
* Refreshes the info about all known migrations from both the classpath and the DB.
*/
public void refresh() {
Collection<ResolvedMigration> resolvedMigrations = migrationResolver.resolveMigrations(context);
List<AppliedMigration> appliedMigrations = schemaHistory.allAppliedMigrations();
MigrationInfoContext context = new MigrationInfoContext();
context.outOfOrder = outOfOrder;
context.pending = pending;
context.missing = missing;
context.ignored = ignored;
context.future = future;
context.target = target;
context.cherryPick = cherryPick;
Map<Pair<MigrationVersion, Boolean>, ResolvedMigration> resolvedVersioned = new TreeMap<>();
Map<String, ResolvedMigration> resolvedRepeatable = new TreeMap<>();
// Separate resolved migrations into versioned and repeatable
for (ResolvedMigration resolvedMigration : resolvedMigrations) {
MigrationVersion version = resolvedMigration.getVersion();
if (version != null) {
if (version.compareTo(context.lastResolved) > 0) {
context.lastResolved = version;
}
//noinspection RedundantConditionalExpression
resolvedVersioned.put(Pair.of(version,
false), resolvedMigration);
} else {
resolvedRepeatable.put(resolvedMigration.getDescription(), resolvedMigration);
}
}
// Split applied into version and repeatable, and update state from synthetic migrations
List<Pair<AppliedMigration, AppliedMigrationAttributes>> appliedVersioned = new ArrayList<>();
List<Pair<AppliedMigration, AppliedMigrationAttributes>> appliedRepeatable = new ArrayList<>();
for (AppliedMigration appliedMigration : appliedMigrations) {
MigrationVersion version = appliedMigration.getVersion();
if (version == null) {
appliedRepeatable.add(Pair.of(appliedMigration, new AppliedMigrationAttributes()));
if (appliedMigration.getType().equals(MigrationType.DELETE) && appliedMigration.isSuccess()) {
markRepeatableAsDeleted(appliedMigration.getDescription(), appliedRepeatable);
}
continue;
}
if (appliedMigration.getType() == MigrationType.SCHEMA) {
context.schema = version;
}
if (appliedMigration.getType() == MigrationType.BASELINE) {
context.baseline = version;
}
if (appliedMigration.getType().equals(MigrationType.DELETE) && appliedMigration.isSuccess()) {
markAsDeleted(version, appliedVersioned);
}
appliedVersioned.add(Pair.of(appliedMigration, new AppliedMigrationAttributes()));
}
// Update last applied and out of order states
for (Pair<AppliedMigration, AppliedMigrationAttributes> av : appliedVersioned) {
MigrationVersion version = av.getLeft().getVersion();
if (version != null) {
if (version.compareTo(context.lastApplied) > 0) {
if (av.getLeft().getType() != MigrationType.DELETE && !av.getRight().deleted
) {
context.lastApplied = version;
}
} else {
av.getRight().outOfOrder = true;
}
}
}
// Set target
if (MigrationVersion.CURRENT == target) {
context.target = context.lastApplied;
}
// Identify pending versioned migrations and build output migration info list
List<MigrationInfoImpl> migrationInfos1 = new ArrayList<>();
Set<ResolvedMigration> pendingResolvedVersioned = new HashSet<>(resolvedVersioned.values());
for (Pair<AppliedMigration, AppliedMigrationAttributes> av : appliedVersioned) {
ResolvedMigration resolvedMigration = resolvedVersioned.get(Pair.of(av.getLeft().getVersion(), av.getLeft().getType().isUndo()));
// Remove pending migrations
if (resolvedMigration != null
&& !av.getRight().deleted && av.getLeft().getType() != MigrationType.DELETE
) {
pendingResolvedVersioned.remove(resolvedMigration);
}
// Build final migration info
migrationInfos1.add(new MigrationInfoImpl(resolvedMigration, av.getLeft(), context, av.getRight().outOfOrder, av.getRight().deleted
));
}
// Add all pending migrations to output list
for (ResolvedMigration prv : pendingResolvedVersioned) {
migrationInfos1.add(new MigrationInfoImpl(prv, null, context, false, false
));
}
if (target != null && target != MigrationVersion.CURRENT && target != MigrationVersion.LATEST) {
boolean targetFound = false;
for (MigrationInfoImpl migration : migrationInfos1) {
if (target.compareTo(migration.getVersion()) == 0) {
targetFound = true;
break;
}
}
if (!targetFound) {
throw new FlywayException("No migration with a target version " + target + " could be found. Ensure target is specified correctly and the migration exists.");
}
}
// Setup the latest repeatable run ranks
for (Pair<AppliedMigration, AppliedMigrationAttributes> av : appliedRepeatable) {
if (av.getRight().deleted && av.getLeft().getType() == MigrationType.DELETE) {
continue;
}
AppliedMigration appliedRepeatableMigration = av.getLeft();
String desc = appliedRepeatableMigration.getDescription();
int rank = appliedRepeatableMigration.getInstalledRank();
Map<String, Integer> latestRepeatableRuns = context.latestRepeatableRuns;
if (!latestRepeatableRuns.containsKey(desc) || (rank > latestRepeatableRuns.get(desc))) {
latestRepeatableRuns.put(desc, rank);
}
}
// Using latest repeatable runs, discover pending repeatables and build output list
Set<ResolvedMigration> pendingResolvedRepeatable = new HashSet<>(resolvedRepeatable.values());
for (Pair<AppliedMigration, AppliedMigrationAttributes> av : appliedRepeatable) {
AppliedMigration appliedRepeatableMigration = av.getLeft();
String desc = appliedRepeatableMigration.getDescription();
int rank = appliedRepeatableMigration.getInstalledRank();
ResolvedMigration resolvedMigration = resolvedRepeatable.get(desc);
int latestRank = context.latestRepeatableRuns.get(desc);
// If latest run is the same rank, its not pending
if (!av.getRight().deleted && av.getLeft().getType() != MigrationType.DELETE
&& resolvedMigration != null && rank == latestRank && resolvedMigration.checksumMatches(appliedRepeatableMigration.getChecksum())) {
pendingResolvedRepeatable.remove(resolvedMigration);
}
// Add to output list
migrationInfos1.add(new MigrationInfoImpl(resolvedMigration, appliedRepeatableMigration, context, false, av.getRight().deleted
));
}
// Add pending repeatables to output list
for (ResolvedMigration prr : pendingResolvedRepeatable) {
migrationInfos1.add(new MigrationInfoImpl(prr, null, context, false, false
));
}
// Set output
Collections.sort(migrationInfos1);
migrationInfos = migrationInfos1;
}
/**
* Marks the latest applied migration with this description as deleted.
*
* @param description The description to match
* @param appliedRepeatable The discovered applied migrations
*/
private void markRepeatableAsDeleted(String description, List<Pair<AppliedMigration, AppliedMigrationAttributes>> appliedRepeatable) {
for (int i = appliedRepeatable.size() - 1; i >= 0; i--) {
Pair<AppliedMigration, AppliedMigrationAttributes> ar = appliedRepeatable.get(i);
if (!ar.getLeft().getType().isSynthetic() && description.equals(ar.getLeft().getDescription())) {
if (!ar.getRight().deleted) {
ar.getRight().deleted = true;
}
return;
}
}
}
/**
* Marks the latest applied migration with this version as deleted.
*
* @param version The version.
* @param appliedVersioned The applied migrations.
*/
private void markAsDeleted(MigrationVersion version, List<Pair<AppliedMigration, AppliedMigrationAttributes>> appliedVersioned) {
for (int i = appliedVersioned.size() - 1; i >= 0; i--) {
Pair<AppliedMigration, AppliedMigrationAttributes> av = appliedVersioned.get(i);
if (!av.getLeft().getType().isSynthetic() && version.equals(av.getLeft().getVersion())) {
if (av.getRight().deleted) {
throw new FlywayException("Corrupted schema history: multiple delete entries for version " + version,
ErrorCode.DUPLICATE_DELETED_MIGRATION);
} else {
av.getRight().deleted = true;
return;
}
}
}
}
@Override
public MigrationInfo[] all() {
return migrationInfos.toArray(new MigrationInfo[0]);
}
@Override
public MigrationInfo current() {
MigrationInfo current = null;
for (MigrationInfoImpl migrationInfo : migrationInfos) {
if (migrationInfo.getState().isApplied()
&& !MigrationState.DELETED.equals(migrationInfo.getState())
&& !migrationInfo.getType().equals(MigrationType.DELETE)
&& migrationInfo.getVersion() != null
&& (current == null || migrationInfo.getVersion().compareTo(current.getVersion()) > 0)) {
current = migrationInfo;
}
}
if (current != null) {
return current;
}
// If no versioned migration has been applied so far, fall back to the latest repeatable one
for (int i = migrationInfos.size() - 1; i >= 0; i--) {
MigrationInfoImpl migrationInfo = migrationInfos.get(i);
if (migrationInfo.getState().isApplied()
&& !MigrationState.DELETED.equals(migrationInfo.getState())
&& !migrationInfo.getType().equals(MigrationType.DELETE)
) {
return migrationInfo;
}
}
return null;
}
@Override
public MigrationInfoImpl[] pending() {
List<MigrationInfoImpl> pendingMigrations = new ArrayList<>();
for (MigrationInfoImpl migrationInfo : migrationInfos) {
if (MigrationState.PENDING == migrationInfo.getState()) {
pendingMigrations.add(migrationInfo);
}
}
return pendingMigrations.toArray(new MigrationInfoImpl[0]);
}
@Override
public MigrationInfoImpl[] applied() {
List<MigrationInfoImpl> appliedMigrations = new ArrayList<>();
for (MigrationInfoImpl migrationInfo : migrationInfos) {
if (migrationInfo.getState().isApplied()) {
appliedMigrations.add(migrationInfo);
}
}
return appliedMigrations.toArray(new MigrationInfoImpl[0]);
}
/**
* Retrieves the full set of infos about the migrations resolved on the classpath.
*
* @return The resolved migrations. An empty array if none.
*/
public MigrationInfo[] resolved() {
List<MigrationInfo> resolvedMigrations = new ArrayList<>();
for (MigrationInfo migrationInfo : migrationInfos) {
if (migrationInfo.getState().isResolved()) {
resolvedMigrations.add(migrationInfo);
}
}
return resolvedMigrations.toArray(new MigrationInfo[0]);
}
/**
* Retrieves the full set of infos about the migrations that failed.
*
* @return The failed migrations. An empty array if none.
*/
public MigrationInfo[] failed() {
List<MigrationInfo> failedMigrations = new ArrayList<>();
for (MigrationInfo migrationInfo : migrationInfos) {
if (migrationInfo.getState().isFailed()) {
failedMigrations.add(migrationInfo);
}
}
return failedMigrations.toArray(new MigrationInfo[0]);
}
/**
* Retrieves the full set of infos about future migrations applied to the DB.
*
* @return The future migrations. An empty array if none.
*/
public MigrationInfo[] future() {
List<MigrationInfo> futureMigrations = new ArrayList<>();
for (MigrationInfo migrationInfo : migrationInfos) {
if (((migrationInfo.getState() == MigrationState.FUTURE_SUCCESS)
|| (migrationInfo.getState() == MigrationState.FUTURE_FAILED))
) {
futureMigrations.add(migrationInfo);
}
}
return futureMigrations.toArray(new MigrationInfo[0]);
}
/**
* Retrieves the full set of infos about out of order migrations applied to the DB.
*
* @return The out of order migrations. An empty array if none.
*/
public MigrationInfo[] outOfOrder() {
List<MigrationInfo> outOfOrderMigrations = new ArrayList<>();
for (MigrationInfo migrationInfo : migrationInfos) {
if (migrationInfo.getState() == MigrationState.OUT_OF_ORDER) {
outOfOrderMigrations.add(migrationInfo);
}
}
return outOfOrderMigrations.toArray(new MigrationInfo[0]);
}
/**
* Validate all migrations for consistency.
*
* @return The list of migrations that failed validation, which is empty if everything is fine.
*/
public List<ValidateOutput> validate() {
List<ValidateOutput> invalidMigrations = new ArrayList<>();
CommandResultFactory commandResultFactory = new CommandResultFactory();
for (MigrationInfoImpl migrationInfo : migrationInfos) {
ErrorDetails validateError = migrationInfo.validate();
if (validateError != null) {
invalidMigrations.add(commandResultFactory.createValidateOutput(migrationInfo, validateError));
}
}
return invalidMigrations;
}
public void setAllSchemasEmpty(Schema[] schemas) {
allSchemasEmpty = Arrays.stream(schemas).allMatch(Schema::empty);
}
@Override
public InfoResult getInfoResult() {
return getInfoResult(this.all());
}
public InfoResult getInfoResult(MigrationInfo[] infos) {
CommandResultFactory commandResultFactory = new CommandResultFactory();
return commandResultFactory.createInfoResult(this.context.getConfiguration(), this.database, infos, this.current(), this.allSchemasEmpty);
}
}