Sub topic 3
Checksum Validation and Safe Flyway Changes
Assume you know basic SQL, Spring Boot configuration, Maven or Gradle, and relational databases. Flyway uses checksums to detect changes to migrations that have already run.
Checksum validation
When Flyway applies a migration, it stores the migration name, version, execution time, and checksum in flyway_schema_history. On later starts, Flyway compares the stored checksum with the current file.
If an applied migration was edited, validation fails. Restore the original file whenever possible, then create a new migration for the change. Do not edit history to hide an accidental schema difference.
Existing databases and Java migrations
For a database that already contains the schema, baseline it before adding new migrations:
spring:
flyway:
baseline-on-migrate: true
baseline-version: 1Use this only when the target database is known to be non-empty. New databases should run their complete migration history instead.
A Java migration is useful when the change needs application logic or JDBC operations that are awkward in SQL. Place the class in db.migration and encode its version in the class name:
package db.migration;
import java.sql.Statement;
import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.flywaydb.core.api.migration.Context;
public class V3__Backfill_display_name extends BaseJavaMigration {
@Override
public void migrate(Context context) throws Exception {
try (Statement s = context.getConnection().createStatement()) {
s.executeUpdate(
"UPDATE app_user SET display_name = username " +
"WHERE display_name IS NULL");
}
}
}Testing and team workflow
Run migrations against a real PostgreSQL instance, commonly supplied by Testcontainers. A context test can verify that no migrations remain pending:
@SpringBootTest
class MigrationsTest {
@Autowired Flyway flyway;
@Test
void migrationsAreCurrent() {
assertEquals(0, flyway.info().pending().length);
}
}In a team, two developers may both create V4 migrations. Coordinate versions before merging. Keep migrations ordered. Enable out-of-order only as a deliberate temporary choice, because it makes history harder to understand.
Expand, contract, and production startup
Use expand-and-contract changes for rolling deployments:
- Add a nullable column or new table.
- Deploy code that writes both old and new shapes.
- Backfill and switch reads.
- Remove the old shape in a later migration.
In production, run migrations with controlled permissions and backups. Spring Boot normally calls Flyway during startup. A FlywayMigrationStrategy bean can add logging, checks, or an approved repair step before calling migrate, but keep startup migrations short to avoid holding deployments open.
Exercise
What should you do after discovering that an applied migration file was edited?
Show answer
Restore the applied file and create a new migration. Use repair only for an intentional, reviewed metadata correction.