I am trying to generate jOOQ
classes from a database running in docker container(Testcontainers
) which will be migrated with flyway
during gradle
build. I am new to gradle and I created working proof of concept which does not feel right, because I have to start the container in configuration phase, so the database url
, password
and username
are available to configuration extensions(flyway
and jooq
). Then I have to register container stop using deprecated method buildFinished
I would like for the container to start only when generateJooq
task needs to be run. Ideally there would be three tasks, first would start the container with database, second would migrate the started database with flyway and third would generate jooq classes, and after that, stop the running container. Any advice how to do that?
import org.testcontainers.containers.PostgreSQLContainer
plugins {
id("org.flywaydb.flyway") version "8.5.13"
id("nu.studer.jooq") version "7.1.1"
}
repositories {
mavenCentral()
}
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.testcontainers:postgresql:1.17.3")
classpath("org.postgresql:postgresql:42.2.14")
}
}
val flywayMigration: Configuration by configurations.creating
dependencies {
flywayMigration("org.postgresql:postgresql:42.3.3")
jooqGenerator("org.postgresql:postgresql:42.3.3")
jooqGenerator("jakarta.xml.bind:jakarta.xml.bind-api:4.0.0")
}
var instance: PostgreSQLContainer<Nothing>? = null
task("postgreSQLContainer") {
instance = PostgreSQLContainer<Nothing>("postgres:11.6")
instance?.start()
gradle.buildFinished {
if (instance?.isRunning == true) {
instance?.stop()
}
}
}
flyway {
configurations = arrayOf("flywayMigration")
url = instance?.jdbcUrl
user = instance?.username
password = instance?.password
}
jooq {
configurations {
create("main") {
jooqConfiguration.apply {
logging = org.jooq.meta.jaxb.Logging.WARN
jdbc.apply {
driver = "org.postgresql.Driver"
url = flyway.url
user = flyway.user
password = flyway.password
}
generator.apply {
name = "org.jooq.codegen.DefaultGenerator"
database.apply {
inputSchema = "public"
}
target.apply {
packageName = "com.cleevio.jooq"
}
}
}
}
}
}
tasks.named<nu.studer.gradle.jooq.JooqGenerate>("generateJooq") {
dependsOn(tasks.named("postgreSQLContainer"))
dependsOn(tasks.named("flywayMigrate"))
inputs.files(fileTree("src/main/resources/db/migration"))
.withPropertyName("migrations")
.withPathSensitivity(PathSensitivity.RELATIVE)
allInputsDeclared.set(true)
}