Nitin Mukesh Tiwari
Nitin Mukesh Tiwari

Reputation: 81

Is it safe to use Jetbrains exposed library with Ktor and perform the database transaction inside a coroutine?

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.

Upvotes: 5

Views: 4657

Answers (1)

Tapac
Tapac

Reputation: 2337

There is support for coroutines in the latest version of Exposed.

Please look at documentation, but as coroutines support in Exposed is still in experimental mode documentation could differ a bit from code.

Upvotes: 8

Related Questions