Skip to content

Are the Queries run in coroutines? Or, do I need to call them under a coroutine? #537

Answered by JasonMing
30atm asked this question in Q&A
Discussion options

You must be logged in to vote

AFAIK, ktorm is running in blocking mode(see: org.ktorm.database.Database#executeExpression), the actually query will block the caller's thread.

Which means, ktorm queries should be dispatched to a standalone blocking dispatcher. Especially the operations depend on the transaction, because JdbcTransactionmanager depends on ThreadLocal.

Here is what I do:

private val dbDispatcher = newFixedThreadPoolContext(30, "ktorm-db")

suspend fun <R> db(block: suspend Database.() -> R): R =
    withContext(dbDispatcher) {
        block(db)
    }

So you can simply call db { ... } in any suspend function without worrying about blocking the non-blocking coroutine dispatchers.

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by 30atm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants