From fe62464f544c2647e5d892b1149f474640a7c8a6 Mon Sep 17 00:00:00 2001 From: Sharang Gupta Date: Thu, 12 Nov 2026 16:39:43 +0000 Subject: [PATCH] Return the connection when withConnection throws (#1767) A function that threw instead of returning a failed future left the connection borrowed for good, unlike withTransaction. Assisted-by: Anthropic Claude (claude-opus-5-5) Signed-off-by: Sharang Gupta (cherry picked from commit 50aaa8ac4a20be000014f66fc94f883bd1c5fbac) Signed-off-by: Thomas Segismont --- .../io/vertx/pgclient/PgPoolTestBase.java | 21 +++++++++++++++++++ .../main/java/io/vertx/sqlclient/Pool.java | 10 ++++++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/vertx-pg-client/src/test/java/io/vertx/pgclient/PgPoolTestBase.java b/vertx-pg-client/src/test/java/io/vertx/pgclient/PgPoolTestBase.java index 9fdd2d820f..032170a881 100644 --- a/vertx-pg-client/src/test/java/io/vertx/pgclient/PgPoolTestBase.java +++ b/vertx-pg-client/src/test/java/io/vertx/pgclient/PgPoolTestBase.java @@ -26,6 +26,7 @@ import org.junit.Before; import org.junit.Test; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; @@ -210,4 +211,24 @@ public void testWithConnection(TestContext ctx) { } } } + + @Test + public void testWithConnectionFunctionThrows(TestContext ctx) { + Pool pool = createPool(options, new PoolOptions() + .setMaxSize(1) + .setConnectionTimeout(2) + .setConnectionTimeoutUnit(TimeUnit.SECONDS)); + RuntimeException failure = new RuntimeException("The function fails"); + pool + .withConnection(conn -> { + throw failure; + }) + .onComplete(ctx.asyncAssertFailure(err -> { + ctx.assertEquals(failure, err); + // The only connection of the pool must have been returned + pool + .withConnection(conn -> conn.query("SELECT 1").execute()) + .onComplete(ctx.asyncAssertSuccess()); + })); + } } diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/Pool.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/Pool.java index dffaf3df58..39f9f99570 100644 --- a/vertx-sql-client/src/main/java/io/vertx/sqlclient/Pool.java +++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/Pool.java @@ -224,7 +224,15 @@ default void withConnection(Function> fun * Like {@link #withConnection(Function, Handler)} but returns a {@code Future} of the asynchronous result */ default Future<@Nullable T> withConnection(Function> function) { - return getConnection().flatMap(conn -> function.apply(conn).onComplete(ar -> conn.close())); + return getConnection().flatMap(conn -> { + Future<@Nullable T> result; + try { + result = function.apply(conn); + } catch (Throwable t) { + result = Future.failedFuture(t); + } + return result.onComplete(ar -> conn.close()); + }); } /**