use of io.vertx.ext.sql.SQLClient in project hono by eclipse.
the class SQL method runTransactionally.
/**
* Run operation transactionally.
* <p>
* This function will perform the following operations:
* <ul>
* <li>Open a new connection</li>
* <li>Turn off auto-commit mode</li>
* <li>Call the provided function</li>
* <li>If the provided function failed, perform a <em>Rollback</em> operation</li>
* <li>If the provided function succeeded, perform a <em>Commit</em> operation</li>
* <li>Close the connection</li>
* </ul>
*
* @param client The client to use.
* @param tracer The tracer to use.
* @param function The function to execute while the transaction is open.
* @param context The span to log to.
* @param <T> The type of the result.
* @return A future, tracking the outcome of the operation.
*/
public static <T> Future<T> runTransactionally(final SQLClient client, final Tracer tracer, final SpanContext context, final BiFunction<SQLConnection, SpanContext, Future<T>> function) {
final Span span = startSqlSpan(tracer, context, "run transactionally", builder -> {
});
final Promise<SQLConnection> promise = Promise.promise();
client.getConnection(promise);
return promise.future().onSuccess(x -> {
final Map<String, Object> log = new HashMap<>();
log.put(Fields.EVENT, "success");
log.put(Fields.MESSAGE, "connection opened");
span.log(log);
}).flatMap(connection -> SQL.setAutoCommit(tracer, span.context(), connection, false).flatMap(y -> function.apply(connection, span.context()).compose(v -> SQL.commit(tracer, span.context(), connection).map(v), x -> SQL.rollback(tracer, span.context(), connection).flatMap(unused -> Future.failedFuture(x)))).onComplete(x -> connection.close())).onComplete(x -> span.finish());
}
Aggregations