diff --git a/.env.example b/.env.example index 5f66adc..eb9c21b 100644 --- a/.env.example +++ b/.env.example @@ -3,4 +3,5 @@ HOST=localhost DB_URL=jdbc:postgresql://localhost:5432/homepage DB_USERNAME=postgres -DB_PASSWORD=postgres \ No newline at end of file +DB_PASSWORD=postgres +DB_MIGRATE=true \ No newline at end of file diff --git a/src/main/kotlin/at/dokkae/homepage/Homepage.kt b/src/main/kotlin/at/dokkae/homepage/Homepage.kt index cad4d81..3f910d9 100644 --- a/src/main/kotlin/at/dokkae/homepage/Homepage.kt +++ b/src/main/kotlin/at/dokkae/homepage/Homepage.kt @@ -6,6 +6,7 @@ import at.dokkae.homepage.repository.MessageRepository import at.dokkae.homepage.repository.impls.JooqMessageRepository import at.dokkae.homepage.templates.Index import io.github.cdimascio.dotenv.dotenv +import org.flywaydb.core.Flyway import org.http4k.core.HttpHandler import org.http4k.core.Method.* import org.http4k.core.Response @@ -33,6 +34,17 @@ import java.util.UUID import java.util.concurrent.CopyOnWriteArrayList import kotlin.concurrent.thread +fun migrateDatabase(env: Environment) { + val flyway = Flyway.configure() + .dataSource(env.dbUrl, env.dbUsername, env.dbPassword) + .locations("classpath:db/migration") + .baselineOnMigrate(true) // optional: creates baseline if no schema history exists + .load() + + val result = flyway.migrate() + println("Migrated ${result.migrationsExecuted} migration${if (result.migrationsExecuted != 1) "s" else ""}") +} + data class Message( val author: String, val content: String, @@ -56,6 +68,10 @@ fun main() { ignoreIfMalformed = true }) + if (env.dbMigrate) { + migrateDatabase(env) + } + val connection = DriverManager.getConnection(env.dbUrl, env.dbUsername, env.dbPassword) val dslContext = DSL.using(connection, SQLDialect.POSTGRES) val messageRepository: MessageRepository = JooqMessageRepository(dslContext) diff --git a/src/main/kotlin/at/dokkae/homepage/config/Environment.kt b/src/main/kotlin/at/dokkae/homepage/config/Environment.kt index 83b3248..6321095 100644 --- a/src/main/kotlin/at/dokkae/homepage/config/Environment.kt +++ b/src/main/kotlin/at/dokkae/homepage/config/Environment.kt @@ -8,6 +8,7 @@ data class Environment( val dbUrl: String, val dbUsername: String, val dbPassword: String, + val dbMigrate: Boolean, ) { companion object { /** @@ -20,6 +21,7 @@ data class Environment( dbUrl = requireEnv(dotenv, "DB_URL"), dbUsername = requireEnv(dotenv, "DB_USERNAME"), dbPassword = requireEnv(dotenv, "DB_PASSWORD"), + dbMigrate = dotenv["DB_MIGRATE"]?.toBoolean() ?: false ) private fun requireEnv(dotenv: Dotenv, key: String): String {