Flyway - Database Migrations
Click to see details of `Migrations have failed validation`
Unresolved dependency
mvn clean spring-boot:runcan fail errors such asValidate failed: Migrations have failed validationif the previous run ofmvn clean spring-boot:runhad resulted in failed migrations, asflywaywould have made an entry in theflyway_schema_history;db table.And then we see the following error when we run the
mvn clean spring-boot:runcommand next time.Click here for errors
ERROR org.springframework.boot.SpringApplication.reportFailure - Application run failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Validate failed: Migrations have failed validation Detected failed migration to version 001 (create baseline). Please remove any half-completed changes then run repair to fix the schema history. Caused by: org.flywaydb.core.api.exception.FlywayValidateException: Validate failed: Migrations have failed validation Detected failed migration to version 001 (create baseline). Please remove any half-completed changes then run repair to fix the schema history.Fix
flywayclearly telling us to repair the failed migrations in the logs. There are few ways to handle this issue, including both the manual and automated solutions. But let's focus on the automated solution for now usingflyway callbacksas we don't want manual intervention.We could consider an approach to automatically clean the failed entries from the
flyway_schema_historyafter a failed migration. For this purpose, we can use theafterMigrateErrorFlyway callback.Let's first create the SQL callback file
db/callback/afterMigrateError__repair.sql:DELETE FROM flyway_schema_history WHERE success=false;This will automatically remove any failed entry from the Flyway state history, whenever a migration error occurs.
But to make
flywayfind and execute this script, we have to add it to the path like below:spring.flyway.locations=classpath:db/migration,classpath:db/callbackAlthough it can be added to some existing properties file, but, we'll add it to a new
application-flyway-callback.propertiesand activate this newflyway-callbackspring profile.
flyway-callbackspring profile should be activated only when theflywayspring profile is also activated.

