-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
DbMigrate.java
496 lines (423 loc) · 20.1 KB
/
DbMigrate.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
/*
* 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.command;
import org.flywaydb.core.api.FlywayException;
import org.flywaydb.core.api.MigrationInfo;
import org.flywaydb.core.api.MigrationState;
import org.flywaydb.core.api.MigrationVersion;
import org.flywaydb.core.api.callback.Event;
import org.flywaydb.core.api.configuration.Configuration;
import org.flywaydb.core.api.executor.Context;
import org.flywaydb.core.api.executor.MigrationExecutor;
import org.flywaydb.core.api.logging.Log;
import org.flywaydb.core.api.logging.LogFactory;
import org.flywaydb.core.api.output.CommandResultFactory;
import org.flywaydb.core.api.output.MigrateResult;
import org.flywaydb.core.api.resolver.MigrationResolver;
import org.flywaydb.core.api.resolver.ResolvedMigration;
import org.flywaydb.core.internal.callback.CallbackExecutor;
import org.flywaydb.core.internal.database.base.Connection;
import org.flywaydb.core.internal.database.base.Database;
import org.flywaydb.core.internal.database.base.Schema;
import org.flywaydb.core.internal.info.MigrationInfoImpl;
import org.flywaydb.core.internal.info.MigrationInfoServiceImpl;
import org.flywaydb.core.internal.jdbc.ExecutionTemplateFactory;
import org.flywaydb.core.internal.schemahistory.SchemaHistory;
import org.flywaydb.core.internal.util.ExceptionUtils;
import org.flywaydb.core.internal.util.StopWatch;
import org.flywaydb.core.internal.util.StringUtils;
import org.flywaydb.core.internal.util.TimeFormat;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
/**
* Main workflow for migrating the database.
*/
public class DbMigrate {
private static final Log LOG = LogFactory.getLog(DbMigrate.class);
/**
* Database-specific functionality.
*/
private final Database database;
/**
* The database schema history table.
*/
private final SchemaHistory schemaHistory;
/**
* The schema containing the schema history table.
*/
private final Schema schema;
/**
* The migration resolver.
*/
private final MigrationResolver migrationResolver;
/**
* The Flyway configuration.
*/
private final Configuration configuration;
/**
* The callback executor.
*/
private final CallbackExecutor callbackExecutor;
/**
* The connection to use to perform the actual database migrations.
*/
private final Connection connectionUserObjects;
/**
* The POJO containing the migration result
*/
private MigrateResult migrateResult;
/**
* The factory object which constructs a migration result
*/
private final CommandResultFactory commandResultFactory;
/**
* This is used to remember the type of migration between calls to migrateGroup().
*/
private boolean isPreviousVersioned;
/**
* Creates a new database migrator.
*
* @param database Database-specific functionality.
* @param schemaHistory The database schema history table.
* @param schema The schema containing the schema history table.
* @param migrationResolver The migration resolver.
* @param configuration The Flyway configuration.
* @param callbackExecutor The callbacks executor.
*/
public DbMigrate(Database database,
SchemaHistory schemaHistory, Schema schema, MigrationResolver migrationResolver,
Configuration configuration, CallbackExecutor callbackExecutor) {
this.database = database;
this.connectionUserObjects = database.getMigrationConnection();
this.schemaHistory = schemaHistory;
this.schema = schema;
this.migrationResolver = migrationResolver;
this.configuration = configuration;
this.callbackExecutor = callbackExecutor;
this.commandResultFactory = new CommandResultFactory();
}
/**
* Starts the actual migration.
*
* @return The number of successfully applied migrations.
* @throws FlywayException when migration failed.
*/
public MigrateResult migrate() throws FlywayException {
callbackExecutor.onMigrateOrUndoEvent(Event.BEFORE_MIGRATE);
migrateResult = commandResultFactory.createMigrateResult(database.getCatalog(), configuration);
int count;
try {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
count = configuration.isGroup() ?
// When group is active, start the transaction boundary early to
// ensure that all changes to the schema history table are either committed or rolled back atomically.
schemaHistory.lock(new Callable<Integer>() {
@Override
public Integer call() {
return migrateAll();
}
}) :
// For all regular cases, proceed with the migration as usual.
migrateAll();
stopWatch.stop();
logSummary(count, stopWatch.getTotalTimeMillis());
} catch (FlywayException e) {
callbackExecutor.onMigrateOrUndoEvent(Event.AFTER_MIGRATE_ERROR);
throw e;
}
callbackExecutor.onMigrateOrUndoEvent(Event.AFTER_MIGRATE);
if (!migrateResult.migrations.isEmpty()) {
for (int i = migrateResult.migrations.size() - 1; i >= 0; i--) {
String targetVersion = migrateResult.migrations.get(i).version;
if (!targetVersion.isEmpty()) {
migrateResult.targetSchemaVersion = targetVersion;
break;
}
}
}
migrateResult.migrationsExecuted = count;
return migrateResult;
}
private int migrateAll() {
int total = 0;
isPreviousVersioned = true;
while (true) {
final boolean firstRun = total == 0;
int count = configuration.isGroup()
// With group active a lock on the schema history table has already been acquired.
? migrateGroup(firstRun)
// Otherwise acquire the lock now. The lock will be released at the end of each migration.
: schemaHistory.lock(new Callable<Integer>() {
@Override
public Integer call() {
return migrateGroup(firstRun);
}
});
total += count;
if (count == 0) {
// No further migrations available
break;
}
}
if (isPreviousVersioned) {
callbackExecutor.onMigrateOrUndoEvent(Event.AFTER_VERSIONED);
}
return total;
}
/**
* Migrate a group of one (group = false) or more (group = true) migrations.
*
* @param firstRun Where this is the first time this code runs in this migration run.
* @return The number of newly applied migrations.
*/
private Integer migrateGroup(boolean firstRun) {
MigrationInfoServiceImpl infoService =
new MigrationInfoServiceImpl(migrationResolver, schemaHistory, database, configuration,
configuration.getTarget(), configuration.isOutOfOrder(), configuration.getCherryPick(),
true, true, true, true);
infoService.refresh();
MigrationInfo current = infoService.current();
MigrationVersion currentSchemaVersion = current == null ? MigrationVersion.EMPTY : current.getVersion();
if (firstRun) {
LOG.info("Current version of schema " + schema + ": " + currentSchemaVersion);
MigrationVersion schemaVersionToOutput = currentSchemaVersion == null ? MigrationVersion.EMPTY : currentSchemaVersion;
migrateResult.initialSchemaVersion = schemaVersionToOutput.getVersion();
if (configuration.isOutOfOrder()) {
String outOfOrderWarning = "outOfOrder mode is active. Migration of schema " + schema + " may not be reproducible.";
LOG.warn(outOfOrderWarning);
migrateResult.warnings.add(outOfOrderWarning);
}
}
MigrationInfo[] future = infoService.future();
if (future.length > 0) {
List<MigrationInfo> resolved = Arrays.asList(infoService.resolved());
Collections.reverse(resolved);
if (resolved.isEmpty()) {
LOG.error("Schema " + schema + " has version " + currentSchemaVersion
+ ", but no migration could be resolved in the configured locations !");
} else {
for (MigrationInfo migrationInfo : resolved) {
// Only consider versioned migrations
if (migrationInfo.getVersion() != null) {
LOG.warn("Schema " + schema + " has a version (" + currentSchemaVersion
+ ") that is newer than the latest available migration ("
+ migrationInfo.getVersion() + ") !");
break;
}
}
}
}
MigrationInfo[] failed = infoService.failed();
if (failed.length > 0) {
if ((failed.length == 1)
&& (failed[0].getState() == MigrationState.FUTURE_FAILED)
&& configuration.isIgnoreFutureMigrations()) {
LOG.warn("Schema " + schema + " contains a failed future migration to version " + failed[0].getVersion() + " !");
} else {
if (failed[0].getVersion() == null) {
throw new FlywayException("Schema " + schema + " contains a failed repeatable migration (" + doQuote(failed[0].getDescription()) + ") !");
}
throw new FlywayException("Schema " + schema + " contains a failed migration to version " + failed[0].getVersion() + " !");
}
}
LinkedHashMap<MigrationInfoImpl, Boolean> group = new LinkedHashMap<>();
for (MigrationInfoImpl pendingMigration : infoService.pending()) {
boolean isOutOfOrder = pendingMigration.getVersion() != null
&& pendingMigration.getVersion().compareTo(currentSchemaVersion) < 0;
group.put(pendingMigration, isOutOfOrder);
if (!configuration.isGroup()) {
// Only include one pending migration if group is disabled
break;
}
}
if (!group.isEmpty()) {
boolean skipExecutingMigrations = false;
applyMigrations(group, skipExecutingMigrations);
}
return group.size();
}
/**
* Logs the summary of this migration run.
*
* @param migrationSuccessCount The number of successfully applied migrations.
* @param executionTime The total time taken to perform this migration run (in ms).
*/
private void logSummary(int migrationSuccessCount, long executionTime) {
if (migrationSuccessCount == 0) {
LOG.info("Schema " + schema + " is up to date. No migration necessary.");
return;
}
if (migrationSuccessCount == 1) {
LOG.info("Successfully applied 1 migration to schema " + schema + " (execution time " + TimeFormat.format(executionTime) + ")");
} else {
LOG.info("Successfully applied " + migrationSuccessCount + " migrations to schema " + schema + " (execution time " + TimeFormat.format(executionTime) + ")");
}
}
/**
* Applies this migration to the database. The migration state and the execution time are updated accordingly.
*
* @param group The group of migrations to apply.
*/
private void applyMigrations(final LinkedHashMap<MigrationInfoImpl, Boolean> group, boolean skipExecutingMigrations) {
boolean executeGroupInTransaction = isExecuteGroupInTransaction(group);
final StopWatch stopWatch = new StopWatch();
try {
if (executeGroupInTransaction) {
ExecutionTemplateFactory.createExecutionTemplate(connectionUserObjects.getJdbcConnection(), database).execute(new Callable<Object>() {
@Override
public Object call() {
doMigrateGroup(group, stopWatch, skipExecutingMigrations);
return null;
}
});
} else {
doMigrateGroup(group, stopWatch, skipExecutingMigrations);
}
} catch (FlywayMigrateException e) {
MigrationInfoImpl migration = e.getMigration();
String failedMsg = "Migration of " + toMigrationText(migration, e.isOutOfOrder()) + " failed!";
if (database.supportsDdlTransactions() && executeGroupInTransaction) {
LOG.error(failedMsg + " Changes successfully rolled back.");
} else {
LOG.error(failedMsg + " Please restore backups and roll back database and code!");
stopWatch.stop();
int executionTime = (int) stopWatch.getTotalTimeMillis();
schemaHistory.addAppliedMigration(migration.getVersion(), migration.getDescription(),
migration.getType(), migration.getScript(), migration.getResolvedMigration().getChecksum(), executionTime, false);
}
throw e;
}
}
private boolean isExecuteGroupInTransaction(LinkedHashMap<MigrationInfoImpl, Boolean> group) {
boolean executeGroupInTransaction = true;
boolean first = true;
for (Map.Entry<MigrationInfoImpl, Boolean> entry : group.entrySet()) {
ResolvedMigration resolvedMigration = entry.getKey().getResolvedMigration();
boolean inTransaction = resolvedMigration.getExecutor().canExecuteInTransaction();
if (first) {
executeGroupInTransaction = inTransaction;
first = false;
continue;
}
if (!configuration.isMixed() && executeGroupInTransaction != inTransaction) {
throw new FlywayException(
"Detected both transactional and non-transactional migrations within the same migration group"
+ " (even though mixed is false). First offending migration: "
+ doQuote((resolvedMigration.getVersion() == null ? "" : resolvedMigration.getVersion())
+ (StringUtils.hasLength(resolvedMigration.getDescription()) ? " " + resolvedMigration.getDescription() : ""))
+ (inTransaction ? "" : " [non-transactional]"));
}
executeGroupInTransaction &= inTransaction;
}
return executeGroupInTransaction;
}
private void doMigrateGroup(LinkedHashMap<MigrationInfoImpl, Boolean> group, StopWatch stopWatch, boolean skipExecutingMigrations) {
Context context = new Context() {
@Override
public Configuration getConfiguration() {
return configuration;
}
@Override
public java.sql.Connection getConnection() {
return connectionUserObjects.getJdbcConnection();
}
};
for (Map.Entry<MigrationInfoImpl, Boolean> entry : group.entrySet()) {
final MigrationInfoImpl migration = entry.getKey();
boolean isOutOfOrder = entry.getValue();
final String migrationText = toMigrationText(migration, isOutOfOrder);
stopWatch.start();
if (isPreviousVersioned && migration.getVersion() == null) {
callbackExecutor.onMigrateOrUndoEvent(Event.AFTER_VERSIONED);
callbackExecutor.onMigrateOrUndoEvent(Event.BEFORE_REPEATABLES);
isPreviousVersioned = false;
}
if (skipExecutingMigrations) {
LOG.debug("Skipping execution of migration of " + migrationText);
} else {
LOG.debug("Starting migration of " + migrationText + " ...");
connectionUserObjects.restoreOriginalState();
connectionUserObjects.changeCurrentSchemaTo(schema);
try {
callbackExecutor.setMigrationInfo(migration);
callbackExecutor.onEachMigrateOrUndoEvent(Event.BEFORE_EACH_MIGRATE);
try {
LOG.info("Migrating " + migrationText);
migration.getResolvedMigration().getExecutor().execute(context);
migrateResult.migrations.add(commandResultFactory.createMigrateOutput(migration));
} catch (FlywayException e) {
callbackExecutor.onEachMigrateOrUndoEvent(Event.AFTER_EACH_MIGRATE_ERROR);
throw new FlywayMigrateException(migration, isOutOfOrder, e);
} catch (SQLException e) {
callbackExecutor.onEachMigrateOrUndoEvent(Event.AFTER_EACH_MIGRATE_ERROR);
throw new FlywayMigrateException(migration, isOutOfOrder, e);
}
LOG.debug("Successfully completed migration of " + migrationText);
callbackExecutor.onEachMigrateOrUndoEvent(Event.AFTER_EACH_MIGRATE);
} finally {
callbackExecutor.setMigrationInfo(null);
}
}
stopWatch.stop();
int executionTime = (int) stopWatch.getTotalTimeMillis();
schemaHistory.addAppliedMigration(migration.getVersion(), migration.getDescription(), migration.getType(),
migration.getScript(), migration.getResolvedMigration().getChecksum(), executionTime, true);
}
}
private String toMigrationText(MigrationInfoImpl migration, boolean isOutOfOrder) {
final MigrationExecutor migrationExecutor = migration.getResolvedMigration().getExecutor();
final String migrationText;
if (migration.getVersion() != null) {
migrationText = "schema " + schema + " to version " + doQuote(migration.getVersion()
+ (StringUtils.hasLength(migration.getDescription()) ? " - " + migration.getDescription() : ""))
+ (isOutOfOrder ? " [out of order]" : "")
+ (migrationExecutor.canExecuteInTransaction() ? "" : " [non-transactional]");
} else {
migrationText = "schema " + schema + " with repeatable migration " + doQuote(migration.getDescription())
+ (migrationExecutor.canExecuteInTransaction() ? "" : " [non-transactional]");
}
return migrationText;
}
private String doQuote(String text) {
return "\"" + text + "\"";
}
public static class FlywayMigrateException extends FlywayException {
private final MigrationInfoImpl migration;
private final boolean outOfOrder;
FlywayMigrateException(MigrationInfoImpl migration, boolean outOfOrder, SQLException e) {
super(ExceptionUtils.toMessage(e), e);
this.migration = migration;
this.outOfOrder = outOfOrder;
}
FlywayMigrateException(MigrationInfoImpl migration, boolean outOfOrder, FlywayException e) {
super(e.getMessage(), e);
this.migration = migration;
this.outOfOrder = outOfOrder;
}
public MigrationInfoImpl getMigration() {
return migration;
}
public boolean isOutOfOrder() {
return outOfOrder;
}
}
}