From 4541f403de83164efdc84de5b1dd12f7af65275a Mon Sep 17 00:00:00 2001 From: Clement Escoffier Date: Mon, 4 May 2020 17:45:27 +0200 Subject: [PATCH] Add a few words about transactions using the reactive SQL clients --- .../main/asciidoc/reactive-sql-clients.adoc | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/docs/src/main/asciidoc/reactive-sql-clients.adoc b/docs/src/main/asciidoc/reactive-sql-clients.adoc index 6808cdb8b2f13..586674b3a8780 100644 --- a/docs/src/main/asciidoc/reactive-sql-clients.adoc +++ b/docs/src/main/asciidoc/reactive-sql-clients.adoc @@ -488,6 +488,58 @@ Navigate to http://localhost:8080/fruits.html and read/create/delete some fruits |`io.vertx.mutiny.mysqlclient.MySQLPool` |=== +== Transactions + +The reactive SQL clients support transactions. +A transaction is started with `client.begin()` and terminated with either `tx.commit()` or `tx.rollback()`. +All these operations are asynchronous: + +* `client.begin()` returns a `Uni` +* `client.commit()` and `client.rollback()` return `Uni` + +The following snippet shows how to run 2 insertions in the same transaction: + +[source, java] +---- +public static Uni insertTwoFruits(PgPool client, Fruit fruit1, Fruit fruit2) { + return client.begin() + .flatMap(tx -> { + Uni> insertOne = tx.preparedQuery("INSERT INTO fruits (name) VALUES ($1) RETURNING (id)") + .execute(Tuple.of(fruit1.name)); + Uni> insertTwo = tx.preparedQuery("INSERT INTO fruits (name) VALUES ($1) RETURNING (id)") + .execute(Tuple.of(fruit2.name)); + + return insertOne.and(insertTwo) + // Ignore the results (the two ids) + .onItem().ignore().andContinueWithNull() + // on success, commit + .onItem().produceUni(x -> tx.commit()) + // on failure rollback + .onFailure().recoverWithUni(tx::rollback); + }); +} +---- + +In this example, the two insertions are not dependant on each other and are executed concurrently (but in the same transaction). +This transaction is committed on success and rolled back on failure. + +You can also create dependant actions as follows: + +[source, java] +---- +return this.client.begin() + .flatMap(tx -> tx + .preparedQuery("INSERT INTO person (firstname,lastname) VALUES ($1,$2) RETURNING (id)", + Tuple.of(person.getFirstName(),person.getLastName())) + + .onItem().produceUni(id-> tx.preparedQuery("INSERT INTO addr (person_id,addrline1) VALUES ($1,$2)", + Tuple.of(id.iterator().next().getLong("id"),person.getLastName()))) + + .onItem().produceUni(res -> tx.commit()) + .onFailure().recoverWithUni(ex-> tx.rollback()) + ); +---- + == Configuration Reference === Common Datasource