blob: a77ea305c7c9bdb2e14e6ce9cd810b6a7cdda238 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
package moe.nea.ledger.database
import moe.nea.ledger.Ledger
import java.sql.Connection
import java.sql.DriverManager
class Database {
lateinit var connection: Connection
object MetaTable : Table("LedgerMeta") {
val key = column("key", DBString)
val value = column("value", DBString)
init {
unique(key)
}
}
data class MetaKey(val name: String) {
companion object {
val DATABASE_VERSION = MetaKey("databaseVersion")
val LAST_LAUNCH = MetaKey("lastLaunch")
}
}
fun setMetaKey(key: MetaKey, value: String) {
MetaTable.insert(connection, Table.OnConflict.REPLACE) {
it[MetaTable.key] = key.name
it[MetaTable.value] = value
}
}
val databaseVersion: Long = 1
fun loadAndUpgrade() {
connection = DriverManager.getConnection("jdbc:sqlite:${Ledger.dataFolder.resolve("database.db")}")
MetaTable.createIfNotExists(connection)
val meta = MetaTable.selectAll(connection).associate { MetaKey(it[MetaTable.key]) to it[MetaTable.value] }
val lastLaunch = meta[MetaKey.LAST_LAUNCH]?.toLong() ?: 0L
println("Last launch $lastLaunch")
setMetaKey(MetaKey.LAST_LAUNCH, System.currentTimeMillis().toString())
val oldVersion = meta[MetaKey.DATABASE_VERSION]?.toLong() ?: -1
println("Old Database Version: $oldVersion; Current version: $databaseVersion")
// TODO: create a backup if there is a db version upgrade happening
DBUpgrade.performUpgradeChain(
connection, oldVersion, databaseVersion,
Upgrades().upgrades
) { version ->
setMetaKey(MetaKey.DATABASE_VERSION, version.toString())
}
}
}
|