Quarkus - Reactive SQL Clients

The Reactive SQL Clients have a straightforward API focusing on scalability and low-overhead.Currently, the following database servers are supported:

  • PostgreSQL

  • MySQL

In this guide, you will learn how to implement a simple CRUD application exposing data stored in PostgreSQL over a RESTful API.

Extension and connection pool class names for each client can be found at the bottom of this document.
If you are not familiar with the Quarkus Vert.x extension, consider reading the Using Eclipse Vert.x guide first.

The application shall manage fruit entities:

  1. public class Fruit {
  2. public Long id;
  3. public String name;
  4. public Fruit() {
  5. }
  6. public Fruit(String name) {
  7. this.name = name;
  8. }
  9. public Fruit(Long id, String name) {
  10. this.id = id;
  11. this.name = name;
  12. }
  13. }
Do you need a ready-to-use PostgreSQL server to try out the examples?
  1. docker run ulimit memlock=-1:-1 -it rm=true memory-swappiness=0 name quarkus_test -e POSTGRES_USER=quarkus_test -e POSTGRES_PASSWORD=quarkus_test -e POSTGRES_DB=quarkus_test -p 5432:5432 postgres:10.5

Installing

Reactive PostgreSQL Client extension

First, make sure your project has the quarkus-reactive-pg-client extension enabled.If you are creating a new project, set the extensions parameter as follows:

  1. mvn io.quarkus:quarkus-maven-plugin:1.0.0.CR1:create \
  2. -DprojectGroupId=org.acme \
  3. -DprojectArtifactId=reactive-pg-client-quickstart \
  4. -Dextensions="reactive-pg-client"
  5. cd reactive-pg-client-quickstart

If you have an already created project, the reactive-pg-client extension can be added to an existing Quarkus project with the add-extension command:

  1. ./mvnw quarkus:add-extension -Dextensions="reactive-pg-client"

Otherwise, you can manually add this to the dependencies section of your pom.xml file:

  1. <dependency>
  2. <groupId>io.quarkus</groupId>
  3. <artifactId>quarkus-reactive-pg-client</artifactId>
  4. </dependency>
In this guide, we will use the Axle API of the Reactive PostgreSQL Client.Read the Using Eclipse Vert.x guide to understand the differences between the callback, RxJava and Axle based APIs.

JSON Binding

We will expose Fruit instances over HTTP in the JSON format.Consequently, you also need to add the quarkus-resteasy-jsonb extension:

  1. ./mvnw quarkus:add-extension -Dextensions="resteasy-jsonb"

If you prefer not to use the command line, manually add this to the dependencies section of your pom.xml file:

  1. <dependency>
  2. <groupId>io.quarkus</groupId>
  3. <artifactId>quarkus-resteasy-jsonb</artifactId>
  4. </dependency>

Of course, this is only a requirement for this guide, not any application using the Reactive PostgreSQL Client.

Configuring

The Reactive PostgreSQL Client can be configured with standard Quarkus datasource properties:

src/main/resources/application.properties

  1. quarkus.datasource.url=vertx-reactive:postgresql://localhost:5432/quarkus_test
  2. quarkus.datasource.username=quarkus_test
  3. quarkus.datasource.password=quarkus_test
The eagle eyes among you might have noticed the url prefix is different from usual JDBC urls.It is required to use the vertx-reactive: prefix otherwise the Reactive PostgreSQL Client extension will not use the quarkus.datasource.url config property.

With that you may create your FruitResource skeleton and @Inject a io.vertx.axle.pgclient.PgPool instance:

src/main/java/org/acme/vertx/FruitResource.java

  1. @Path("fruits")
  2. @Produces(MediaType.APPLICATION_JSON)
  3. @Consumes(MediaType.APPLICATION_JSON)
  4. public class FruitResource {
  5. @Inject
  6. io.vertx.axle.pgclient.PgPool client;
  7. }

Database schema and seed data

Before we implement the REST endpoint and data management code, we need to setup the database schema.It would also be convenient to have some data inserted upfront.

For production we would recommend to use something like the Flyway database migration tool.But for development we can simply drop and create the tables on startup, and then insert a few fruits.

src/main/java/org/acme/vertx/FruitResource.java

  1. @Inject
  2. @ConfigProperty(name = "myapp.schema.create", defaultValue = "true") (1)
  3. boolean schemaCreate;
  4. @PostConstruct
  5. void config() {
  6. if (schemaCreate) {
  7. initdb();
  8. }
  9. }
  10. private void initdb() {
  11. // TODO
  12. }
  13. }
You may override the default value of the myapp.schema.create property in the application.properties file.

Almost ready!To initialize the DB in development mode, we will use the client simple query method.It returns a CompletionStage and thus can be composed to execute queries sequentially:

  1. client.query("DROP TABLE IF EXISTS fruits")
  2. .thenCompose(r -> client.query("CREATE TABLE fruits (id SERIAL PRIMARY KEY, name TEXT NOT NULL)"))
  3. .thenCompose(r -> client.query("INSERT INTO fruits (name) VALUES ('Orange')"))
  4. .thenCompose(r -> client.query("INSERT INTO fruits (name) VALUES ('Pear')"))
  5. .thenCompose(r -> client.query("INSERT INTO fruits (name) VALUES ('Apple')"))
  6. .toCompletableFuture()
  7. .join();
