aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/moe/nea/ledger/database/DBUpgrade.kt
blob: 7d1782aa6cd646625e04a92c4c4d5f554cb47db5 (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
55
56
57
58
59
60
61
62
63
64
65
66
67
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
				}
			}
		}
	}
}