Skip to content

Commit

Permalink
Hardening of current transaction state
Browse files Browse the repository at this point in the history
  • Loading branch information
Sanne committed Mar 14, 2023
1 parent be61ce8 commit 7d563bb
Showing 1 changed file with 17 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -288,8 +288,12 @@ private SqlClient client() {

@Override
public CompletionStage<Void> beginTransaction() {
if ( transaction != null ) {
throw new IllegalStateException( "Can't begin a new transaction as an active transaction is already associated to this connection" );
}
return connection.begin()
.onSuccess( tx -> LOG.tracef( "Transaction started: %s", tx ) )
.onFailure( v -> LOG.errorf( "Failed to start a transaction: %s", transaction ) )
.toCompletionStage()
.thenAccept( tx -> transaction = tx );
}
Expand All @@ -298,22 +302,28 @@ public CompletionStage<Void> beginTransaction() {
public CompletionStage<Void> commitTransaction() {
return transaction.commit()
.onSuccess( v -> LOG.tracef( "Transaction committed: %s", transaction ) )
.onFailure( v -> LOG.errorf( "Failed to commit transaction: %s", transaction ) )
.toCompletionStage()
.whenComplete( (v, x) -> transaction = null );
.whenComplete( this::afterTransactionEnd );
}

@Override
public CompletionStage<Void> rollbackTransaction() {
return transaction.rollback()
.onFailure( v -> LOG.errorf( "Failed to rollback transaction: %s", transaction ) )
.onSuccess( v -> LOG.tracef( "Transaction rolled back: %s", transaction ) )
.toCompletionStage()
.whenComplete( (v, x) -> transaction = null );
.whenComplete( this::afterTransactionEnd );
}

@Override
public CompletionStage<Void> close() {
if ( transaction != null ) {
throw new IllegalStateException( "Connection being closed with a live transaction associated to it" );
}
return connection.close()
.onSuccess( event -> LOG.tracef( "Connection closed: %s", connection ) )
.onFailure( v -> LOG.errorf( "Failed to close a connection: %s", connection ) )
.toCompletionStage();
}

Expand All @@ -333,6 +343,11 @@ private static <T> T getLastInsertedId(RowSet<Row> rows, Class<T> idClass, Strin
return null;
}

private void afterTransactionEnd(Void v, Throwable x) {
LOG.tracef( "Clearing current transaction instance from connection: %s", transaction );
transaction = null;
}

private static class RowSetResult implements Result {
private final RowSet<Row> rowset;
private final RowIterator<Row> it;
Expand Down

0 comments on commit 7d563bb

Please sign in to comment.