summaryrefslogtreewikicommitdiff
path: root/core/src/db/Database.kt
diff options
context:
space:
mode:
authorFreya Murphy <freya@freyacat.org>2026-03-26 23:15:33 -0400
committerFreya Murphy <freya@freyacat.org>2026-03-27 23:09:23 -0400
commitf8322cd21cde68a72b05efbad3a05b8e67c0bdd0 (patch)
treed7e60bc8fedadc8fa7ae725571cad1f398eaf6dc /core/src/db/Database.kt
downloadkenshinshideandseek2-f8322cd21cde68a72b05efbad3a05b8e67c0bdd0.tar.gz
kenshinshideandseek2-f8322cd21cde68a72b05efbad3a05b8e67c0bdd0.tar.bz2
kenshinshideandseek2-f8322cd21cde68a72b05efbad3a05b8e67c0bdd0.zip
initial
Diffstat (limited to 'core/src/db/Database.kt')
-rw-r--r--core/src/db/Database.kt80
1 files changed, 80 insertions, 0 deletions
diff --git a/core/src/db/Database.kt b/core/src/db/Database.kt
new file mode 100644
index 0000000..27864b3
--- /dev/null
+++ b/core/src/db/Database.kt
@@ -0,0 +1,80 @@
+package cat.freya.khs.db
+
+import cat.freya.khs.Khs
+import java.util.UUID
+import org.jetbrains.exposed.v1.core.*
+import org.jetbrains.exposed.v1.jdbc.*
+import org.jetbrains.exposed.v1.jdbc.Database as Exposed
+import org.jetbrains.exposed.v1.jdbc.transactions.transaction
+
+class Database(plugin: Khs) {
+ val driver = getDriver(plugin)
+ val source = driver.connect()
+ val db = Exposed.connect(source)
+
+ init {
+ transaction(db) { SchemaUtils.create(Players) }
+ migrateLegacy()
+ }
+
+ fun getPlayer(uuid: UUID): Player? =
+ transaction(db) {
+ val id = uuid.toString()
+ Players.selectAll().where { Players.uuid eq id }.map { it.toPlayer() }.singleOrNull()
+ }
+
+ fun getPlayer(name: String): Player? =
+ transaction(db) {
+ Players.selectAll().where { Players.name eq name }.map { it.toPlayer() }.singleOrNull()
+ }
+
+ fun getPlayers(page: UInt, pageSize: UInt): List<Player> =
+ transaction(db) {
+ val offset = page * pageSize
+ val wins = Players.hiderWins + Players.seekerWins
+ Players.selectAll()
+ .orderBy(wins to SortOrder.DESC)
+ .limit(pageSize.toInt())
+ .offset(offset.toLong())
+ .map { it.toPlayer() }
+ }
+
+ fun getPlayerNames(limit: UInt, startsWith: String): List<String> =
+ transaction(db) {
+ Players.select(Players.name)
+ .where { Players.name like "$startsWith%" }
+ .orderBy(Players.name to SortOrder.ASC)
+ .limit(limit.toInt())
+ .map { it[Players.name] }
+ .filterNotNull()
+ }
+
+ fun upsertPlayer(player: Player) = transaction(db) { Players.upsert { it.fromPlayer(player) } }
+
+ fun upsertName(u: UUID, n: String) =
+ transaction(db) {
+ Players.upsert {
+ it[uuid] = u.toString()
+ it[name] = n
+ }
+ }
+
+ fun migrateLegacy() =
+ transaction(db) {
+ if (!LegacyPlayers.exists() || !LegacyNames.exists()) return@transaction
+
+ val legacy =
+ LegacyPlayers.join(
+ LegacyNames,
+ JoinType.LEFT,
+ onColumn = LegacyPlayers.uuid,
+ otherColumn = LegacyNames.uuid,
+ )
+ .selectAll()
+ .map { it.toLegacyPlayer() }
+ Players.insertIgnore { legacy.forEach { player -> it.fromPlayer(player) } }
+
+ SchemaUtils.drop(LegacyPlayers)
+ SchemaUtils.drop(LegacyNames)
+ }
+}