Wondering why we need to convert the result to CompletableFuture and block until the latest query is completed?This code is part of a @PostConstruct method and Quarkus invokes it synchronously.As a consequence, returning prematurely could lead to serving requests while the database is not ready yet.

That’s it!So far we have seen how to configure a pooled client and execute simple queries.We are now ready to develop the data management code and implement our RESTful endpoint.

Using

Query results traversal

In development mode, the database is set up with a few rows in the fruits table.To retrieve all the data, we will use the query method again:

  1. CompletionStage<RowSet> rowSet = client.query("SELECT id, name FROM fruits ORDER BY name ASC");

When the operation completes, we will get a RowSet that has all the rows buffered in memory.As an java.lang.Iterable<Row>, it can be traversed with a for-each loop:

  1. CompletionStage<List<Fruit>> fruits = rowSet.thenApply(pgRowSet -> {
  2. List<Fruit> list = new ArrayList<>(pgRowSet.size());
  3. for (Row row : pgRowSet) {
  4. list.add(from(row));
  5. }
  6. return list;
  7. });

The from method converts a Row instance to a Fruit instance.It is extracted as a convenience for the implementation of the other data management methods:

src/main/java/org/acme/vertx/Fruit.java

  1. private static Fruit from(Row row) {
  2. return new Fruit(row.getLong("id"), row.getString("name"));
  3. }

Putting it all together, the Fruit.findAll method looks like:

src/main/java/org/acme/vertx/Fruit.java

  1. public static CompletionStage<List<Fruit>> findAll(PgPool client) {
  2. return client.query("SELECT id, name FROM fruits ORDER BY name ASC").thenApply(pgRowSet -> {
  3. List<Fruit> list = new ArrayList<>(pgRowSet.size());
  4. for (Row row : pgRowSet) {
  5. list.add(from(row));
  6. }
  7. return list;
  8. });
  9. }

And the endpoint to get all fruits from the backend:

src/main/java/org/acme/vertx/FruitResource.java

  1. @GET
  2. public CompletionStage<Response> get() {
  3. return Fruit.findAll(client)
  4. .thenApply(Response::ok)
  5. .thenApply(ResponseBuilder::build);
  6. }

Now start Quarkus in dev mode with:

  1. ./mvnw compile quarkus:dev

Lastly, open your browser and navigate to http://localhost:8080/fruits, you should see:

  1. [{"id":3,"name":"Apple"},{"id":1,"name":"Orange"},{"id":2,"name":"Pear"}]

Prepared queries

The Reactive PostgreSQL Client can also prepare queries and take parameters that are replaced in the SQL statement at execution time:

  1. client.preparedQuery("SELECT name FROM fruits WHERE id = $1", Tuple.of(id))
The SQL string can refer to parameters by position, using $1, $2, …​etc.

Like the simple query method, preparedQuery returns an instance of CompletionStage<RowSet>.Equipped with this tooling, we are able to safely use an id provided by the user to get the details of a particular fruit:

src/main/java/org/acme/vertx/Fruit.java

  1. public static CompletionStage<Fruit> findById(PgPool client, Long id) {
  2. return client.preparedQuery("SELECT id, name FROM fruits WHERE id = $1", Tuple.of(id)) (1)
  3. .thenApply(RowSet::iterator) (2)
  4. .thenApply(iterator -> iterator.hasNext() ? from(iterator.next()) : null); (3)
  5. }
1Create a Tuple to hold the prepared query parameters.
2Get an Iterator for the RowSet result.
3Create a Fruit instance from the Row if an entity was found.

And in the JAX-RS resource:

src/main/java/org/acme/vertx/FruitResource.java

  1. @GET
  2. @Path("{id}")
  3. public CompletionStage<Response> getSingle(@PathParam Long id) {
  4. return Fruit.findById(client, id)
  5. .thenApply(fruit -> fruit != null ? Response.ok(fruit) : Response.status(Status.NOT_FOUND)) (1)
  6. .thenApply(ResponseBuilder::build); (2)
  7. }
1Prepare a JAX-RS response with either the Fruit instance if found or the 404 status code.
2Build and send the response.

The same logic applies when saving a Fruit:

src/main/java/org/acme/vertx/Fruit.java

  1. public CompletionStage<Long> save(PgPool client) {
  2. return client.preparedQuery("INSERT INTO fruits (name) VALUES ($1) RETURNING (id)", Tuple.of(name))
  3. .thenApply(pgRowSet -> pgRowSet.iterator().next().getLong("id"));
  4. }

And in the web resource we handle the POST request:

src/main/java/org/acme/vertx/FruitResource.java

  1. @POST
  2. public CompletionStage<Response> create(Fruit fruit) {
  3. return fruit.save(client)
  4. .thenApply(id -> URI.create("/fruits/" + id))
  5. .thenApply(uri -> Response.created(uri).build());
  6. }

