Search code examples
gradleflyway

How should I structure these gradle task dependencies?


I have these gradle tasks:
- startTestDatabaseContainer: builds and starts a docker container with a database
- removeTestDatabaseContainer: stops and removes the docker container
- flywayValidate: a task from org.flywaydb.flyway that validates my migration files

I wish to run these three tasks in order. Reading this leads me to this solution:

flywayValidate.dependsOn startTestDatabaseContainer
flywayValidate.finalizedBy removeTestDatabaseContainer

This works ok, but then I can't run gradle flywayValidate from the commandline without startTestDatabaseContainer and removeTestDatabaseContainer also being invoked. I want to be able to run flywayValidate without that happening.

What can I do to accomplish this when I cannot have ordered dependencies in gradle?

My first attempt was simply:

task validateMigration {
    dependsOn startTestDatabaseContainer
    dependsOn flywayValidate
    finalizedBy removeTestDatabaseContainer
}

But that fails because flywayValidate can run before startTestDatabaseContainer.

Edit: I've setup a demonstration base on Opal's solution here: github.com/stianlagstad/flyway-migration-error-causes-final-gradle-task-to-not-execute. Clone it and run gradle validateMigration. The migration will fail and the final gradle task won't run (and docker ps will show the container still running). If you fix the migration file then everything works as expected. I'm sure I'm misunderstanding something. Any pointers would be helpful!


Solution

  • task validateMigration {
        dependsOn startTestDatabaseContainer
        dependsOn flywayMigrate
        flywayMigrate.finalizedBy removeTestDatabaseContainer
        flywayMigrate.mustRunAfter startTestDatabaseContainer
    }
    

    This did the trick! Thank you orzeh for the PR on Github, and thank you Opal for the help!