https://kotlinlang.org logo
#ktor
Title
# ktor
m

Matej Drobnič

06/18/2020, 3:47 AM
Considering pretty much all database ORMs are blocking, what is the recommended pattern for accessing database from ktor? Do we have to wrap everything in
withContext(<http://Dispatchers.IO|Dispatchers.IO>)
? That would look pretty messy.
🙄 1
m

Matej Drobnič

06/18/2020, 6:53 AM
I know about that, I was just wondering if there is a cleaner solution out there rather than wrapping every single database call into withContext
r

Robert Jaros

06/18/2020, 6:54 AM
R2DBC is non blocking.
m

Matej Drobnič

06/18/2020, 6:54 AM
but it is not ORM, it only executes raw SQL calls
r

Robert Jaros

06/18/2020, 6:55 AM
yes, but still it's a good alternative to consider
r

Roger Home-Martinsen

06/18/2020, 6:56 AM
OK, I do not think it is messy at all. It think it is just very clear. If you are utilizing the functions you know that these are “main-safe”.
👍 1
m

Matej Drobnič

06/18/2020, 7:13 AM
well, it is very explicit. Considering database calls are big chunk of backend code, it adds a lot of cruft to the code.
Copy code
val user  = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
    database.getUser()
}

// doSomething with the user

withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
    database.saveUser(updatedUser)
}
Best thing I can see is creating my own proxy database layer that wraps all database calls into nice suspending calls. But that would make adding new database calls more complicated since call would have to be added to the proxy layer first.
r

Roger Home-Martinsen

06/18/2020, 7:16 AM
OK, I would add all this into a service with suspend functions and wrapping all functions there.
m

Matej Drobnič

06/18/2020, 7:16 AM
yes, but still it's a good alternative to consider
I'm not sure how it can be an alternative. ORM and database connector are two completely different things.
yeah that was my idea. Just wanted to pick some brains to see if I was missing anything.
thanks
👍 1
t

thanksforallthefish

06/18/2020, 7:20 AM
https://spring.io/projects/spring-data-r2dbc ? still, afaik you have to write your sql, so not a full-fledge orm, but it simplifies the mapping
r

Robert Jaros

06/18/2020, 8:23 AM
@Matej Drobnič r2dbc with spring data libraries and coroutines extensions is definitely more than a database connector :-)
2 Views