This is an automated email from the ASF dual-hosted git repository.

garydgregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-dbcp.git


The following commit(s) were added to refs/heads/master by this push:
     new b7f6ec70 [DBCP-600] Honor positive sub-second validation timeouts
b7f6ec70 is described below

commit b7f6ec70f66516330e1a509b623c9a1064e66a86
Author: Gary Gregory <[email protected]>
AuthorDate: Sun Nov 22 14:01:16 2026 -0500

    [DBCP-600] Honor positive sub-second validation timeouts
    
    Convert positive sub-second durations to one JDBC second in both
    validation-query and Connection.isValid paths. Cap oversized durations
    at Integer.MAX_VALUE seconds to prevent integer overflow.
    
    Document fractional-second conversion and retained cached-statement
    timeouts for nonpositive durations. Add regression coverage for timeout
    boundaries, statement reuse, validation failures, and fast-fail
    settings.
---
 src/changes/changes.xml                            |   1 +
 .../apache/commons/dbcp2/PoolableConnection.java   |  46 ++--
 .../apache/commons/dbcp2/TestBasicDataSource.java  |  11 +-
 .../commons/dbcp2/TestPoolableConnection.java      | 279 ++++++++++++++++++++-
 4 files changed, 318 insertions(+), 19 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 04b2606b..b6542149 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -77,6 +77,7 @@ The <action> type attribute can be add,update,fix,remove.
       <action type="fix" dev="ggregory" due-to="Gary Gregory">Omit unknown and 
obsolete JNDI property values from BasicDataSourceFactory diagnostics to avoid 
logging credentials supplied under incorrect property names (f008).</action>
       <action type="fix" dev="ggregory" due-to="Bill Mitchell, Tiefang Hu, 
Gary Gregory" issue="DBCP-522">Prevent stale cached auto-commit state after 
unchecked failures in DelegatingConnection.setAutoCommit(), preserving rollback 
and auto-commit restoration when pooled connections are returned #549.</action>
       <action type="fix" dev="ggregory" due-to="Gary Gregory">Invalidate 
cached read-only, catalog, and schema state before driver calls in 
DelegatingConnection so unchecked failures do not leave stale values or prevent 
pooled connection state restoration.</action>
+      <action type="fix" dev="ggregory" due-to="Aryan Ganjoo, Gary Gregory" 
issue="DBCP-600">Honor positive sub-second validation timeouts as one JDBC 
second in both validation paths, and cap oversized durations to prevent integer 
overflow #548.</action>
       <!-- ADD -->
       <action type="add" dev="ggregory" due-to="Gary Gregory">Add 
DriverAdapterCPDS.exportPasswordAsRefAddr to optionally omit the password 
address from JNDI References. Password export remains enabled by default for 
compatibility; the setting survives JNDI lookup and Java serialization.</action>
       <action type="add" dev="ggregory" due-to="Gary Gregory">Add 
PoolingDriver.Builder and PoolingDriver.builder() to configure delegate access 
when creating drivers, preserving the existing permissive default.</action>
diff --git a/src/main/java/org/apache/commons/dbcp2/PoolableConnection.java 
b/src/main/java/org/apache/commons/dbcp2/PoolableConnection.java
index 4d39b5ea..469e6a59 100644
--- a/src/main/java/org/apache/commons/dbcp2/PoolableConnection.java
+++ b/src/main/java/org/apache/commons/dbcp2/PoolableConnection.java
@@ -385,30 +385,40 @@ public class PoolableConnection extends 
DelegatingConnection<Connection> impleme
      * <ol>
      * <li>If {@code fastFailValidation} (constructor argument) is {@code 
true} and this connection has previously
      * thrown a fatal disconnection exception, a {@link SQLException} is 
thrown.</li>
-     * <li>If {@code sql} is null, the driver's #{@link 
Connection#isValid(int) isValid(timeout)} is called. If it
+     * <li>If {@code sql} is null or empty, the driver's {@link 
Connection#isValid(int) isValid(timeout)} is called. If it
      * returns {@code false}, {@link SQLException} is thrown; otherwise, this 
method returns successfully.</li>
-     * <li>If {@code sql} is not null, it is executed as a query and if the 
resulting {@link ResultSet} contains at
+     * <li>Otherwise, {@code sql} is executed as a query and if the resulting 
{@link ResultSet} contains at
      * least one row, this method returns successfully. If not, {@link 
SQLException} is thrown.</li>
      * </ol>
      *
