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 4408b323 [DBCP-601] Clear transaction association after read-only 
prepare
     new 80935fec Merge branch 'master' of 
https://github.com/apache/commons-dbcp.git
4408b323 is described below

commit 4408b32322a21cfd1e7508e15c6dc3d4b7ca3aa7
Author: Gary Gregory <[email protected]>
AuthorDate: Mon Nov 23 12:09:52 2026 -0500

    [DBCP-601] Clear transaction association after read-only prepare
    
    Clear currentXid before returning XA_RDONLY so pooled connections can
    enlist in subsequent transactions. Preserve the association when
    auto-commit restoration fails.
    
    Add regression tests for connection reuse, both auto-commit settings,
    restoration failure, and read-write behavior. Update Javadoc.
---
 src/changes/changes.xml                            |  1 +
 .../dbcp2/managed/LocalXAConnectionFactory.java    | 25 ++++--
 .../dbcp2/managed/TestBasicManagedDataSource.java  | 91 ++++++++++++++++++++++
 .../commons/dbcp2/managed/TestLocalXaResource.java | 52 +++++++++++++
 4 files changed, 164 insertions(+), 5 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 3263088f..43a05e3e 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -85,6 +85,7 @@ The <action> type attribute can be add,update,fix,remove.
       <action type="fix" dev="ggregory" due-to="Gary Gregory">Preserve 
DriverAdapterCPDS eviction durations through JNDI References, including 
negative fractional seconds on Java 8, preferring Duration properties and 
accepting long legacy millisecond values.</action>
       <action type="fix" dev="ggregory" due-to="Gary Gregory">Apply 
SharedPoolDataSource and PerUserPoolDataSource login timeouts to every physical 
connection attempt, restoring the underlying provider's timeout afterwards. 
Bound waits to configure the provider, and preserve live timeout settings 
across deserialization.</action>
       <action type="fix" dev="ggregory" due-to="Gary Gregory">Preserve local 
