3

In my case, I'm using spring-boot with gradle and added flyway by simply putting compile 'org.flywaydb:flyway-core' to the build.gradle.

For a simulator run, which is in test, I would like to clear the database before each run. I've put a reset script in /src/test/resources/db/migration/V1.0__Reset.sql (with the real init sql-script at /src/main/resources/db/migration/V1.1__Init.sql), but receive a SyntaxException due to the reset script, which doesn't occur when I run it from the MySQL Workbench.

How can I reset or clear the database at startup?

-- UPDATE --

I've tried to use a Spring DataSourceInitializer, but it seems Flyway scripts are executed before the DS init, so it results in Hibernate Syntax error because the tables aren't found.

@Resource
DataSource ds;

@Bean
public DataSourceInitializer dbInit() throws FileNotFoundException, URISyntaxException {
        public DataSourceInitializer dbInit() throws FileNotFoundException, URISyntaxException {
        DataSourceInitializer re = new DataSourceInitializer();
        re.setDataSource(ds);
        re.setEnabled(true);

        String str = "classpath:sql/V1.0__Reset.sql";
        URL url = ResourceUtils.getURL(str);
        org.springframework.core.io.Resource resi = new PathResource(url.toURI());
        // new org.springframework.core.io.ClassPathResource(str)
        re.setDatabasePopulator(new ResourceDatabasePopulator(resi));
        return re;
    }
Community
  • 1
  • 1
Stefan K.
  • 7,701
  • 6
  • 52
  • 64

2 Answers2

3

Go for Flyway.clean(). It does exactly what you want. No need to write your own reset script.

Axel Fontaine
  • 34,542
  • 16
  • 106
  • 137
  • This is a similar questions (at least the solution is): http://stackoverflow.com/questions/29745995/execute-sth-after-or-before-bean-is-created – derkoe Apr 21 '15 at 12:35
0

You can use ApplicationRunner to run just after the startup and inside it do whatever you want with flyway. You'll also probably want to run migrate after clean:

@Component
public class CleanDatabase implements ApplicationRunner {

    @Autowired
    private Flyway flyway;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        flyway.clean();
        flyway.migrate();
    }

}