Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear database at startup while using flyway

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;
    }
like image 326
Stefan K. Avatar asked Nov 23 '25 04:11

Stefan K.


1 Answers

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

like image 105
Axel Fontaine Avatar answered Nov 24 '25 19:11

Axel Fontaine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!