How do I configure Flyway in Grails3 / Postgres?

2019-03-06 07:42发布

问题:

I am trying to use Flyway to run migrations for my Grails 3.2.8 application. According to https://flywaydb.org/documentation/plugins/grails one should just need to add a dependency to build.gradle:

dependencies {
  compile "org.flywaydb:flyway-core:4.1.2"
}

As I want Flyway to generate my schema I have also edited application.yml to not have domain object generated. If I do not have this setting Grails will generate my tables - not Flyway.

environments:
    development:
        dataSource:
            dbCreate: none

I have also added a migration file to:

grails-app
  conf
    db
      migration
        V1__create_tables.sql

I also read here (https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html) that some extra configuration could done so I added this to application.yml:

flyway:
  enabled: true
  locations: classpath:grails-app/conf/db/migration
  sql-migration-prefix: V
  sql-migration-suffix: .sql

I have also tried without any of my added configurations. I seem to be missing something?

回答1:

spring-boot auto-configuration of flyway relies by default on one single DataSource bean being available at the time of auto-configuration.

ref. https://github.com/spring-projects/spring-boot/blob/v1.5.2.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration.java#L130

however, that is not the case if gorm defines the grails DataSource - that happens after boot autoconfig.

one possible solution is to define an "alias" DataSource bean that acts as the flyway dataSource, delegating to the gorm/grails defined one.

@Configuration
class FlywayConfig {

    @Autowired
    DataSource dataSource

    @Bean
    @FlywayDataSource
    DataSource flywayDataSource() {
        return dataSource
    }

}

sample: check https://github.com/zyro23/stackoverflow-43211960/commit/c4063c900b7f96bc9ba65c84684a14a1992ca2a5

visiting http://localhost:8080/dbconsole (jdbc:h2:mem:devDb) you should see that the TEST table has been created.



标签: grails flyway