DEV Community

Discussion on: How to setup jOOQ with Flyway and Gradle

Collapse
 
tbroyer profile image
Thomas Broyer

FWIW, the way I do the jOOQ codegen in my projects is to "just" use a JavaExec task and put the config in an XML file:

val flywayConf by lazy {
    Properties().apply {
        file("src/main/resources/db/flyway.conf").reader().use { load(it) }
    }
}

val dbUrl = findProperty("db.url") as? String ?: "jdbc:postgresql:///foo"
val dbUser = findProperty("db.user") as? String ?: "foo"
val dbPassword = findProperty("db.password") as? String ?: "foo"
val dbSchema = flywayConf.getProperty("flyway.schemas")

flyway {
    url = dbUrl
    user = dbUser
    password = dbPassword
    schemas = arrayOf(dbSchema)
}

val jooqCodegen by configurations.creating {
    isVisible = false
    isCanBeResolved = true
    isCanBeConsumed = false
}

dependencies {
    api(platform(project(":platform"))
    api("org.jooq:jooq")
    api("org.postgresql:postgresql")
    api("com.google.guava:guava")

    jooqCodegen(platform(project(":platform")))
    jooqCodegen("org.jooq:jooq-codegen")
    jooqCodegen("org.postgresql:postgresql")
}

val jooqOutputDir = file("src/main/jooq")

tasks {
    register<JavaExec>("jooq") {
        val jooqConfigFile = file("src/jooq-codegen.xml")

        dependsOn("flywayMigrate")
        finalizedBy("spotlessJavaApply")

        inputs.dir("src/main/resources/db/migration").withPathSensitivity(PathSensitivity.RELATIVE)
        inputs.file(jooqConfigFile).withPathSensitivity(PathSensitivity.NONE)
        outputs.dir(jooqOutputDir)

        doFirst {
            project.delete(jooqOutputDir)
        }

        classpath = jooqCodegen
        main = "org.jooq.codegen.GenerationTool"
        systemProperties = mapOf(
            "db.url" to dbUrl,
            "db.user" to dbUser,
            "db.password" to dbPassword,
            "db.schema" to dbSchema,
            "outputdir" to jooqOutputDir.path
        )
        args(jooqConfigFile)
    }
}
sourceSets {
    main {
        java {
            srcDir(jooqOutputDir)
        }
    }
}
idea {
    module {
        generatedSourceDirs.add(jooqOutputDir)
    }
}

(note: we run the codegen against a Postgresql database, so we do it manually and commit the generated files, hence the jooqOutputDir being in src/main, and running Spotless as a finalizer task to reformat the code; also we only use SQL migrations, hence the inputs only listing src/main/resources/db/migration)