Search code examples
gradleflyway

Gradle flyway script to update multiple databases


I have a Gradle script which uses the flyway plugin to create some database tables, and now I need to update the script so that it can work with 2 separate sets of flyway scripts, each of which updates a separate database.

In the single-database version of the script I simply do this:

flyway {
    url = 'jdbc:edb://localhost:5432/mydb'
    schemas = ['my_schema']
    user = 'my_user'
    password = 'my_pass'
    locations = ['filesystem:src/main/resources/db/flyway/my_db']
}

I've been experimenting with declaring a new task to run the scripts for the second db:

task flywayMigrate2 << {
    ext {
        flyway {
            url = 'jdbc:edb://localhost:5432/mydb2'
            schemas = ['my_schema2']
            user = 'my_user2'
            password = 'my_pass2'
            locations = ['filesystem:src/main/resources/db/flyway/my_db2']
        }
    }    
}

flywayMigrate2.finalizedBy flywayMigrate

My Gradle skills are poor, but I know this isn't the right way to do it - my understanding is that the ext block overwrites the original flyway configuration, so if I wanted to run flywayMigrate after flywayMigrate2 it would continue to use the second set of config values rather than reverting to the original set.

I can't be the first person to need to do this, but I'm struggling to find a decent approach, can anyone help?


Solution

  • The flyway { ... } extension object is for configuring properties which are common to all flyway tasks. Each task also has properties which can be configured, my guess is that task level properties override properties configured on the flyway { ... } extension object.

    I think you'd just configure two FlywayMigrateTask instances in your build.gradle

    import org.flywaydb.gradle.task.*
    
    task migrate1(type: FlywayMigrateTask) {
        url = 'jdbc:edb://localhost:5432/mydb1'
        user = 'user1'
        locations = ['filesystem:src/main/flyway/db1/migration']
        // etc
    }
    
    task migrate2(type: FlywayMigrateTask) {
        url = 'jdbc:edb://localhost:5432/mydb2'
        user = 'user2'
        locations = ['filesystem:src/main/flyway/db2/migration']
        // etc
    }
    

    See also AbstractFlywayTask.java