Async database access with MySQL, Kotlin and jasync-sql

osha1
Outbrain Engineering
3 min readSep 4, 2018

As an ode to the conversion of mauricio/postgresql-async to jasync-sql, I also converted this blog post to nowadays. Please do not take that too seriously ;-)

Last year I felt I wanted to contribute in some way to the S̸c̸a̸l̸a̸ Kotlin community. Since I didn’t think I was smart enough to work on the main libraries or compiler, I started to look for something that I could build and would benefit me and the community in general. I started looking around and noticed that there weren’t async drivers for the good old relational databases. If you’re fancy and you’re using one of the new NoSQL ones, you are most likely covered, but if you still rely on databases like P̸o̸s̸t̸g̸r̸e̸S̸Q̸L̸ MySQL (like I do at my daily job), you have to rely on the official (and blocking) P̸o̸s̸t̸g̸r̸e̸S̸Q̸L̸ MySQL JDBC driver and so the p̸o̸s̸t̸g̸r̸e̸s̸q̸l̸-̸a̸s̸y̸n̸c̸ ̸p̸r̸o̸j̸e̸c̸t̸ jasync-sql was born.

I started looking at what people did in the NodeJS community like node-postgres and I noticed you don’t really need the full JDBC implementation for a usable database driver, as long as you can execute statements and get something back, you probably have all you need so this was the goal. Build something that would allow you to execute queries and get results back.

Connecting to the database

Let’s see some sample usage:

The basic usage pattern is quite simple, you ask for something, you get a CompletableFuture<*> back. In this case, I’m simplifying the code by blocking to get the results, but if you’re using an async framework (like A̸k̸k̸a̸ ̸o̸r̸ ̸P̸l̸a̸y̸ RxJava or kotlinx-coroutines) you can just compose on these futures to do your work.

The MySQLConnection is a real connection to the database, it implements the Connection interface and you should try to use the interface as much as possible. When you create a connection handler, it’s not connected to the database yet, you have to connect it yourself calling connect() and waiting for the future to return or composing on the future to do something else.

When you execute a statement, you get back a QueryResult object that might or might not contain a ResultSet. That depends on the kind of statement you executed, if the statement you asked for returns rows, there will be a ResultSet available for you, if it does not then you will have a null in there.

That is it for now.

The rest of the original post is talking about higher level integration. Might tackle that in a separate blog post.

And, Yes there is a script to convert blog posts as well :-)

As always, comments are welcome, and don’t forget to star ⭐: https://github.com/jasync-sql/jasync-sql/

“flat lay photography of eight coffee latte in mugs on round table” by Nathan Dumlao on Unsplash

--

--