login timeout settings when SharedPoolDataSource and PerUserPoolDataSource are 
deserialized before configuring a connection provider, including the 
distinction between an unset timeout and explicit zero.</action>
+      <action type="fix" dev="ggregory" due-to="Ken Pritchard, Gary Gregory" 
issue="DBCP-601">Clear the transaction association when 
LocalXAResource.prepare() returns XA_RDONLY so read-only pooled connections can 
enlist in subsequent transactions #552.</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/managed/LocalXAConnectionFactory.java 
b/src/main/java/org/apache/commons/dbcp2/managed/LocalXAConnectionFactory.java
index 25bc0d80..233f2e8f 100644
--- 
a/src/main/java/org/apache/commons/dbcp2/managed/LocalXAConnectionFactory.java
+++ 
b/src/main/java/org/apache/commons/dbcp2/managed/LocalXAConnectionFactory.java
@@ -184,14 +184,26 @@ public class LocalXAConnectionFactory implements 
XAConnectionFactory {
         }
 
         /**
-         * This method does nothing since the LocalXAConnection does not 
support two-phase-commit. This method will
-         * return XAResource.XA_RDONLY if the connection isReadOnly(). This 
assumes that the physical connection is
-         * wrapped with a proxy that prevents an application from changing the 
read-only flag while enrolled in a
-         * transaction.
+         * Prepares the transaction branch for completion.
+         *
+         * <p>
+         * For a read-only connection, restores the original auto-commit 
setting and clears the transaction association before returning
+         * {@link XAResource#XA_RDONLY}. The transaction manager will not call 
{@link #commit(Xid, boolean)} or {@link #rollback(Xid)} for that branch.
+         * </p>
+         *
+         * <p>
+         * Otherwise, or if checking the read-only setting or restoring 
auto-commit throws an {@link SQLException}, retains the transaction association
+         * and returns {@link XAResource#XA_OK}. The local connection does not 
support an actual two-phase prepare operation.
+         * </p>
+         *
+         * <p>
+         * Assumes that the physical connection is wrapped with a proxy that 
prevents an application from changing the read-only flag while enrolled
+         * in a transaction.
+         * </p>
          *
          * @param xid
          *            the id of the transaction branch for this connection
-         * @return XAResource.XA_RDONLY if the connection.isReadOnly(); 
XAResource.XA_OK otherwise
+         * @return {@link XAResource#XA_RDONLY} if the read-only branch 
completes successfully; {@link XAResource#XA_OK} otherwise.
          */
         @Override
         public synchronized int prepare(final Xid xid) {
@@ -203,6 +215,9 @@ public class LocalXAConnectionFactory implements 
XAConnectionFactory {
                     // update the auto commit flag
                     connection.setAutoCommit(originalAutoCommit);
 
+                    // A read-only vote completes the branch without a 
subsequent commit or rollback call.
+                    this.currentXid = null;
+
                     // tell the transaction manager we are read only
                     return XA_RDONLY;
                 }
diff --git 
a/src/test/java/org/apache/commons/dbcp2/managed/TestBasicManagedDataSource.java
 
b/src/test/java/org/apache/commons/dbcp2/managed/TestBasicManagedDataSource.java
index fd435387..0532c1b0 100644
--- 
a/src/test/java/org/apache/commons/dbcp2/managed/TestBasicManagedDataSource.java
+++ 
b/src/test/java/org/apache/commons/dbcp2/managed/TestBasicManagedDataSource.java
@@ -22,6 +22,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.junit.jupiter.api.Assertions.fail;
 
 import java.sql.Connection;
@@ -31,6 +32,8 @@ import javax.sql.XADataSource;
 import javax.transaction.TransactionManager;
 import javax.transaction.TransactionSynchronizationRegistry;
 import javax.transaction.xa.XAException;
+import javax.transaction.xa.XAResource;
+import javax.transaction.xa.Xid;
 
 import org.apache.commons.dbcp2.BasicDataSource;
 import org.apache.commons.dbcp2.TestBasicDataSource;
@@ -48,6 +51,57 @@ import 
com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionSynchroniza
  */
 public class TestBasicManagedDataSource extends TestBasicDataSource {
 
+    /**
+     * A second transaction participant that votes {@link XAResource#XA_OK} 
and does nothing else.
+     */
+    private static final class OtherXAResource implements XAResource {
+
+        @Override
+        public void commit(final Xid xid, final boolean onePhase) {
+        }
+
+        @Override
+        public void end(final Xid xid, final int flags) {
+        }
+
+        @Override
+        public void forget(final Xid xid) {
+        }
+
+        @Override
+        public int getTransactionTimeout() {
+            return 0;
+        }
+
+        @Override
+        public boolean isSameRM(final XAResource xaResource) {
+            return xaResource == this;
+        }
+
+        @Override
+        public int prepare(final Xid xid) {
+            return XA_OK;
+        }
+
+        @Override
+        public Xid[] recover(final int flag) {
+            return new Xid[0];
+        }
+
+        @Override
+        public void rollback(final Xid xid) {
+        }
+
+        @Override
+        public boolean setTransactionTimeout(final int seconds) {
+            return false;
+        }
+
+        @Override
+        public void start(final Xid xid, final int flags) {
+        }
+    }
+
     @Override
     protected BasicDataSource createDataSource() throws Exception {
         final BasicManagedDataSource basicManagedDataSource = new 
BasicManagedDataSource();
@@ -77,6 +131,43 @@ public class TestBasicManagedDataSource extends 
TestBasicDataSource {
         }
     }
 
+    /**
+     * Tests that a read-only connection remains reusable after voting {@link 
XAResource#XA_RDONLY} in a two-phase commit.
+     *
+     * @throws Exception if the test fails.
+     */
+    @Test
+    void testReadOnlyConnectionReusableAfterTwoPhaseCommit() throws Exception {
+        final TransactionManagerImpl transactionManager = new 
TransactionManagerImpl();
+        try (final BasicManagedDataSource basicManagedDataSource = new 
BasicManagedDataSource()) {
+            basicManagedDataSource.setTransactionManager(transactionManager);
+            
basicManagedDataSource.setDriverClassName("org.apache.commons.dbcp2.TesterDriver");
+            basicManagedDataSource.setUrl("jdbc:apache:commons:testdriver");
+            basicManagedDataSource.setUsername("userName");
+            basicManagedDataSource.setPassword("password");
+            basicManagedDataSource.setDefaultReadOnly(Boolean.TRUE);
+            basicManagedDataSource.setMaxTotal(1);
+            for (int i = 0; i < 2; i++) {
+                transactionManager.begin();
+                try {
+                    // A second resource makes the transaction manager use 
two-phase commit.
+                    
assertTrue(transactionManager.getTransaction().enlistResource(new 
OtherXAResource()));
+                    try (final Connection connection = 
basicManagedDataSource.getConnection()) {
+                        assertTrue(connection.isReadOnly());
+                    }
+                    transactionManager.commit();
+                } finally {
+                    if (transactionManager.getTransaction() != null) {
+                        transactionManager.rollback();
+                    }
+                }
+            }
+            // The same pooled connection served both transactions.
+            assertEquals(1, 
basicManagedDataSource.getConnectionPool().getCreatedCount());
+            assertEquals(0, 
basicManagedDataSource.getConnectionPool().getDestroyedCount());
+        }
+    }
+
     /**
      * JIRA: DBCP-294
      * Verify that PoolableConnections created by BasicManagedDataSource 
unregister themselves
diff --git 
a/src/test/java/org/apache/commons/dbcp2/managed/TestLocalXaResource.java 
b/src/test/java/org/apache/commons/dbcp2/managed/TestLocalXaResource.java
index cc15365d..0c57ab28 100644
--- a/src/test/java/org/apache/commons/dbcp2/managed/TestLocalXaResource.java
+++ b/src/test/java/org/apache/commons/dbcp2/managed/TestLocalXaResource.java
@@ -48,6 +48,8 @@ import javax.transaction.xa.Xid;
 
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
 
 /**
  * Tests for LocalXAConnectionFactory$LocalXAResource
@@ -451,6 +453,56 @@ public class TestLocalXaResource {
         assertFalse(resource.isSameRM(new 
LocalXAConnectionFactory.LocalXAResource(conn)));
     }
 
+    @ParameterizedTest
+    @ValueSource(booleans = { false, true })
+    void testPrepareReadOnlyEndsTransactionBranch(final boolean autoCommit) 
throws SQLException, XAException {
+        final Xid xid = new TestXid();
+        conn.setAutoCommit(autoCommit);
+        conn.setReadOnly(true);
+        resource.start(xid, XAResource.TMNOFLAGS);
+        resource.end(xid, XAResource.TMSUCCESS);
+        assertEquals(XAResource.XA_RDONLY, resource.prepare(xid));
+        assertNull(resource.getXid());
+        assertEquals(autoCommit, conn.getAutoCommit());
+        assertFalse(((TestConnection) conn).committed);
+        assertFalse(((TestConnection) conn).rolledback);
+        final Xid nextXid = new TestXid();
+        resource.start(nextXid, XAResource.TMNOFLAGS);
+        assertEquals(nextXid, resource.getXid());
+        assertFalse(conn.getAutoCommit());
+    }
+
+    @Test
+    void testPrepareReadOnlyKeepsTransactionBranchWhenAutoCommitRestoreFails() 
throws SQLException, XAException {
+        final Xid xid = new TestXid();
+        conn.setAutoCommit(true);
+        conn.setReadOnly(true);
+        resource.start(xid, XAResource.TMNOFLAGS);
+        resource.end(xid, XAResource.TMSUCCESS);
+        ((TestConnection) conn).throwWhenSetAutoCommit = true;
+        assertEquals(XAResource.XA_OK, resource.prepare(xid));
+        assertEquals(xid, resource.getXid());
+        assertFalse(conn.getAutoCommit());
+        ((TestConnection) conn).throwWhenSetAutoCommit = false;
+        resource.rollback(xid);
+        assertTrue(((TestConnection) conn).rolledback);
+        assertTrue(conn.getAutoCommit());
+        assertNull(resource.getXid());
+    }
+
+    @Test
+    void testPrepareReadWriteKeepsTransactionBranch() throws SQLException, 
XAException {
+        final Xid xid = new TestXid();
+        conn.setReadOnly(false);
+        resource.start(xid, XAResource.TMNOFLAGS);
+        resource.end(xid, XAResource.TMSUCCESS);
+        assertEquals(XAResource.XA_OK, resource.prepare(xid));
+        assertEquals(xid, resource.getXid());
+        resource.commit(xid, false);
+        assertTrue(((TestConnection) conn).committed);
+        assertNull(resource.getXid());
+    }
+
     @Test
     void testRollback() throws SQLException, XAException {
         final Xid xid = new TestXid();

Reply via email to