Result metadata

A RowSet does not only hold your data in memory, it also gives you some information about the data itself, such as:

  • the number of rows affected by the query (inserted/deleted/updated/retrieved depending on the query type),

  • the column names.

Let’s use this to support removal of fruits in the database:

src/main/java/org/acme/vertx/Fruit.java

  1. public static CompletionStage<Boolean> delete(PgPool client, Long id) {
  2. return client.preparedQuery("DELETE FROM fruits WHERE id = $1", Tuple.of(id))
  3. .thenApply(pgRowSet -> pgRowSet.rowCount() == 1); (1)
  4. }
1Inspect metadata to determine if a fruit has been actually deleted.

And to handle the HTTP DELETE method in the web resource:

src/main/java/org/acme/vertx/FruitResource.java

  1. @DELETE
  2. @Path("{id}")
  3. public CompletionStage<Response> delete(@PathParam Long id) {
  4. return Fruit.delete(client, id)
  5. .thenApply(deleted -> deleted ? Status.NO_CONTENT : Status.NOT_FOUND)
  6. .thenApply(status -> Response.status(status).build());
  7. }

With GET, POST and DELETE methods implemented, we may now create a minimal web page to try the RESTful application out.We will use jQuery to simplify interactions with the backend:

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8"/>
  5. <title>Reactive PostgreSQL Client - Quarkus</title>
  6. <script src="https://code.jquery.com/jquery-3.3.1.min.js"
  7. integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
  8. <script type="application/javascript" src="fruits.js"></script>
  9. </head>
  10. <body>
  11. <h1>Fruits API Testing</h1>
  12. <h2>All fruits</h2>
  13. <div id="all-fruits"></div>
  14. <h2>Create Fruit</h2>
  15. <input id="fruit-name" type="text">
  16. <button id="create-fruit-button" type="button">Create</button>
  17. <div id="create-fruit"></div>
  18. </body>
  19. </html>

In the Javascript code, we need a function to refresh the list of fruits when:

  • the page is loaded, or

  • a fruit is added, or

  • a fruit is deleted.

  1. function refresh() {
  2. $.get('/fruits', function (fruits) {
  3. var list = '';
  4. (fruits || []).forEach(function (fruit) { (1)
  5. list = list
  6. + '<tr>'
  7. + '<td>' + fruit.id + '</td>'
  8. + '<td>' + fruit.name + '</td>'
  9. + '<td><a href="#" onclick="deleteFruit(' + fruit.id + ')">Delete</a></td>'
  10. + '</tr>'
  11. });
  12. if (list.length > 0) {
  13. list = ''
  14. + '<table><thead><th>Id</th><th>Name</th><th></th></thead>'
  15. + list
  16. + '</table>';
  17. } else {
  18. list = "No fruits in database"
  19. }
  20. $('#all-fruits').html(list);
  21. });
  22. }
  23. function deleteFruit(id) {
  24. $.ajax('/fruits/' + id, {method: 'DELETE'}).then(refresh);
  25. }
  26. $(document).ready(function () {
  27. $('#create-fruit-button').click(function () {
  28. var fruitName = $('#fruit-name').val();
  29. $.post({
  30. url: '/fruits',
  31. contentType: 'application/json',
  32. data: JSON.stringify({name: fruitName})
  33. }).then(refresh);
  34. });
  35. refresh();
  36. });
1The fruits parameter is not defined when the database is empty.

All done!Navigate to http://localhost:8080/fruits.html and read/create/delete some fruits.

Database Clients details

DatabaseExtension namePool class name
PostgreSQLquarkus-reactive-pg-clientio.vertx.axle.pgclient.PgPool
MySQLquarkus-reactive-mysql-clientio.vertx.axle.mysqlclient.MySQLPool

Configuration Reference

MySQL

Configuration property fixed at build time - ️ Configuration property overridable at runtime

Configuration propertyTypeDefault
quarkus.datasource.urlThe datasource URL.string
quarkus.datasource.usernameThe datasource username.string
quarkus.datasource.passwordThe datasource password.string
quarkus.datasource.max-sizeThe datasource pool maximum size.int
quarkus.reactive-mysql-client.cache-prepared-statementsWhether prepared statements should be cached on the client side.boolean
quarkus.reactive-mysql-client.charsetCharset for connections.string
quarkus.reactive-mysql-client.collationCollation for connections.string

PostgreSQL

Configuration property fixed at build time - ️ Configuration property overridable at runtime

Configuration propertyTypeDefault
quarkus.reactive-pg-client.cache-prepared-statementsWhether prepared statements should be cached on the client side.boolean
quarkus.reactive-pg-client.pipelining-limitThe maximum number of inflight database commands that can be pipelined.int
quarkus.datasource.urlThe datasource URL.string
quarkus.datasource.usernameThe datasource username.string
quarkus.datasource.passwordThe datasource password.string
quarkus.datasource.max-sizeThe datasource pool maximum size.int