Database migration tool that enables versioned database schema evolution with simple SQL scripts and Java migrations
—
Primary database migration operations providing schema evolution, validation, and maintenance capabilities for managing database changes across all environments.
Executes all pending migrations in version order, applying schema changes to bring the database up to the latest version.
/**
* Starts the database migration. All pending migrations will be applied in order.
* Calling migrate on an up-to-date database has no effect.
* @return An object summarising the successfully applied migrations
* @throws FlywayException when the migration failed
*/
public MigrateResult migrate() throws FlywayExceptionUsage Examples:
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.output.MigrateResult;
// Basic migration
Flyway flyway = Flyway.configure()
.dataSource("jdbc:postgresql://localhost/mydb", "user", "pass")
.load();
MigrateResult result = flyway.migrate();
System.out.println("Applied " + result.migrationsExecuted + " migrations");
System.out.println("Current version: " + result.targetSchemaVersion);
// Migration with target version
Flyway flyway = Flyway.configure()
.dataSource(dataSource)
.target(MigrationVersion.fromVersion("2.1"))
.load();
flyway.migrate();Validates applied migrations against available migration files, detecting inconsistencies without making changes.
/**
* Validates the applied migrations against the available ones on the classpath.
* @throws FlywayException when the validation failed
*/
public void validate() throws FlywayException;
/**
* Validates the applied migrations against the available ones on the classpath.
* @return An object summarising the validation results
* @throws FlywayException when the validation failed
*/
public ValidateResult validateWithResult() throws FlywayException;Usage Examples:
// Simple validation
try {
flyway.validate();
System.out.println("Validation successful");
} catch (FlywayValidateException e) {
System.out.println("Validation failed: " + e.getMessage());
}
// Detailed validation results
ValidateResult result = flyway.validateWithResult();
if (!result.validationSuccessful) {
for (ValidateOutput invalid : result.invalidMigrations) {
System.out.println("Invalid: " + invalid.version + " - " + invalid.description);
}
}Removes all database objects including tables, views, procedures, and functions, returning the database to a clean state.
/**
* Drops all objects (tables, views, procedures, triggers, ...) in the configured schemas.
* The schemas are cleaned in the order they are configured.
* @return An object summarising the actions taken
* @throws FlywayException when the clean failed
*/
public CleanResult clean() throws FlywayException;Usage Examples:
// Clean database for testing
Flyway flyway = Flyway.configure()
.dataSource(testDataSource)
.schemas("test_schema")
.cleanDisabled(false) // Must explicitly enable clean
.load();
CleanResult result = flyway.clean();
System.out.println("Cleaned schemas: " + result.schemasCleaned);
// Conditional clean in test environment
if ("test".equals(environment)) {
flyway.clean();
flyway.migrate();
}Creates a baseline for an existing database by marking a specific version as the baseline, allowing migrations to start from that point.
/**
* Baselines an existing database, excluding all migrations up to and including baselineVersion.
* @return An object summarising the actions taken
* @throws FlywayException when the baseline failed
*/
public BaselineResult baseline() throws FlywayException;Usage Examples:
// Baseline existing database
Flyway flyway = Flyway.configure()
.dataSource(existingDatabase)
.baselineVersion(MigrationVersion.fromVersion("1.0"))
.baselineDescription("Legacy database baseline")
.load();
BaselineResult result = flyway.baseline();
System.out.println("Baseline version: " + result.baselineVersion);
// Automatic baseline on migrate
Flyway flyway = Flyway.configure()
.dataSource(dataSource)
.baselineOnMigrate(true)
.baselineVersion(MigrationVersion.fromVersion("2.0"))
.load();
flyway.migrate(); // Will baseline automatically if neededRepairs the schema history table by removing failed migration entries and realigning checksums.
/**
* Repairs the Flyway schema history table. This will perform the following actions:
* - Remove any failed migrations on databases without DDL transactions
* - Realign the checksums, descriptions and types of the applied migrations with the ones of the available migrations
* @return An object summarising the actions taken
* @throws FlywayException when the repair failed
*/
public RepairResult repair() throws FlywayException;Usage Examples:
// Repair after failed migration
RepairResult result = flyway.repair();
System.out.println("Repaired migrations: " + result.migrationsRepaired);
System.out.println("Removed entries: " + result.migrationsRemoved);
// Check repair results
for (RepairOutput repair : result.repairActions) {
System.out.println("Repaired: " + repair.version + " - " + repair.description);
}Retrieves comprehensive information about migration status, including applied, pending, and failed migrations.
/**
* Retrieves the complete information about all migrations including applied, pending and current migrations with details and status.
* @return An object containing all migration info
*/
public MigrationInfoService info();Usage Examples:
// Get migration information
MigrationInfoService infoService = flyway.info();
// All migrations
MigrationInfo[] all = infoService.all();
for (MigrationInfo info : all) {
System.out.println(info.getVersion() + " " + info.getState() + " " + info.getDescription());
}
// Current version
MigrationInfo current = infoService.current();
if (current != null) {
System.out.println("Current version: " + current.getVersion());
}
// Pending migrations
MigrationInfo[] pending = infoService.pending();
System.out.println("Pending migrations: " + pending.length);Undoes migrations down to a specified target version (Teams edition feature).
/**
* Undoes the most recently applied versioned migration.
* @return An object summarising the actions taken
* @throws FlywayException when undo failed
*/
public OperationResult undo() throws FlywayException;Usage Examples:
// Undo last migration (Teams feature)
OperationResult result = flyway.undo();
System.out.println("Undo operation: " + result.operation);
// Undo to specific version
Flyway flyway = Flyway.configure()
.dataSource(dataSource)
.target(MigrationVersion.fromVersion("1.5"))
.load();
flyway.undo();public class MigrateResult extends HtmlResult {
/** List of migrations that were executed */
public List<MigrateOutput> migrations;
/** The initial schema version before migration */
public String initialSchemaVersion;
/** The target schema version after migration */
public String targetSchemaVersion;
/** The schema name used */
public String schemaName;
/** Number of migrations executed */
public int migrationsExecuted;
/** Whether the migration was successful */
public boolean success;
/** Flyway version used for migration */
public String flywayVersion;
/** Database connection string/name */
public String database;
/** Database type identifier */
public String databaseType;
/** List of warnings encountered */
public List<String> warnings;
/** Calculate total execution time of all migrations */
public long getTotalMigrationTime();
/** Add a warning message */
public void addWarning(String warning);
/** Get migrations that are still pending */
public List<MigrateOutput> getPendingMigrations();
/** Get migrations that completed successfully */
public List<MigrateOutput> getSuccessfulMigrations();
/** Get migrations that failed */
public List<MigrateOutput> getFailedMigrations();
}public class CleanResult extends OperationResultBase {
/** List of schemas that were cleaned */
public List<String> schemasCleaned;
/** List of schemas that were dropped */
public List<String> schemasDropped;
}public class ValidateResult extends OperationResultBase {
/** Error details consolidated from validation */
public final ErrorDetails errorDetails;
/** List of invalid migrations found */
public final List<ValidateOutput> invalidMigrations;
/** Whether validation was successful */
public final boolean validationSuccessful;
/** Number of migrations validated */
public final int validateCount;
/** All validation error messages combined */
public String getAllErrorMessages();
}public class BaselineResult extends OperationResultBase {
/** The version that was baselined */
public String baselineVersion;
/** Description of the baseline */
public String baselineDescription;
}public class RepairResult extends OperationResultBase {
/** List of migrations that were repaired */
public List<RepairOutput> repairActions;
/** Number of migrations repaired */
public int migrationsRepaired;
/** Number of migration entries removed */
public int migrationsRemoved;
}All operations throw FlywayException or its subclasses on failure:
try {
flyway.migrate();
} catch (FlywayValidateException e) {
// Handle validation errors specifically
for (ErrorDetails error : e.getErrorDetails()) {
System.out.println("Error: " + error.getErrorCode() + " - " + error.getMessage());
}
} catch (FlywayException e) {
// Handle general Flyway errors
System.out.println("Migration failed: " + e.getMessage());
}Install with Tessl CLI
npx tessl i tessl/maven-org-flywaydb--flyway-core