Skip to content

Commit

Permalink
Issue helidon-io#7187 - Fix examples to handle transactions in try/ca…
Browse files Browse the repository at this point in the history
…tch blocks, so the transaction is always either committed or rolled-back

Signed-off-by: Tomáš Kraus <tomas.kraus@oracle.com>
  • Loading branch information
Tomas-Kraus committed Jul 21, 2023
1 parent fb7585c commit 24475c2
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -159,15 +159,20 @@ private void updatePokemonType(ServerRequest req, ServerResponse res) {
private void transactional(ServerRequest req, ServerResponse res) {
Pokemon pokemon = req.content().as(Pokemon.class);
DbTransaction tx = dbClient.transaction();
long count = tx.createNamedGet("select-for-update")
.namedParam(pokemon)
.execute()
.map(dbRow -> tx.createNamedUpdate("update")
.namedParam(pokemon)
.execute())
.orElse(0L);
tx.commit();
res.send("Updated " + count + " records");
try {
long count = tx.createNamedGet("select-for-update")
.namedParam(pokemon)
.execute()
.map(dbRow -> tx.createNamedUpdate("update")
.namedParam(pokemon)
.execute())
.orElse(0L);
tx.commit();
res.send("Updated " + count + " records");
} catch (Throwable t) {
tx.rollback();
throw t;
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import io.helidon.dbclient.DbClient;
import io.helidon.dbclient.DbExecute;
import io.helidon.dbclient.DbTransaction;

import jakarta.json.Json;
import jakarta.json.JsonArray;
Expand Down Expand Up @@ -82,9 +83,15 @@ private static void initSchema(DbClient dbClient) {
*/
private static void initData(DbClient dbClient) {
// Init Pokémon types
DbExecute exec = dbClient.execute();
initTypes(exec);
initPokemons(exec);
DbTransaction tx = dbClient.transaction();
try {
initTypes(tx);
initPokemons(tx);
tx.commit();
} catch (Throwable t) {
tx.rollback();
throw t;
}
}

/**
Expand All @@ -93,9 +100,15 @@ private static void initData(DbClient dbClient) {
* @param dbClient database client
*/
private static void deleteData(DbClient dbClient) {
DbExecute exec = dbClient.execute();
exec.namedDelete("delete-all-pokemons");
exec.namedDelete("delete-all-types");
DbTransaction tx = dbClient.transaction();
try {
tx.namedDelete("delete-all-pokemons");
tx.namedDelete("delete-all-types");
tx.commit();
} catch (Throwable t) {
tx.rollback();
throw t;
}
}

/**
Expand Down

0 comments on commit 24475c2

Please sign in to comment.