21

I am using Springboot and Flyway. The migrations work just fine but I wanted to be able perform a clean flyway command when the application context gets loaded with test profile.

Is it possible to configure SpringBoot to do clean and then migrate if active profile is test?

kryger
  • 12,906
  • 8
  • 44
  • 65
Barbadoss
  • 1,136
  • 3
  • 14
  • 22

4 Answers4

42

You can overwrite the Flyway autoconfiguration like this:

@Bean
@Profile("test")
public Flyway flyway(DataSource theDataSource) {
    Flyway flyway = new Flyway();
    flyway.setDataSource(theDataSource);
    flyway.setLocations("classpath:db/migration");
    flyway.clean();
    flyway.migrate();

    return flyway;
}

In Spring Boot 1.3 (current version is 1.3.0.M1, GA release is planned for September), you can use a FlywayMigrationStrategy bean to define the actions you want to run:

@Bean
@Profile("test")
public FlywayMigrationStrategy cleanMigrateStrategy() {
    FlywayMigrationStrategy strategy = new FlywayMigrationStrategy() {
        @Override
        public void migrate(Flyway flyway) {
            flyway.clean();
            flyway.migrate();
        }
    };

    return strategy;
}
yankee
  • 38,872
  • 15
  • 103
  • 162
dunni
  • 43,386
  • 10
  • 104
  • 99
  • 1
    Your solution works but is there a way to avoid this behavior if the server reboots only to hot-swapping? During development it's not necessary, in fact it's rather annoying, to drop the entire data base. Is there a solution for this? – Stefan Falk May 11 '18 at 22:48
9

in more recent versions of spring boot (eg 2.0.2) you can use the property spring.flyway.clean-on-validation-error if you want to use clean because of a change in the sql files

1

Same answer as @dunni (Thanks, by the way!), but updated to modern Java 8+

@Profile("test")
@Bean
public FlywayMigrationStrategy flywayCleanMigrationStrategy() {
  return flyway -> {
    flyway.clean();
    flyway.migrate();
  };
}
t0r0X
  • 4,212
  • 1
  • 38
  • 34
1

... and here's the Kotlin version, if needed :)

@Profile("test")
@Configuration
class FlywayMigrationConfig {
    @Bean
    fun flywayCleanMigrationStrategy() = FlywayMigrationStrategy {
        it.clean()
        it.migrate()
    }
}
spyro
  • 475
  • 4
  • 10