Sub topic 9
Checksum validation and what to do when it fails
This chapter assumes you can write versioned migrations, that you know Flyway records each applied migration in flyway_schema_history, and that Spring Boot runs Flyway at startup. Here you will see how Flyway detects changes to applied migrations, why it refuses to start when it finds one, and how to recover safely.
What a checksum is
A checksum is a number computed from the content of a migration. Flyway computes one for every SQL migration file and stores it in the checksum column of flyway_schema_history when it applies the migration. For Java migrations, the checksum is whatever the class reports through getChecksum(). BaseJavaMigration returns null by default, so Java migrations are not checked unless you override that method.
On later runs, Flyway computes the checksum of each file on the classpath again and compares it with the stored value. If the two differ, the file changed after it was applied.
The purpose is to protect a promise: a versioned migration describes one exact change, and every environment that applies version 2 got the same version 2. If someone edits V2__add_display_name.sql after it ran on a colleague's machine or in production, those databases and a fresh database built from the edited file no longer match. Flyway cannot tell which is correct, so it stops.
When validation runs
Flyway runs validate before migrate when spring.flyway.validate-on-migrate is true. This is the default, and the configuration chapter showed it set explicitly. Validation compares the migrations found in spring.flyway.locations with the rows in the history table. It reports:
- A checksum mismatch for an applied migration.
- An applied migration that no longer exists in the locations (a missing migration).
- A migration that has a lower version than the latest applied one but was never applied (an ignored migration, covered in the team workflow chapter).
- A previous failed migration still recorded in the history table.
- A description or type that differs from the history row.
Because Spring Boot calls migrate during context startup, a validation error stops the application from starting.
Caused by: org.flywaydb.core.api.exception.FlywayValidateException: Validate failed: Migrations have failed validation
Migration checksum mismatch for migration version 2
-> Applied to database : 1573920891
-> Resolved locally : -204118345
Either revert the changes to the migration, or run repair to update the schema history.The two numbers are the stored checksum and the checksum of the file now on the classpath. Your numbers will differ, because they depend on the file contents.
Reproducing a mismatch
Start with the migrations from earlier chapters and let the application run once so versions 1 and 2 are applied. Then change an applied file:
-- src/main/resources/db/migration/V2__add_display_name.sql
-- Edited after it was applied
ALTER TABLE app_user ADD COLUMN display_name VARCHAR(255);The only change is the column length, from 200 to 255. Restart the application and it fails with the mismatch error above. Flyway does not look at what the change means. Any difference counts, and that includes whitespace and comments. Flyway normalizes line endings, so a change from LF to CRLF alone does not usually trigger a mismatch. Be careful with editors and Git settings that rewrite files, because anything beyond line endings, such as a stripped trailing space or a re-saved encoding, changes the checksum.
Choosing the right fix
Do not reach for repair first. The correct fix depends on what happened and where the migration has run.
The diagram block must follow the required format, so here it is in full.
Revert the edit
If the change was accidental, restore the file with git checkout -- <file> or git restore. This is the most common cause. Reformatting tools and editors that touch every file in a directory are frequent culprits.
Add a new migration instead
If you need a different result, leave the applied file as it was and add a migration with the next version.
-- src/main/resources/db/migration/V3__widen_display_name.sql
ALTER TABLE app_user ALTER COLUMN display_name TYPE VARCHAR(255);This syntax is PostgreSQL. Other databases use different ALTER COLUMN forms. This approach works in every environment, because each database moves forward from whatever state it is in. It is the right answer for anything that has left your machine.
Rebuild a disposable database
If the migration has only run on your local database or a throwaway test database, you can edit the file and recreate the database. With a container database, remove the container and volume and start again. Do this only when no one else has applied the old version. A teammate whose database holds the old version will see the same error.
Use repair
repair updates the history table so it matches the files on disk. It recalculates checksums of applied migrations, updates their descriptions and types, and removes entries for failed migrations. It does not run any SQL against your schema and does not undo anything.
That makes it appropriate in a narrow case: the database already contains the effect you want, and only the recorded checksum is out of date. An example is a migration whose comments were corrected after it ran. Another is a change you applied by hand to match a new file.
Run it with the Flyway command line or the Maven or Gradle plugin, using the same locations and connection settings as the application:
flyway -url=jdbc:postgresql://localhost:5432/appdb \
-user=app -password="$DB_PASSWORD" \
-locations=filesystem:src/main/resources/db/migration \
repairSpring Boot does not call repair for you. If you want it as part of startup, you supply a FlywayMigrationStrategy bean, which is covered in the production chapter. Avoid that outside development, because it silences exactly the signal that validation exists to give.
<br>
Failed migrations
A different failure looks similar at startup. If a migration fails partway through, the outcome depends on whether the database supports transactional DDL. PostgreSQL does, so Flyway wraps each migration in a transaction and rolls it back. The history table has no row for it, you fix the file, and the next start applies it normally. Because the migration never counted as applied, editing it is fine.
MySQL and Oracle commit DDL statements implicitly. A migration that fails after its first few statements can leave the schema half changed. Flyway then records the migration with success = false, and the next startup stops with an error about a failed migration. To recover:
- Inspect the schema and manually undo the statements that did succeed, or complete them.
- Fix the migration file so it is correct for a clean database.
- Run
repairto remove the failed row from the history table. - Start the application so Flyway applies the migration again.
Check the success column to find such rows:
SELECT installed_rank, version, description, checksum, success
FROM flyway_schema_history
WHERE success = false;Checksums for repeatable and Java migrations
Repeatable migrations use the checksum differently. A changed checksum is not an error for them. It is the trigger that makes Flyway re-apply the file after all versioned migrations have run. This is why R__active_users_view.sql can be edited freely.
Java migrations are checked only if you provide a checksum. Without one, Flyway cannot notice that the code changed.
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 {
private static final String SQL =
"UPDATE app_user SET display_name = username WHERE display_name IS NULL";
@Override
public Integer getChecksum() {
return SQL.hashCode();
}
@Override
public void migrate(Context context) throws Exception {
try (Statement st = context.getConnection().createStatement()) {
st.execute(SQL);
}
}
}String.hashCode() is stable across JVM runs, so it is acceptable here. Each time the statement changes, the checksum changes and validation reports it, as with a SQL file.
Options that relax validation
Several properties change what validation does. Treat each as a deliberate exception.
| Property | Effect | Typical use |
|---|---|---|
| `spring.flyway.validate-on-migrate` | When `false`, skips validation before migrating | Almost never. It hides drift. |
| `spring.flyway.ignore-migration-patterns` | Downgrades listed problem types (such as `*:missing`) from errors to ignored | Rolling back to an older application build whose migration folder lacks newer files |
| `spring.flyway.out-of-order` | Lets Flyway apply a lower-numbered pending migration after higher ones | Team workflow, covered in a later chapter |
The ignore-migration-patterns syntax is <type>:<status>. For example, *:missing ignores applied migrations that no longer exist in the locations. In Flyway 10 and later, the older ignore-missing-migrations and ignore-future-migrations options are no longer available, and the pattern setting replaces them.
spring:
flyway:
ignore-migration-patterns: "*:missing"None of these patterns ignore a checksum mismatch by default. If you list *:*, you remove every safeguard, so avoid it.
Practical habits that prevent mismatches
- Treat a migration file as read-only once it is merged to a shared branch.
- Add a pre-merge check, for instance a CI job that fails if a file under
db/migrationthat existed on the main branch has changed. - Mark migration directories in
.gitattributesso line endings and whitespace handling are the same on every machine. - Run the full migration set against an empty database in CI. A mismatch caused by file edits shows up against an existing database, and a clean run catches broken SQL.
Exercise
Your teammate changed the comment at the top of V4_addindex.sql, which production already applied. The application now fails to start in staging with a checksum mismatch. The schema in staging is correct. What are two reasonable fixes, and which is better if the comment change is not important?
Show answer
One fix is to restore the original file with Git, so the checksum matches again. The other is to run repair against staging (and production, when it deploys), which updates the stored checksum to match the edited file without running any SQL. Reverting is better when the comment is unimportant, because it needs no changes to any database and keeps every environment consistent with the file in version control.
Exercise
A MySQL migration V7 fails after its first of three statements ran. The next startup fails with a message about a failed migration. Why does this not happen on PostgreSQL, and what are the steps to recover on MySQL?
Show answer
PostgreSQL supports transactional DDL, so Flyway rolls back the whole migration and writes no history row. MySQL commits DDL implicitly, so the first statement stays applied and Flyway records V7 with success = false. To recover, manually undo or complete the changes the first statement made, fix V7 so it works on a clean database, run repair to remove the failed history row, and restart the application so V7 runs again.