ALB Studio

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

Kotlin
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. A UUID is stored as its 36-character string, an enum as its name, null as SQL NULL.
  • Inside withConnection, transaction and migrations, use the blocking helpers on Connection: update, query, queryFirst, batch, insertAndGetKey, execute, inTransaction. On ResultSet there are getUuid, getIntOrNull and getLongOrNull.
  • 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 thenCompose or put them in one transaction.

SQL that works on both backendsLink to this section

NeedUse
Insert or updatedb.dialect.upsert(table, listOf("uuid"), listOf("level", "xp")), then bind keys and values in that order
Insert, skip duplicatesdb.dialect.insertIgnore(table, columns)
Auto-increment idid ${dialect.autoIncrementPrimaryKey}
Big text / binarydialect.longTextType, dialect.blobType
Player iduuid CHAR(36)
TimestampsBIGINT epoch milliseconds

Type a class, method, config key or topic. Use the arrow keys and Enter to open a result.