From 24d33afd59570f22af775aa58ac78cdbe98f585b Mon Sep 17 00:00:00 2001 From: Kevin Belisle Date: Thu, 2 Sep 2021 00:54:10 -0400 Subject: [PATCH] Add database schema migration --- app/src/main/kotlin/xyz/etztech/stonks/App.kt | 21 +++++++++++++++++++ app/src/main/kotlin/xyz/etztech/stonks/DSL.kt | 7 +++++++ 2 files changed, 28 insertions(+) diff --git a/app/src/main/kotlin/xyz/etztech/stonks/App.kt b/app/src/main/kotlin/xyz/etztech/stonks/App.kt index e77fea5..f0fb2ff 100644 --- a/app/src/main/kotlin/xyz/etztech/stonks/App.kt +++ b/app/src/main/kotlin/xyz/etztech/stonks/App.kt @@ -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 diff --git a/app/src/main/kotlin/xyz/etztech/stonks/DSL.kt b/app/src/main/kotlin/xyz/etztech/stonks/DSL.kt index 5850c5c..7040ebd 100644 --- a/app/src/main/kotlin/xyz/etztech/stonks/DSL.kt +++ b/app/src/main/kotlin/xyz/etztech/stonks/DSL.kt @@ -41,3 +41,10 @@ object Players : Table() { override val primaryKey = PrimaryKey(id, name = "PK_id") } + +object KeyValue : Table() { + val key: Column = varchar("Key", 150) + val value: Column = integer("Value") + + override val primaryKey = PrimaryKey(key, name = "PK_key") +}