Database
The shared SQLite or MySQL connection pool: async queries, transactions and portable SQL.
Docs updated · What changed
On this page
ALBCore.instance.database is one shared connection pool for ALBCore and every child plugin. The same code runs on SQLite and MySQL.
QueriesLink to this section
val db = ALBCore.instance.database
val players = db.table("level_players") // "alb_level_players"
db.update("UPDATE $players SET xp = xp + ? WHERE uuid = ?", 50, uuid) // Future<Int>
db.query("SELECT uuid, level FROM $players ORDER BY level DESC LIMIT 10") { rs ->
rs.getUuid("uuid") to rs.getInt("level")
} // Future<List<Pair>>
db.queryFirst("SELECT level FROM $players WHERE uuid = ?", uuid) { it.getInt(1) } // Future<Int?>
db.batch("INSERT INTO $players (uuid, level) VALUES (?, ?)", rows) // one transaction
db.insertAndGetKey("INSERT INTO ${db.table("logs")} (message) VALUES (?)", text) // Future<Long?>
db.transaction { conn -> // commit on return, rollback on throw
conn.update("UPDATE $players SET coins = coins - ? WHERE uuid = ?", price, buyer)
conn.update("UPDATE $players SET coins = coins + ? WHERE uuid = ?", price, seller)
}- Parameters are bound to
?in order. AUUIDis stored as its 36-character string, an enum as its name,nullas SQL NULL. - Inside
withConnection,transactionand migrations, use the blocking helpers onConnection:update,query,queryFirst,batch,insertAndGetKey,execute,inTransaction. OnResultSetthere aregetUuid,getIntOrNullandgetLongOrNull. - Failures are logged by ALBCore (with the SQL) and complete the future exceptionally.
- SQLite runs all tasks on one thread, in order. MySQL runs them in parallel: chain dependent steps with
thenComposeor put them in onetransaction.
SQL that works on both backendsLink to this section
| Need | Use |
|---|---|
| Insert or update | db.dialect.upsert(table, listOf("uuid"), listOf("level", "xp")), then bind keys and values in that order |
| Insert, skip duplicates | db.dialect.insertIgnore(table, columns) |
| Auto-increment id | id ${dialect.autoIncrementPrimaryKey} |
| Big text / binary | dialect.longTextType, dialect.blobType |
| Player id | uuid CHAR(36) |
| Timestamps | BIGINT epoch milliseconds |