+     * <p>
+     * Positive timeouts are converted to whole seconds, discarding any 
fractional second, with a minimum of one second and a maximum of
+     * {@link Integer#MAX_VALUE} seconds. For example, 100 milliseconds and 
1.9 seconds both become one second.
+     * </p>
+     *
+     * <p>
+     * A zero or negative timeout passes zero (no timeout) to {@link 
Connection#isValid(int)}. When executing a validation query, a zero or negative 
timeout
+     * leaves the statement's timeout unchanged. The validation statement is 
cached for reuse with the same SQL, so any previously applied timeout is 
retained.
+     * </p>
+     *
      * @param sql
-     *            The validation SQL query.
+     *            The validation SQL query, or null or empty to use {@link 
Connection#isValid(int)}.
      * @param timeoutDuration
-     *            The validation timeout in seconds.
+     *            The validation timeout, converted to whole seconds as 
described above.
      * @throws SQLException
-     *             Thrown when validation fails or an SQLException occurs 
during validation
+     *             Thrown when validation fails or an SQLException occurs 
during validation.
      * @since 2.10.0
      */
-    public void validate(final String sql, Duration timeoutDuration) throws 
SQLException {
+    public void validate(final String sql, final Duration timeoutDuration) 
throws SQLException {
         if (fastFailValidation && fatalSqlExceptionThrown.get()) {
             throw new 
SQLException(Utils.getMessage("poolableConnection.validate.fastFail"));
         }
 
+        // JDBC timeouts are whole seconds where 0 means no timeout, so a 
positive sub-second timeout becomes 1 second.
+        final int timeoutSeconds = timeoutDuration.isNegative() || 
timeoutDuration.isZero() ? 0
+                : (int) Math.max(1, Math.min(Integer.MAX_VALUE, 
timeoutDuration.getSeconds()));
         if (sql == null || sql.isEmpty()) {
-            if (timeoutDuration.isNegative()) {
-                timeoutDuration = Duration.ZERO;
-            }
-            if (!isValid(timeoutDuration)) {
+            if (!isValid(Duration.ofSeconds(timeoutSeconds))) {
                 throw new SQLException("isValid() returned false");
             }
             return;
@@ -421,8 +431,8 @@ public class PoolableConnection extends 
DelegatingConnection<Connection> impleme
             validationPreparedStatement = 
getInnermostDelegateInternal().prepareStatement(sql);
         }
 
-        if (timeoutDuration.compareTo(Duration.ZERO) > 0) {
-            validationPreparedStatement.setQueryTimeout((int) 
timeoutDuration.getSeconds());
+        if (timeoutSeconds > 0) {
+            validationPreparedStatement.setQueryTimeout(timeoutSeconds);
         }
 
         try (ResultSet rs = validationPreparedStatement.executeQuery()) {
@@ -439,18 +449,22 @@ public class PoolableConnection extends 
DelegatingConnection<Connection> impleme
      * <ol>
      * <li>If {@code fastFailValidation} (constructor argument) is {@code 
true} and this connection has previously
      * thrown a fatal disconnection exception, a {@link SQLException} is 
thrown.</li>
-     * <li>If {@code sql} is null, the driver's #{@link 
Connection#isValid(int) isValid(timeout)} is called. If it
+     * <li>If {@code sql} is null or empty, the driver's {@link 
Connection#isValid(int) isValid(timeout)} is called. If it
      * returns {@code false}, {@link SQLException} is thrown; otherwise, this 
method returns successfully.</li>
-     * <li>If {@code sql} is not null, it is executed as a query and if the 
resulting {@link ResultSet} contains at
+     * <li>Otherwise, {@code sql} is executed as a query and if the resulting 
{@link ResultSet} contains at
      * least one row, this method returns successfully. If not, {@link 
SQLException} is thrown.</li>
      * </ol>
      *
+     * <p>
+     * Zero and negative timeouts are handled as described in {@link 
#validate(String, Duration)}.
+     * </p>
+     *
      * @param sql
-     *            The validation SQL query.
+     *            The validation SQL query, or null or empty to use {@link 
Connection#isValid(int)}.
      * @param timeoutSeconds
      *            The validation timeout in seconds.
      * @throws SQLException
-     *             Thrown when validation fails or an SQLException occurs 
during validation
+     *             Thrown when validation fails or an SQLException occurs 
during validation.
      * @deprecated Use {@link #validate(String, Duration)}.
      */
     @Deprecated
diff --git a/src/test/java/org/apache/commons/dbcp2/TestBasicDataSource.java 
b/src/test/java/org/apache/commons/dbcp2/TestBasicDataSource.java
index 0f2d9cc0..952c5a5f 100644
--- a/src/test/java/org/apache/commons/dbcp2/TestBasicDataSource.java
+++ b/src/test/java/org/apache/commons/dbcp2/TestBasicDataSource.java
@@ -1156,12 +1156,21 @@ public class TestBasicDataSource extends 
TestConnectionPool {
     void testValidationQueryTimeoutSucceed() throws Exception {
         ds.setTestOnBorrow(true);
         ds.setTestOnReturn(true);
-        ds.setValidationQueryTimeout(Duration.ofMillis(100)); // Works for 
TesterStatement
+        ds.setValidationQueryTimeout(Duration.ofSeconds(5)); // Works for 
TesterStatement
         try (final Connection con = ds.getConnection()) {
             // close right away.
         }
     }
 
+    @Test
+    void testValidationQueryTimeoutSubSecondFail() {
+        ds.setTestOnBorrow(true);
+        // A positive sub-second timeout must not be truncated to 0 (no 
timeout); it becomes 1 second, too fast for TesterStatement.
+        ds.setValidationQueryTimeout(Duration.ofMillis(100));
+        final SQLException e = assertThrows(SQLException.class, 
ds::getConnection);
+        assertTrue(e.toString().contains("timeout"));
+    }
+
     @Test
     void testValidationQueryTimeoutZero() throws Exception {
         ds.setTestOnBorrow(true);
diff --git a/src/test/java/org/apache/commons/dbcp2/TestPoolableConnection.java 
b/src/test/java/org/apache/commons/dbcp2/TestPoolableConnection.java
index 183d2cdc..2f84e520 100644
--- a/src/test/java/org/apache/commons/dbcp2/TestPoolableConnection.java
+++ b/src/test/java/org/apache/commons/dbcp2/TestPoolableConnection.java
@@ -19,13 +19,27 @@ package org.apache.commons.dbcp2;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
 
 import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
 import java.sql.SQLException;
+import java.sql.SQLTimeoutException;
+import java.time.Duration;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.stream.Stream;
 
 import javax.management.OperationsException;
 
@@ -33,6 +47,11 @@ import org.apache.commons.pool2.impl.GenericObjectPool;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.NullAndEmptySource;
+import org.mockito.InOrder;
 
 /**
  */
@@ -40,6 +59,48 @@ public class TestPoolableConnection {
 
     private GenericObjectPool<PoolableConnection> pool;
 
+    private static Stream<Arguments> fastFailValidationArguments() {
+        return Stream.of(false, true).flatMap(fastFail -> Stream.of(null, "", 
"SELECT 1").map(sql -> Arguments.of(fastFail, sql)));
+    }
+
+    private static PreparedStatement mockValidationStatement(final Connection 
nativeConnection) throws SQLException {
+        final PreparedStatement statement = mock(PreparedStatement.class);
+        when(nativeConnection.prepareStatement("SELECT 
1")).thenReturn(statement);
+        when(statement.executeQuery()).thenAnswer(invocation -> {
+            final ResultSet resultSet = mock(ResultSet.class);
+            when(resultSet.next()).thenReturn(true);
+            return resultSet;
+        });
+        return statement;
+    }
+
+    private static Stream<Duration> nonPositiveValidationTimeouts() {
+        return Stream.of(Duration.ofSeconds(Long.MIN_VALUE), 
Duration.ofSeconds(-1), Duration.ofNanos(-1), Duration.ZERO);
+    }
+
+    private static Stream<Arguments> positiveValidationTimeouts() {
+        return Stream.of(
+                Arguments.of(Duration.ofNanos(1), 1),
+                Arguments.of(Duration.ofMillis(100), 1),
+                Arguments.of(Duration.ofMillis(999), 1),
+                Arguments.of(Duration.ofNanos(999_999_999), 1),
+                Arguments.of(Duration.ofSeconds(1), 1),
+                Arguments.of(Duration.ofSeconds(1, 1), 1),
+                Arguments.of(Duration.ofMillis(1900), 1),
+                Arguments.of(Duration.ofSeconds(5), 5),
+                Arguments.of(Duration.ofSeconds(Integer.MAX_VALUE - 1L), 
Integer.MAX_VALUE - 1),
+                Arguments.of(Duration.ofSeconds(Integer.MAX_VALUE), 
Integer.MAX_VALUE),
+                Arguments.of(Duration.ofSeconds(Integer.MAX_VALUE, 
999_999_999), Integer.MAX_VALUE),
+                Arguments.of(Duration.ofSeconds(Integer.MAX_VALUE + 1L), 
Integer.MAX_VALUE),
+                Arguments.of(Duration.ofSeconds(1L << 32), Integer.MAX_VALUE),
+                Arguments.of(Duration.ofSeconds(Long.MAX_VALUE, 999_999_999), 
Integer.MAX_VALUE));
+    }
+
+    private static Stream<Arguments> validationTimeoutsWithoutQuery() {
+        return Stream.concat(positiveValidationTimeouts(), 
nonPositiveValidationTimeouts().map(timeout -> Arguments.of(timeout, 0)))
+                .flatMap(timeout -> Stream.of(null, "").map(sql -> 
Arguments.of(sql, timeout.get()[0], timeout.get()[1])));
+    }
+
     @BeforeEach
     public void setUp() throws Exception {
         final PoolableConnectionFactory factory = new 
PoolableConnectionFactory(
@@ -125,7 +186,7 @@ public class TestPoolableConnection {
         nativeConnection.setFailure(null);
 
         // validate should not fail - error was not fatal and condition was 
cleaned up
-        conn.validate("SELECT 1", 1000);
+        conn.validate("SELECT 1", Duration.ofSeconds(1000));
 
         // now set up fatal failure
         nativeConnection.setFailure(new SQLException("Fatal connection 
error.", "01002"));
@@ -134,7 +195,7 @@ public class TestPoolableConnection {
         nativeConnection.setFailure(null);
 
         // validate should now fail because of previous fatal error, despite 
cleanup
-        assertThrows(SQLException.class, () -> conn.validate("SELECT 1", 
1000), "Should throw SQL exception on validation.");
+        assertThrows(SQLException.class, () -> conn.validate("SELECT 1", 
Duration.ofSeconds(1000)), "Should throw SQL exception on validation.");
 
         // verify that bad connection does not get returned to the pool
         conn.close(); // testOnReturn triggers validate, which should fail
@@ -213,4 +274,218 @@ public class TestPoolableConnection {
 
         assertEquals(0, pool.getNumActive(), "The pool should have no active 
connections");
     }
+
+    @ParameterizedTest(name = "fastFail={0}, sql={1}")
+    @MethodSource("fastFailValidationArguments")
+    void testValidateAfterFatalException(final boolean fastFail, final String 
sql) throws Exception {
+        final Connection nativeConnection = mock(Connection.class);
+        final PreparedStatement statement = 
mockValidationStatement(nativeConnection);
+        final SQLException fatalException = new SQLException("Connection 
lost", "08006");
+        when(nativeConnection.createStatement()).thenThrow(fatalException);
+        when(nativeConnection.isValid(1)).thenReturn(true);
+        final PoolableConnection conn = new 
PoolableConnection(nativeConnection, null, null, null, fastFail);
+        try {
+            assertSame(fatalException, assertThrows(SQLException.class, 
conn::createStatement));
+            if (fastFail) {
+                assertThrows(SQLException.class, () -> conn.validate(sql, 
Duration.ofMillis(100)));
+                verify(nativeConnection, never()).isValid(anyInt());
+                verify(nativeConnection, 
never()).prepareStatement(anyString());
+            } else {
+                conn.validate(sql, Duration.ofMillis(100));
+                if (sql == null || sql.isEmpty()) {
+                    verify(nativeConnection).isValid(1);
+                } else {
+                    verify(statement).setQueryTimeout(1);
+                    verify(statement).executeQuery();
+                }
+            }
+        } finally {
+            conn.reallyClose();
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("nonPositiveValidationTimeouts")
+    void testValidateWithDifferentQueryNonPositiveTimeout(final Duration 
timeout) throws Exception {
+        final Connection nativeConnection = mock(Connection.class);
+        final TesterPreparedStatement firstStatement = new 
TesterPreparedStatement(nativeConnection, "SELECT 1");
+        final TesterPreparedStatement secondStatement = new 
TesterPreparedStatement(nativeConnection, "SELECT 2");
+        final int defaultTimeout = secondStatement.getQueryTimeout();
+        when(nativeConnection.prepareStatement("SELECT 
1")).thenReturn(firstStatement);
+        when(nativeConnection.prepareStatement("SELECT 
2")).thenReturn(secondStatement);
+        final PoolableConnection conn = new 
PoolableConnection(nativeConnection, null, null);
+        try {
+            conn.validate("SELECT 1", Duration.ofSeconds(5));
+            conn.validate("SELECT 2", timeout);
+            assertEquals(5, firstStatement.getQueryTimeout());
+            assertEquals(defaultTimeout, secondStatement.getQueryTimeout());
+            verify(nativeConnection).prepareStatement("SELECT 1");
+            verify(nativeConnection).prepareStatement("SELECT 2");
+        } finally {
+            firstStatement.close();
+            conn.reallyClose();
+        }
+    }
+
+    @ParameterizedTest
+    @NullAndEmptySource
+    void testValidateWithoutQueryInvalidConnection(final String sql) throws 
Exception {
+        final Connection nativeConnection = mock(Connection.class);
+        final PoolableConnection conn = new 
PoolableConnection(nativeConnection, null, null);
+        try {
+            final SQLException exception = assertThrows(SQLException.class, () 
-> conn.validate(sql, Duration.ofMillis(100)));
+            assertEquals("isValid() returned false", exception.getMessage());
+            verify(nativeConnection).isValid(1);
+        } finally {
+            conn.reallyClose();
+        }
+    }
+
+    @ParameterizedTest
+    @NullAndEmptySource
+    void testValidateWithoutQuerySQLException(final String sql) throws 
Exception {
+        final Connection nativeConnection = mock(Connection.class);
+        final SQLException expected = new SQLException("Validation failed", 
"08006");
+        when(nativeConnection.isValid(1)).thenThrow(expected);
+        final PoolableConnection conn = new 
PoolableConnection(nativeConnection, null, null);
+        try {
+            assertSame(expected, assertThrows(SQLException.class, () -> 
conn.validate(sql, Duration.ofMillis(100))));
+            verify(nativeConnection).isValid(1);
+        } finally {
+            conn.reallyClose();
+        }
+    }
+
+    @ParameterizedTest(name = "sql={0}, timeout={1}, seconds={2}")
+    @MethodSource("validationTimeoutsWithoutQuery")
+    void testValidateWithoutQueryTimeout(final String sql, final Duration 
timeout, final int timeoutSeconds) throws Exception {
+        final Connection nativeConnection = mock(Connection.class);
+        when(nativeConnection.isValid(timeoutSeconds)).thenReturn(true);
+        final PoolableConnection conn = new 
PoolableConnection(nativeConnection, null, null);
+        try {
+            conn.validate(sql, timeout);
+            verify(nativeConnection).isValid(timeoutSeconds);
+            verify(nativeConnection, never()).prepareStatement(anyString());
+        } finally {
+            conn.reallyClose();
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("nonPositiveValidationTimeouts")
+    void testValidateWithQueryNonPositiveTimeout(final Duration timeout) 
throws Exception {
+        final Connection nativeConnection = mock(Connection.class);
+        final PreparedStatement statement = 
mockValidationStatement(nativeConnection);
+        final PoolableConnection conn = new 
PoolableConnection(nativeConnection, null, null);
+        try {
+            conn.validate("SELECT 1", timeout);
+            verify(statement, never()).setQueryTimeout(anyInt());
+            verify(statement).executeQuery();
+        } finally {
+            conn.reallyClose();
+        }
+    }
+
+    @Test
+    void testValidateWithQueryNoRows() throws Exception {
+        final Connection nativeConnection = mock(Connection.class);
+        final PreparedStatement statement = 
mockValidationStatement(nativeConnection);
+        final ResultSet resultSet = mock(ResultSet.class);
+        when(statement.executeQuery()).thenReturn(resultSet);
+        final PoolableConnection conn = new 
PoolableConnection(nativeConnection, null, null);
+        try {
+            final SQLException exception = assertThrows(SQLException.class, () 
-> conn.validate("SELECT 1", Duration.ofMillis(100)));
+            assertEquals("validationQuery didn't return a row", 
exception.getMessage());
+            verify(statement).setQueryTimeout(1);
+            verify(resultSet).close();
+        } finally {
+            conn.reallyClose();
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("positiveValidationTimeouts")
+    void testValidateWithQueryPositiveTimeout(final Duration timeout, final 
int timeoutSeconds) throws Exception {
+        final Connection nativeConnection = mock(Connection.class);
+        final PreparedStatement statement = 
mockValidationStatement(nativeConnection);
+        final PoolableConnection conn = new 
PoolableConnection(nativeConnection, null, null);
+        try {
+            conn.validate("SELECT 1", timeout);
+            final InOrder order = inOrder(statement);
+            order.verify(statement).setQueryTimeout(timeoutSeconds);
+            order.verify(statement).executeQuery();
+            order.verifyNoMoreInteractions();
+            verify(nativeConnection, never()).isValid(anyInt());
+        } finally {
+            conn.reallyClose();
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("nonPositiveValidationTimeouts")
+    void testValidateWithQueryRetainsCachedTimeout(final Duration timeout) 
throws Exception {
+        final Connection nativeConnection = mock(Connection.class);
+        final TesterPreparedStatement statement = new 
TesterPreparedStatement(nativeConnection, "SELECT 1");
+        when(nativeConnection.prepareStatement("SELECT 
1")).thenReturn(statement);
+        final PoolableConnection conn = new 
PoolableConnection(nativeConnection, null, null);
+        try {
+            conn.validate("SELECT 1", Duration.ofSeconds(5));
+            conn.validate("SELECT 1", timeout);
+            assertEquals(5, statement.getQueryTimeout());
+            verify(nativeConnection).prepareStatement("SELECT 1");
+        } finally {
+            conn.reallyClose();
+        }
+    }
+
+    @Test
+    void testValidateWithQuerySetTimeoutSQLException() throws Exception {
+        final Connection nativeConnection = mock(Connection.class);
+        final PreparedStatement statement = 
mockValidationStatement(nativeConnection);
+        final SQLException expected = new SQLException("Cannot set query 
timeout");
+        doThrow(expected).when(statement).setQueryTimeout(1);
+        final PoolableConnection conn = new 
PoolableConnection(nativeConnection, null, null);
+        try {
+            assertSame(expected, assertThrows(SQLException.class, () -> 
conn.validate("SELECT 1", Duration.ofMillis(100))));
+            verify(statement, never()).executeQuery();
+        } finally {
+            conn.reallyClose();
+        }
+    }
+
+    @Test
+    void testValidateWithQueryTimeoutException() throws Exception {
+        final Connection nativeConnection = mock(Connection.class);
+        final PreparedStatement statement = 
mockValidationStatement(nativeConnection);
+        final SQLTimeoutException expected = new 
SQLTimeoutException("Validation query timed out");
+        when(statement.executeQuery()).thenThrow(expected);
+        final PoolableConnection conn = new 
PoolableConnection(nativeConnection, null, null);
+        try {
+            assertSame(expected, assertThrows(SQLTimeoutException.class, () -> 
conn.validate("SELECT 1", Duration.ofMillis(100))));
+            verify(statement).setQueryTimeout(1);
+        } finally {
+            conn.reallyClose();
+        }
+    }
+
+    @ParameterizedTest
+    @MethodSource("positiveValidationTimeouts")
+    void testValidateWithQueryUpdatesCachedTimeout(final Duration timeout, 
final int timeoutSeconds) throws Exception {
+        final Connection nativeConnection = mock(Connection.class);
+        final PreparedStatement statement = 
mockValidationStatement(nativeConnection);
+        final PoolableConnection conn = new 
PoolableConnection(nativeConnection, null, null);
+        try {
+            conn.validate("SELECT 1", Duration.ofSeconds(5));
+            conn.validate("SELECT 1", timeout);
+            verify(nativeConnection).prepareStatement("SELECT 1");
+            final InOrder order = inOrder(statement);
+            order.verify(statement).setQueryTimeout(5);
+            order.verify(statement).executeQuery();
+            order.verify(statement).setQueryTimeout(timeoutSeconds);
+            order.verify(statement).executeQuery();
+            order.verifyNoMoreInteractions();
+        } finally {
+            conn.reallyClose();
+        }
+    }
 }

Reply via email to