Add database schema migration

main release-0.6
Kevin Belisle 2021-09-02 00:54:10 -04:00
parent a86453f497
commit 24d33afd59
2 changed files with 28 additions and 0 deletions

View File

@ -4,6 +4,7 @@ import com.natpryce.konfig.*
import java.io.FileInputStream
import java.util.*
import kotlinx.coroutines.*
import kotlinx.serialization.*
import org.h2.tools.Server
import org.jetbrains.exposed.exceptions.ExposedSQLException
import org.jetbrains.exposed.sql.*
@ -11,6 +12,7 @@ import org.jetbrains.exposed.sql.transactions.TransactionManager
import org.jetbrains.exposed.sql.transactions.transaction
import xyz.etztech.stonks.api.initApiServer
import xyz.etztech.stonks.dsl.AggregateStatistics
import xyz.etztech.stonks.dsl.KeyValue
import xyz.etztech.stonks.dsl.LiveStatistics
import xyz.etztech.stonks.dsl.Players
import xyz.etztech.stonks.dsl.Statistics
@ -91,6 +93,7 @@ fun initH2Server(
SchemaUtils.create(LiveStatistics)
SchemaUtils.create(AggregateStatistics)
SchemaUtils.create(Players)
SchemaUtils.create(KeyValue)
// Create indexes with explicit SQL because I can't figure out how to do it with exposed
// Wrap it in a try block because it throws an exception if index already exists
@ -113,6 +116,24 @@ fun initH2Server(
TransactionManager.current()
.exec("CREATE INDEX idx_type_name ON LiveStatistics (\"Type\", \"Name\")")
} catch (e: ExposedSQLException) {}
val schemaVersions =
KeyValue.slice(KeyValue.value).select { KeyValue.key.eq("SchemaVersion") }.map {
it[KeyValue.value]
}
val schemaVersion = if (schemaVersions.count() > 0) schemaVersions.single() else 0
println("Database schemaVersion = ${schemaVersion}")
if (schemaVersion < 1) {
println("Migrating database to schemaVersion 1.")
TransactionManager.current().exec("TRUNCATE TABLE AGGREGATESTATISTICS")
KeyValue.insert {
it[KeyValue.key] = "SchemaVersion"
it[KeyValue.value] = 1
}
}
}
return database

View File

@ -41,3 +41,10 @@ object Players : Table() {
override val primaryKey = PrimaryKey(id, name = "PK_id")
}
object KeyValue : Table() {
val key: Column<String> = varchar("Key", 150)
val value: Column<Int> = integer("Value")
override val primaryKey = PrimaryKey(key, name = "PK_key")
}