diff options
author | Linnea Gräf <nea@nea.moe> | 2024-12-07 00:50:33 +0100 |
---|---|---|
committer | Linnea Gräf <nea@nea.moe> | 2024-12-07 00:50:33 +0100 |
commit | d708dca108dcbfe3d67dfe90c27de9cdb41184a6 (patch) | |
tree | 2b4b0c1d12396abbbaba7b6653616f6391988bbf /src/main/kotlin/moe/nea/ledger/database/DBUpgrade.kt | |
parent | 6bdc91b4bda1497e785af695769acae91e8e7064 (diff) | |
download | LocalTransactionLedger-d708dca108dcbfe3d67dfe90c27de9cdb41184a6.tar.gz LocalTransactionLedger-d708dca108dcbfe3d67dfe90c27de9cdb41184a6.tar.bz2 LocalTransactionLedger-d708dca108dcbfe3d67dfe90c27de9cdb41184a6.zip |
feat: Add SQLITE database entry logging
Diffstat (limited to 'src/main/kotlin/moe/nea/ledger/database/DBUpgrade.kt')
-rw-r--r-- | src/main/kotlin/moe/nea/ledger/database/DBUpgrade.kt | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/src/main/kotlin/moe/nea/ledger/database/DBUpgrade.kt b/src/main/kotlin/moe/nea/ledger/database/DBUpgrade.kt new file mode 100644 index 0000000..7d1782a --- /dev/null +++ b/src/main/kotlin/moe/nea/ledger/database/DBUpgrade.kt @@ -0,0 +1,68 @@ +package moe.nea.ledger.database + +import java.sql.Connection + +interface DBUpgrade { + val toVersion: Long + val fromVersion get() = toVersion - 1 + fun performUpgrade(connection: Connection) + + companion object { + + fun performUpgrades( + connection: Connection, + upgrades: Iterable<DBUpgrade>, + ) { + for (upgrade in upgrades) { + upgrade.performUpgrade(connection) + } + } + + fun performUpgradeChain( + connection: Connection, + from: Long, to: Long, + upgrades: Iterable<DBUpgrade>, + afterEach: (newVersion: Long) -> Unit, + ) { + val table = buildLookup(upgrades) + for (version in (from + 1)..(to)) { + val currentUpgrades = table[version] ?: listOf() + println("Scheduled ${currentUpgrades.size} upgrades to reach DB version $version") + performUpgrades(connection, currentUpgrades) + afterEach(version) + } + } + + fun buildLookup(upgrades: Iterable<DBUpgrade>): Map<Long, List<DBUpgrade>> { + return upgrades.groupBy { it.toVersion } + } + + fun createTable(to: Long, table: Table, vararg columns: Column<*>): DBUpgrade { + require(columns.all { it in table.columns }) + return of("Create table ${table}", to) { + table.createIfNotExists(it, columns.toList()) + } + } + + fun addColumns(to: Long, table: Table, vararg columns: Column<*>): DBUpgrade { + return of("Add columns to table $table", to) { + table.alterTableAddColumns(it, columns.toList()) + } + } + + fun of(name: String, to: Long, block: (Connection) -> Unit): DBUpgrade { + return object : DBUpgrade { + override val toVersion: Long + get() = to + + override fun performUpgrade(connection: Connection) { + block(connection) + } + + override fun toString(): String { + return name + } + } + } + } +}
\ No newline at end of file |