I am new to Kotlin and recently started working on Ktor server. To perform database operations server needs to communicate with MySql server. I started using JetBrains Exposed library to write database operations.
I wrote a suspended function to execute a block of code(database queries written using Exposed DSL) using transaction. This was followed from a blogpost on the getting started guide for ktor.
suspend fun <T> dbQuery(block: () -> T): T = withContext(Dispatchers.IO) {
transaction { block() }
}
Whenever I need to perform a db query I call
dbQuery {
// my queries
}
Because Exposed uses threadlocal transaction managers as well as blocking JDBC driver, I am wondering if this is safe to do so?
There is no good documentation on how to actually handle mysql connections with coroutines.
Incase this is wrong and will eventually lead to Transaction lock out then any pointer on how to solve this will help.
IO
dispatcher is meant for blocking operations so you should be fine. Note that no functions you call within thewithContext
block should be suspendable. If a function suspends, it may resume in a different thread. – Cardon