Add migration file generator
This commit is contained in:
@@ -36,6 +36,8 @@ dependencies {
|
||||
implementation(libs.exposed.core)
|
||||
implementation(libs.exposed.jdbc)
|
||||
implementation(libs.exposed.kotlin.datetime)
|
||||
implementation(libs.exposed.migration.core)
|
||||
implementation(libs.exposed.migration.jdbc)
|
||||
|
||||
implementation(libs.postgres)
|
||||
implementation(libs.hikaricp)
|
||||
@@ -100,4 +102,12 @@ tasks {
|
||||
args = configArgs
|
||||
workingDir = file("run/development")
|
||||
}
|
||||
|
||||
register<JavaExec>("generateMigration") {
|
||||
group = "database"
|
||||
description = "Generates a new migration"
|
||||
|
||||
classpath = sourceSets["main"].runtimeClasspath
|
||||
mainClass.set("com.mtusi.messenger.main.plugins.DatabaseKt")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,6 +37,8 @@ koin-test = { module = "io.insert-koin:koin-test", version.ref = "koin" }
|
||||
exposed-core = { module = "org.jetbrains.exposed:exposed-core", version.ref = "exposed" }
|
||||
exposed-jdbc = { module = "org.jetbrains.exposed:exposed-jdbc", version.ref = "exposed" }
|
||||
exposed-kotlin-datetime = { module = "org.jetbrains.exposed:exposed-kotlin-datetime", version.ref = "exposed" }
|
||||
exposed-migration-core = { module = "org.jetbrains.exposed:exposed-migration-core", version.ref = "exposed" }
|
||||
exposed-migration-jdbc = { module = "org.jetbrains.exposed:exposed-migration-jdbc", version.ref = "exposed" }
|
||||
|
||||
postgres = { module = "org.postgresql:postgresql", version.ref = "postgres" }
|
||||
hikaricp = { module = "com.zaxxer:HikariCP", version.ref = "hikaricp" }
|
||||
|
||||
+5
-1
@@ -6,8 +6,12 @@ import org.jetbrains.exposed.v1.core.dao.id.java.UUIDTable
|
||||
import org.jetbrains.exposed.v1.datetime.timestamp
|
||||
|
||||
object SessionModel : UUIDTable("sessions") {
|
||||
val userId = reference("user_id", UserModel, onDelete = ReferenceOption.CASCADE)
|
||||
val userId = reference("user_id", UserModel, onDelete = ReferenceOption.CASCADE, onUpdate = ReferenceOption.NO_ACTION, fkName = "sessions_user_id_fkey")
|
||||
val tokenHash = varchar("token_hash", 64).uniqueIndex("sessions_token_hash_key")
|
||||
val createdAt = timestamp("created_at")
|
||||
val expiresAt = timestamp("expires_at")
|
||||
|
||||
init {
|
||||
index("sessions_user_id_idx", false, userId)
|
||||
}
|
||||
}
|
||||
|
||||
+6
-2
@@ -5,9 +5,13 @@ import org.jetbrains.exposed.v1.core.ReferenceOption
|
||||
import org.jetbrains.exposed.v1.core.Table
|
||||
|
||||
object ChatMemberModel : Table("chat_members") {
|
||||
val chatId = reference("chat_id", ChatModel, onDelete = ReferenceOption.CASCADE)
|
||||
val userId = reference("user_id", UserModel, onDelete = ReferenceOption.CASCADE)
|
||||
val chatId = reference("chat_id", ChatModel, onDelete = ReferenceOption.CASCADE, onUpdate = ReferenceOption.NO_ACTION, fkName = "chat_members_chat_id_fkey")
|
||||
val userId = reference("user_id", UserModel, onDelete = ReferenceOption.CASCADE, onUpdate = ReferenceOption.NO_ACTION, fkName = "chat_members_user_id_fkey")
|
||||
val position = integer("position")
|
||||
|
||||
override val primaryKey = PrimaryKey(chatId, userId)
|
||||
|
||||
init {
|
||||
index("chat_members_user_id_idx", false, userId)
|
||||
}
|
||||
}
|
||||
|
||||
+6
-2
@@ -9,8 +9,12 @@ import org.jetbrains.exposed.v1.datetime.timestamp
|
||||
const val MAX_MESSAGE_TEXT_LENGTH = 4000
|
||||
|
||||
object MessageModel : UUIDTable("messages") {
|
||||
val chatId = reference("chat_id", ChatModel, onDelete = ReferenceOption.CASCADE)
|
||||
val senderId = reference("sender_id", UserModel, onDelete = ReferenceOption.CASCADE)
|
||||
val chatId = reference("chat_id", ChatModel, onDelete = ReferenceOption.CASCADE, onUpdate = ReferenceOption.NO_ACTION, fkName = "messages_chat_id_fkey")
|
||||
val senderId = reference("sender_id", UserModel, onDelete = ReferenceOption.CASCADE, onUpdate = ReferenceOption.NO_ACTION, fkName = "messages_sender_id_fkey")
|
||||
val text = varchar("text", MAX_MESSAGE_TEXT_LENGTH)
|
||||
val createdAt = timestamp("created_at")
|
||||
|
||||
init {
|
||||
index("messages_chat_id_created_at_id_idx", false, chatId, createdAt, id)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,34 +1,41 @@
|
||||
package com.mtusi.messenger.main.plugins
|
||||
|
||||
import com.mtusi.messenger.main.config.database.DatabaseConfig
|
||||
import com.mtusi.messenger.main.config.database.SerialDatabaseConfig
|
||||
import com.mtusi.messenger.main.infrastructure.models.authentication.SessionModel
|
||||
import com.mtusi.messenger.main.infrastructure.models.chat.ChatMemberModel
|
||||
import com.mtusi.messenger.main.infrastructure.models.chat.ChatModel
|
||||
import com.mtusi.messenger.main.infrastructure.models.message.MessageModel
|
||||
import com.mtusi.messenger.main.infrastructure.models.user.UserModel
|
||||
import com.typesafe.config.ConfigFactory
|
||||
import com.zaxxer.hikari.HikariConfig
|
||||
import com.zaxxer.hikari.HikariDataSource
|
||||
import io.ktor.server.application.Application
|
||||
import io.ktor.server.application.ApplicationStopped
|
||||
import io.ktor.server.config.HoconApplicationConfig
|
||||
import io.ktor.server.config.getAs
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import org.flywaydb.core.Flyway
|
||||
import org.jetbrains.exposed.v1.core.ExperimentalDatabaseMigrationApi
|
||||
import org.jetbrains.exposed.v1.core.Table
|
||||
import org.jetbrains.exposed.v1.core.DatabaseConfig as ExposedDatabaseConfig
|
||||
import org.jetbrains.exposed.v1.jdbc.Database
|
||||
import org.jetbrains.exposed.v1.jdbc.JdbcTransaction
|
||||
import org.jetbrains.exposed.v1.jdbc.transactions.experimental.newSuspendedTransaction
|
||||
import org.jetbrains.exposed.v1.jdbc.transactions.transaction
|
||||
import org.jetbrains.exposed.v1.migration.jdbc.MigrationUtils
|
||||
import org.koin.ktor.ext.inject
|
||||
import java.io.File
|
||||
import javax.sql.DataSource
|
||||
|
||||
private const val MIGRATIONS_DIRECTORY = "src/main/resources/migrations"
|
||||
private const val DEVELOPMENT_DATABASE_CONFIG = "run/development/config/database.conf"
|
||||
|
||||
fun Application.configureDatabase() {
|
||||
|
||||
val config by inject<DatabaseConfig>()
|
||||
|
||||
val dataSource = HikariDataSource(
|
||||
HikariConfig().apply {
|
||||
poolName = "messenger"
|
||||
jdbcUrl = config.jdbcConnectionUrl
|
||||
username = config.username
|
||||
password = config.resolvePassword()
|
||||
maximumPoolSize = config.maxPoolSize
|
||||
connectionTimeout = config.connectionTimeoutMs
|
||||
}
|
||||
)
|
||||
val dataSource = config.createDataSource()
|
||||
|
||||
Database.connect(
|
||||
datasource = dataSource,
|
||||
@@ -44,6 +51,19 @@ fun Application.configureDatabase() {
|
||||
|
||||
}
|
||||
|
||||
private fun DatabaseConfig.createDataSource(): HikariDataSource {
|
||||
return HikariDataSource(
|
||||
HikariConfig().apply {
|
||||
poolName = "messenger"
|
||||
jdbcUrl = jdbcConnectionUrl
|
||||
username = this@createDataSource.username
|
||||
password = resolvePassword()
|
||||
maximumPoolSize = maxPoolSize
|
||||
connectionTimeout = connectionTimeoutMs
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
private fun DatabaseConfig.resolvePassword(): String {
|
||||
return password
|
||||
?: passwordFile?.let { File(it).readText().trim() }
|
||||
@@ -64,6 +84,65 @@ fun applyDatabaseMigrations(
|
||||
|
||||
}
|
||||
|
||||
fun main(args: Array<out String>) {
|
||||
generateMigration(args.joinToString("_"))
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalDatabaseMigrationApi::class)
|
||||
private fun generateMigration(description: String) {
|
||||
require(description.isNotEmpty()) { "Description cannot be empty" }
|
||||
|
||||
val tables: Array<Table> = arrayOf(
|
||||
UserModel,
|
||||
ChatModel,
|
||||
ChatMemberModel,
|
||||
MessageModel,
|
||||
SessionModel
|
||||
)
|
||||
|
||||
val config = HoconApplicationConfig(ConfigFactory.parseFile(File(DEVELOPMENT_DATABASE_CONFIG)).resolve())
|
||||
.property("database")
|
||||
.getAs<SerialDatabaseConfig>()
|
||||
|
||||
config.createDataSource().use { dataSource ->
|
||||
|
||||
Database.connect(dataSource)
|
||||
applyDatabaseMigrations(dataSource)
|
||||
|
||||
val migrations = File(MIGRATIONS_DIRECTORY).listFiles { it.extension == "sql" }.orEmpty()
|
||||
|
||||
val latestVersion = migrations.maxOfOrNull {
|
||||
it.name
|
||||
.substringBefore("__")
|
||||
.drop(1)
|
||||
.toInt()
|
||||
}
|
||||
|
||||
val version = latestVersion?.inc() ?: 1
|
||||
|
||||
transaction {
|
||||
|
||||
val statements = MigrationUtils.statementsRequiredForDatabaseMigration(*tables)
|
||||
|
||||
if (statements.isEmpty()) {
|
||||
println("Database schema is up to date, no migration generated")
|
||||
return@transaction
|
||||
}
|
||||
|
||||
val script = MigrationUtils.generateMigrationScript(
|
||||
tables = tables,
|
||||
scriptDirectory = MIGRATIONS_DIRECTORY,
|
||||
scriptName = "V${version}__$description"
|
||||
)
|
||||
|
||||
println("Generated migration ${script.path}")
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
suspend fun <R> suspendedTransaction(statement: JdbcTransaction.() -> R) = newSuspendedTransaction(
|
||||
context = Dispatchers.IO,
|
||||
statement = statement
|
||||
|
||||
Reference in New Issue
Block a user