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

1

5

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.

Jerald answered 4/8, 2019 at 20:8 Comment(1)
The IO dispatcher is meant for blocking operations so you should be fine. Note that no functions you call within the withContext block should be suspendable. If a function suspends, it may resume in a different thread.Cardon
S
8

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.

Statutory answered 6/8, 2019 at 20:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.