0
# Core Migration Operations
1
2
Primary database migration operations providing schema evolution, validation, and maintenance capabilities for managing database changes across all environments.
3
4
## Capabilities
5
6
### Migrate
7
8
Executes all pending migrations in version order, applying schema changes to bring the database up to the latest version.
9
10
```java { .api }
11
/**
12
* Starts the database migration. All pending migrations will be applied in order.
13
* Calling migrate on an up-to-date database has no effect.
14
* @return An object summarising the successfully applied migrations
15
* @throws FlywayException when the migration failed
16
*/
17
public MigrateResult migrate() throws FlywayException
18
```
19
20
**Usage Examples:**
21
22
```java
23
import org.flywaydb.core.Flyway;
24
import org.flywaydb.core.api.output.MigrateResult;
25
26
// Basic migration
27
Flyway flyway = Flyway.configure()
28
.dataSource("jdbc:postgresql://localhost/mydb", "user", "pass")
29
.load();
30
31
MigrateResult result = flyway.migrate();
32
System.out.println("Applied " + result.migrationsExecuted + " migrations");
33
System.out.println("Current version: " + result.targetSchemaVersion);
34
35
// Migration with target version
36
Flyway flyway = Flyway.configure()
37
.dataSource(dataSource)
38
.target(MigrationVersion.fromVersion("2.1"))
39
.load();
40
41
flyway.migrate();
42
```
43
44
### Validate
45
46
Validates applied migrations against available migration files, detecting inconsistencies without making changes.
47
48
```java { .api }
49
/**
50
* Validates the applied migrations against the available ones on the classpath.
51
* @throws FlywayException when the validation failed
52
*/
53
public void validate() throws FlywayException;
54
55
/**
56
* Validates the applied migrations against the available ones on the classpath.
57
* @return An object summarising the validation results
58
* @throws FlywayException when the validation failed
59
*/
60
public ValidateResult validateWithResult() throws FlywayException;
61
```
62
63
**Usage Examples:**
64
65
```java
66
// Simple validation
67
try {
68
flyway.validate();
69
System.out.println("Validation successful");
70
} catch (FlywayValidateException e) {
71
System.out.println("Validation failed: " + e.getMessage());
72
}
73
74
// Detailed validation results
75
ValidateResult result = flyway.validateWithResult();
76
if (!result.validationSuccessful) {
77
for (ValidateOutput invalid : result.invalidMigrations) {
78
System.out.println("Invalid: " + invalid.version + " - " + invalid.description);
79
}
80
}
81
```
82
83
### Clean
84
85
Removes all database objects including tables, views, procedures, and functions, returning the database to a clean state.
86
87
```java { .api }
88
/**
89
* Drops all objects (tables, views, procedures, triggers, ...) in the configured schemas.
90
* The schemas are cleaned in the order they are configured.
91
* @return An object summarising the actions taken
92
* @throws FlywayException when the clean failed
93
*/
94
public CleanResult clean() throws FlywayException;
95
```
96
97
**Usage Examples:**
98
99
```java
100
// Clean database for testing
101
Flyway flyway = Flyway.configure()
102
.dataSource(testDataSource)
103
.schemas("test_schema")
104
.cleanDisabled(false) // Must explicitly enable clean
105
.load();
106
107
CleanResult result = flyway.clean();
108
System.out.println("Cleaned schemas: " + result.schemasCleaned);
109
110
// Conditional clean in test environment
111
if ("test".equals(environment)) {
112
flyway.clean();
113
flyway.migrate();
114
}
115
```
116
117
### Baseline
118
119
Creates a baseline for an existing database by marking a specific version as the baseline, allowing migrations to start from that point.
120
121
```java { .api }
122
/**
123
* Baselines an existing database, excluding all migrations up to and including baselineVersion.
124
* @return An object summarising the actions taken
125
* @throws FlywayException when the baseline failed
126
*/
127
public BaselineResult baseline() throws FlywayException;
128
```
129
130
**Usage Examples:**
131
132
```java
133
// Baseline existing database
134
Flyway flyway = Flyway.configure()
135
.dataSource(existingDatabase)
136
.baselineVersion(MigrationVersion.fromVersion("1.0"))
137
.baselineDescription("Legacy database baseline")
138
.load();
139
140
BaselineResult result = flyway.baseline();
141
System.out.println("Baseline version: " + result.baselineVersion);
142
143
// Automatic baseline on migrate
144
Flyway flyway = Flyway.configure()
145
.dataSource(dataSource)
146
.baselineOnMigrate(true)
147
.baselineVersion(MigrationVersion.fromVersion("2.0"))
148
.load();
149
150
flyway.migrate(); // Will baseline automatically if needed
151
```
152
153
### Repair
154
155
Repairs the schema history table by removing failed migration entries and realigning checksums.
156
157
```java { .api }
158
/**
159
* Repairs the Flyway schema history table. This will perform the following actions:
160
* - Remove any failed migrations on databases without DDL transactions
161
* - Realign the checksums, descriptions and types of the applied migrations with the ones of the available migrations
162
* @return An object summarising the actions taken
163
* @throws FlywayException when the repair failed
164
*/
165
public RepairResult repair() throws FlywayException;
166
```
167
168
**Usage Examples:**
169
170
```java
171
// Repair after failed migration
172
RepairResult result = flyway.repair();
173
System.out.println("Repaired migrations: " + result.migrationsRepaired);
174
System.out.println("Removed entries: " + result.migrationsRemoved);
175
176
// Check repair results
177
for (RepairOutput repair : result.repairActions) {
178
System.out.println("Repaired: " + repair.version + " - " + repair.description);
179
}
180
```
181
182
### Info
183
184
Retrieves comprehensive information about migration status, including applied, pending, and failed migrations.
185
186
```java { .api }
187
/**
188
* Retrieves the complete information about all migrations including applied, pending and current migrations with details and status.
189
* @return An object containing all migration info
190
*/
191
public MigrationInfoService info();
192
```
193
194
**Usage Examples:**
195
196
```java
197
// Get migration information
198
MigrationInfoService infoService = flyway.info();
199
200
// All migrations
201
MigrationInfo[] all = infoService.all();
202
for (MigrationInfo info : all) {
203
System.out.println(info.getVersion() + " " + info.getState() + " " + info.getDescription());
204
}
205
206
// Current version
207
MigrationInfo current = infoService.current();
208
if (current != null) {
209
System.out.println("Current version: " + current.getVersion());
210
}
211
212
// Pending migrations
213
MigrationInfo[] pending = infoService.pending();
214
System.out.println("Pending migrations: " + pending.length);
215
```
216
217
### Undo
218
219
Undoes migrations down to a specified target version (Teams edition feature).
220
221
```java { .api }
222
/**
223
* Undoes the most recently applied versioned migration.
224
* @return An object summarising the actions taken
225
* @throws FlywayException when undo failed
226
*/
227
public OperationResult undo() throws FlywayException;
228
```
229
230
**Usage Examples:**
231
232
```java
233
// Undo last migration (Teams feature)
234
OperationResult result = flyway.undo();
235
System.out.println("Undo operation: " + result.operation);
236
237
// Undo to specific version
238
Flyway flyway = Flyway.configure()
239
.dataSource(dataSource)
240
.target(MigrationVersion.fromVersion("1.5"))
241
.load();
242
243
flyway.undo();
244
```
245
246
## Operation Results
247
248
### MigrateResult
249
250
```java { .api }
251
public class MigrateResult extends HtmlResult {
252
/** List of migrations that were executed */
253
public List<MigrateOutput> migrations;
254
/** The initial schema version before migration */
255
public String initialSchemaVersion;
256
/** The target schema version after migration */
257
public String targetSchemaVersion;
258
/** The schema name used */
259
public String schemaName;
260
/** Number of migrations executed */
261
public int migrationsExecuted;
262
/** Whether the migration was successful */
263
public boolean success;
264
/** Flyway version used for migration */
265
public String flywayVersion;
266
/** Database connection string/name */
267
public String database;
268
/** Database type identifier */
269
public String databaseType;
270
/** List of warnings encountered */
271
public List<String> warnings;
272
273
/** Calculate total execution time of all migrations */
274
public long getTotalMigrationTime();
275
/** Add a warning message */
276
public void addWarning(String warning);
277
/** Get migrations that are still pending */
278
public List<MigrateOutput> getPendingMigrations();
279
/** Get migrations that completed successfully */
280
public List<MigrateOutput> getSuccessfulMigrations();
281
/** Get migrations that failed */
282
public List<MigrateOutput> getFailedMigrations();
283
}
284
```
285
286
### CleanResult
287
288
```java { .api }
289
public class CleanResult extends OperationResultBase {
290
/** List of schemas that were cleaned */
291
public List<String> schemasCleaned;
292
/** List of schemas that were dropped */
293
public List<String> schemasDropped;
294
}
295
```
296
297
### ValidateResult
298
299
```java { .api }
300
public class ValidateResult extends OperationResultBase {
301
/** Error details consolidated from validation */
302
public final ErrorDetails errorDetails;
303
/** List of invalid migrations found */
304
public final List<ValidateOutput> invalidMigrations;
305
/** Whether validation was successful */
306
public final boolean validationSuccessful;
307
/** Number of migrations validated */
308
public final int validateCount;
309
310
/** All validation error messages combined */
311
public String getAllErrorMessages();
312
}
313
```
314
315
### BaselineResult
316
317
```java { .api }
318
public class BaselineResult extends OperationResultBase {
319
/** The version that was baselined */
320
public String baselineVersion;
321
/** Description of the baseline */
322
public String baselineDescription;
323
}
324
```
325
326
### RepairResult
327
328
```java { .api }
329
public class RepairResult extends OperationResultBase {
330
/** List of migrations that were repaired */
331
public List<RepairOutput> repairActions;
332
/** Number of migrations repaired */
333
public int migrationsRepaired;
334
/** Number of migration entries removed */
335
public int migrationsRemoved;
336
}
337
```
338
339
## Error Handling
340
341
All operations throw `FlywayException` or its subclasses on failure:
342
343
```java
344
try {
345
flyway.migrate();
346
} catch (FlywayValidateException e) {
347
// Handle validation errors specifically
348
for (ErrorDetails error : e.getErrorDetails()) {
349
System.out.println("Error: " + error.getErrorCode() + " - " + error.getMessage());
350
}
351
} catch (FlywayException e) {
352
// Handle general Flyway errors
353
System.out.println("Migration failed: " + e.getMessage());
354
}
355
```