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

jbonofre pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-java.git


The following commit(s) were added to refs/heads/main by this push:
     new 054c7b8b7 GH-62: Optimize Flight SQL JDBC Statement execution paths 
(#1090)
054c7b8b7 is described below

commit 054c7b8b77791cb98b8b13645aeff720a2da7632
Author: Hélder Gregório <[email protected]>
AuthorDate: Wed Nov 11 08:25:52 2026 +0000

    GH-62: Optimize Flight SQL JDBC Statement execution paths (#1090)
    
    ## What Changed
    
    - This change simplifies the Flight SQL JDBC request flow for
    `Statement.executeQuery/executeUpdate` avoiding the `PreparedStatement`
    request flow
    - Preserved the current requirement that `Statement.execute(String)`
    still flows through PreparedStatement
    - Right now, Arrow Flight does not offer a good solution for this use
    case. There is no way for the client to disambiguate between a
    `CommandStatementUpdate` or `CommandStatemenQuery` without doing a
    server call
    - Moved prepared-statement-specific creation and execution concerns into
    `ArrowFlightPreparedStatement`
    - Similarly, created `ArrowFlightStatement` with specific logic to
    handle `Statements`
    - Removed statement/prepared-statement construction details and logic
    from `ArrowFlightMetaImpl`. `ArrowFlightMetaImpl` was left it focused on
    orchestration
    
    Closes #62.
    
    This PR was assisted by AI
    
    ---------
    
    Co-authored-by: JB Onofré <[email protected]>
---
 .../arrow/driver/jdbc/ArrowFlightConnection.java   |  77 ++-
 .../arrow/driver/jdbc/ArrowFlightJdbcFactory.java  |  22 +-
 .../jdbc/ArrowFlightJdbcFlightStreamResultSet.java | 105 +++-
 .../ArrowFlightJdbcVectorSchemaRootResultSet.java  |   2 +-
 .../arrow/driver/jdbc/ArrowFlightMetaImpl.java     | 258 ++++------
 .../driver/jdbc/ArrowFlightPreparedStatement.java  | 245 +++++++++-
 .../arrow/driver/jdbc/ArrowFlightStatement.java    | 153 +++++-
 .../jdbc/client/ArrowFlightSqlClientHandler.java   |  10 +
 ...rrowFlightJdbcConnectionPoolDataSourceTest.java | 100 ++++
 .../ArrowFlightJdbcFlightStreamResultSetTest.java  |  86 ++++
 .../jdbc/ArrowFlightPreparedStatementTest.java     | 151 +++++-
 .../jdbc/ArrowFlightStatementExecuteTest.java      | 113 ++++-
 .../ArrowFlightStatementExecuteUpdateTest.java     |  25 +-
 .../jdbc/ArrowFlightStatementProtocolTest.java     | 539 +++++++++++++++++++++
 .../apache/arrow/driver/jdbc/ResultSetTest.java    |  49 +-
 .../driver/jdbc/utils/MockFlightSqlProducer.java   |  55 ++-
 16 files changed, 1719 insertions(+), 271 deletions(-)

diff --git 
a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java
 
b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java
index a5c453176..366223067 100644
--- 
a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java
+++ 
b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java
@@ -19,11 +19,18 @@ package org.apache.arrow.driver.jdbc;
 import static 
org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty.replaceSemiColons;
 
 import io.netty.util.concurrent.DefaultThreadFactory;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
 import java.sql.SQLException;
+import java.sql.Statement;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.HashMap;
+import java.util.HashSet;
+import java.util.IdentityHashMap;
 import java.util.Map;
 import java.util.Properties;
+import java.util.Set;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import org.apache.arrow.driver.jdbc.client.ArrowFlightSqlClientHandler;
@@ -33,8 +40,10 @@ import org.apache.arrow.flight.FlightClient;
 import org.apache.arrow.memory.BufferAllocator;
 import org.apache.arrow.util.AutoCloseables;
 import org.apache.arrow.util.Preconditions;
+import org.apache.arrow.util.VisibleForTesting;
 import org.apache.calcite.avatica.AvaticaConnection;
 import org.apache.calcite.avatica.AvaticaFactory;
+import org.apache.calcite.avatica.AvaticaStatement;
 import org.apache.calcite.avatica.DriverVersion;
 
 /** Connection to the Arrow Flight server. */
@@ -45,7 +54,11 @@ public final class ArrowFlightConnection extends 
AvaticaConnection {
   private final ArrowFlightConnectionConfigImpl config;
   private ExecutorService executorService;
   private int metadataResultSetCount;
+  // Track metadata result sets so connection close can release them.
   private Map<Integer, ArrowFlightJdbcFlightStreamResultSet> 
metadataResultSetMap = new HashMap<>();
+  // Track original statement owners when execution replaces their 
statement-map entries.
+  private final Set<AvaticaStatement> statementOwners =
+      Collections.newSetFromMap(new IdentityHashMap<>());
 
   /**
    * Creates a new {@link ArrowFlightConnection}.
@@ -143,7 +156,7 @@ public final class ArrowFlightConnection extends 
AvaticaConnection {
   void reset() throws SQLException {
     // Clean up any open Statements
     try {
-      AutoCloseables.close(statementMap.values());
+      AutoCloseables.close(getStatementsToClose());
     } catch (final Exception e) {
       throw AvaticaConnection.HELPER.createException(e.getMessage(), e);
     }
@@ -204,6 +217,33 @@ public final class ArrowFlightConnection extends 
AvaticaConnection {
     metadataResultSetMap.remove(id);
   }
 
+  synchronized void registerStatementOwner(final AvaticaStatement statement) {
+    statementOwners.add(statement);
+  }
+
+  synchronized void unregisterStatementOwner(final AvaticaStatement statement) 
{
+    statementOwners.remove(statement);
+  }
+
+  @VisibleForTesting
+  synchronized boolean isStatementOwner(final Statement statement) {
+    return statementOwners.contains(statement);
+  }
+
+  private synchronized ArrayList<AutoCloseable> getStatementsToClose() {
+    final ArrayList<AutoCloseable> statements = new 
ArrayList<>(statementOwners);
+    final Set<Integer> ownedHandles = new HashSet<>();
+    for (AvaticaStatement statement : statementOwners) {
+      ownedHandles.add(statement.handle.id);
+    }
+    for (Map.Entry<Integer, AvaticaStatement> entry : statementMap.entrySet()) 
{
+      if (!ownedHandles.contains(entry.getKey())) {
+        statements.add(entry.getValue());
+      }
+    }
+    return statements;
+  }
+
   @Override
   public Properties getClientInfo() {
     final Properties copy = new Properties();
@@ -222,7 +262,7 @@ public final class ArrowFlightConnection extends 
AvaticaConnection {
       topLevelException = e;
     }
     // copies of the collections are used to avoid concurrent modification 
problems
-    ArrayList<AutoCloseable> closeables = new 
ArrayList<>(statementMap.values());
+    ArrayList<AutoCloseable> closeables = getStatementsToClose();
     closeables.addAll(new ArrayList<>(metadataResultSetMap.values()));
     closeables.add(clientHandler);
     closeables.addAll(allocator.getChildAllocators());
@@ -258,4 +298,37 @@ public final class ArrowFlightConnection extends 
AvaticaConnection {
   public ArrowFlightMetaImpl getMeta() {
     return (ArrowFlightMetaImpl) this.meta;
   }
+
+  @Override
+  public PreparedStatement prepareStatement(final String sql) throws 
SQLException {
+    return prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, 
ResultSet.CONCUR_READ_ONLY);
+  }
+
+  @Override
+  public PreparedStatement prepareStatement(
+      final String sql, final int resultSetType, final int 
resultSetConcurrency)
+      throws SQLException {
+    return prepareStatement(sql, resultSetType, resultSetConcurrency, 
getHoldability());
+  }
+
+  @Override
+  public PreparedStatement prepareStatement(
+      final String sql,
+      final int resultSetType,
+      final int resultSetConcurrency,
+      final int resultSetHoldability)
+      throws SQLException {
+    checkOpen();
+    try {
+      return ArrowFlightPreparedStatement.builder(this)
+          .withQuery(sql)
+          .withGeneratedHandle()
+          .withResultSetType(resultSetType)
+          .withResultSetConcurrency(resultSetConcurrency)
+          .withResultSetHoldability(resultSetHoldability)
+          .build();
+    } catch (final RuntimeException e) {
+      throw HELPER.createException("while preparing SQL:" + sql, e);
+    }
+  }
 }
diff --git 
a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFactory.java
 
b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFactory.java
index e1ccfc820..10c361866 100644
--- 
a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFactory.java
+++ 
b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFactory.java
@@ -20,7 +20,6 @@ import java.sql.ResultSetMetaData;
 import java.sql.SQLException;
 import java.util.Properties;
 import java.util.TimeZone;
-import org.apache.arrow.driver.jdbc.client.ArrowFlightSqlClientHandler;
 import org.apache.arrow.memory.RootAllocator;
 import org.apache.calcite.avatica.AvaticaConnection;
 import org.apache.calcite.avatica.AvaticaFactory;
@@ -82,17 +81,18 @@ public class ArrowFlightJdbcFactory implements 
AvaticaFactory {
       final int resultSetHoldability)
       throws SQLException {
     final ArrowFlightConnection flightConnection = (ArrowFlightConnection) 
connection;
-    ArrowFlightSqlClientHandler.PreparedStatement preparedStatement =
-        flightConnection.getMeta().getPreparedStatement(statementHandle);
+    final AvaticaStatement existingStatement =
+        flightConnection.statementMap.get(statementHandle.id);
+    if (existingStatement instanceof ArrowFlightPreparedStatement) {
+      return (ArrowFlightPreparedStatement) existingStatement;
+    }
+    if (existingStatement != null) {
+      throw new IllegalStateException(
+          "Unexpected statement type found for prepared statement handle: " + 
statementHandle);
+    }
 
-    return ArrowFlightPreparedStatement.newPreparedStatement(
-        flightConnection,
-        preparedStatement,
-        statementHandle,
-        signature,
-        resultType,
-        resultSetConcurrency,
-        resultSetHoldability);
+    throw new IllegalStateException(
+        "PreparedStatement was not pre-created for handle: " + 
statementHandle);
   }
 
   @Override
diff --git 
a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java
 
b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java
index 376e5b11e..2ab807e78 100644
--- 
a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java
+++ 
b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java
@@ -21,17 +21,22 @@ import static 
org.apache.arrow.driver.jdbc.utils.FlightEndpointDataQueue.createN
 import java.sql.ResultSet;
 import java.sql.ResultSetMetaData;
 import java.sql.SQLException;
+import java.util.Collection;
+import java.util.Iterator;
 import java.util.Optional;
 import java.util.TimeZone;
 import java.util.concurrent.TimeUnit;
 import org.apache.arrow.driver.jdbc.client.CloseableEndpointStreamPair;
 import org.apache.arrow.driver.jdbc.utils.FlightEndpointDataQueue;
 import org.apache.arrow.driver.jdbc.utils.VectorSchemaRootTransformer;
+import org.apache.arrow.flight.CallStatus;
 import org.apache.arrow.flight.FlightInfo;
+import org.apache.arrow.flight.FlightRuntimeException;
 import org.apache.arrow.flight.FlightStream;
 import org.apache.arrow.util.AutoCloseables;
 import org.apache.arrow.vector.VectorSchemaRoot;
 import org.apache.arrow.vector.types.pojo.Schema;
+import org.apache.calcite.avatica.AvaticaConnection;
 import org.apache.calcite.avatica.AvaticaResultSet;
 import org.apache.calcite.avatica.AvaticaResultSetMetaData;
 import org.apache.calcite.avatica.AvaticaStatement;
@@ -49,6 +54,7 @@ public final class ArrowFlightJdbcFlightStreamResultSet
   private final FlightInfo flightInfo;
   private CloseableEndpointStreamPair currentEndpointData;
   private FlightEndpointDataQueue flightEndpointDataQueue;
+  private volatile boolean cancelled;
 
   private VectorSchemaRootTransformer transformer;
   private VectorSchemaRoot currentVectorSchemaRoot;
@@ -106,7 +112,7 @@ public final class ArrowFlightJdbcFlightStreamResultSet
     final TimeZone timeZone = TimeZone.getDefault();
     final QueryState state = new QueryState();
 
-    final Meta.Signature signature = ArrowFlightMetaImpl.newSignature(null, 
null, null, null);
+    final Meta.Signature signature = 
ArrowFlightMetaImpl.buildDefaultSignature();
 
     final AvaticaResultSetMetaData resultSetMetaData =
         new AvaticaResultSetMetaData(null, null, signature);
@@ -143,7 +149,8 @@ public final class ArrowFlightJdbcFlightStreamResultSet
 
   private void populateData() throws SQLException {
     loadNewQueue();
-    
flightEndpointDataQueue.enqueue(connection.getClientHandler().getStreams(flightInfo));
+    enqueueEndpointData(
+        flightEndpointDataQueue, 
connection.getClientHandler().getStreams(flightInfo));
     loadNewFlightStream();
 
     // Ownership of the root will be passed onto the cursor.
@@ -192,23 +199,38 @@ public final class ArrowFlightJdbcFlightStreamResultSet
         return true;
       }
 
-      if (currentEndpointData != null) {
-        currentEndpointData.getStream().getRoot().clear();
-        if (currentEndpointData.getStream().next()) {
-          populateDataForCurrentFlightStream();
-          continue;
+      try {
+        if (currentEndpointData != null) {
+          currentEndpointData.getStream().getRoot().clear();
+          if (currentEndpointData.getStream().next()) {
+            populateDataForCurrentFlightStream();
+            continue;
+          }
+
+          enqueueEndpointData(currentEndpointData);
         }
 
-        flightEndpointDataQueue.enqueue(currentEndpointData);
+        currentEndpointData = getNextEndpointStream(false);
+      } catch (final FlightRuntimeException e) {
+        // A concurrent statement.cancel() (or close) cancels in-flight 
FlightStreams,
+        // which surface here as CANCELLED. Normalize to Avatica's "Statement 
canceled".
+        if ((cancelled || flightEndpointDataQueue.isClosed())
+            && e.status().code() == CallStatus.CANCELLED.code()) {
+          throw AvaticaConnection.HELPER.createException("Statement canceled");
+        }
+        throw e;
       }
 
-      currentEndpointData = getNextEndpointStream(false);
-
       if (currentEndpointData != null) {
         populateDataForCurrentFlightStream();
         continue;
       }
 
+      // Cancellation can wake the reader before queue cleanup completes.
+      if (cancelled || flightEndpointDataQueue.isClosed()) {
+        throw AvaticaConnection.HELPER.createException("Statement canceled");
+      }
+
       if (statement != null && statement.isCloseOnCompletion()) {
         statement.close();
       }
@@ -219,6 +241,7 @@ public final class ArrowFlightJdbcFlightStreamResultSet
 
   @Override
   protected void cancel() {
+    cancelled = true;
     super.cancel();
     final CloseableEndpointStreamPair currentEndpoint = 
this.currentEndpointData;
     if (currentEndpoint != null) {
@@ -259,13 +282,61 @@ public final class ArrowFlightJdbcFlightStreamResultSet
 
   private CloseableEndpointStreamPair getNextEndpointStream(final boolean 
canTimeout)
       throws SQLException {
-    if (canTimeout) {
-      final int statementTimeout = statement != null ? 
statement.getQueryTimeout() : 0;
-      return statementTimeout != 0
-          ? flightEndpointDataQueue.next(statementTimeout, TimeUnit.SECONDS)
-          : flightEndpointDataQueue.next();
-    } else {
-      return flightEndpointDataQueue.next();
+    try {
+      if (canTimeout) {
+        final int statementTimeout = statement != null ? 
statement.getQueryTimeout() : 0;
+        return statementTimeout != 0
+            ? flightEndpointDataQueue.next(statementTimeout, TimeUnit.SECONDS)
+            : flightEndpointDataQueue.next();
+      } else {
+        return flightEndpointDataQueue.next();
+      }
+    } catch (final IllegalStateException e) {
+      throw normalizeClosedQueueException(flightEndpointDataQueue, e);
+    }
+  }
+
+  static void enqueueEndpointData(
+      final FlightEndpointDataQueue queue,
+      final Collection<CloseableEndpointStreamPair> endpointRequests)
+      throws SQLException {
+    final Iterator<CloseableEndpointStreamPair> endpointIterator = 
endpointRequests.iterator();
+    while (endpointIterator.hasNext()) {
+      final CloseableEndpointStreamPair endpointRequest = 
endpointIterator.next();
+      try {
+        queue.enqueue(endpointRequest);
+      } catch (final IllegalStateException e) {
+        final SQLException exception = normalizeClosedQueueException(queue, e);
+        closeRejectedEndpoint(endpointRequest, exception);
+        endpointIterator.forEachRemaining(endpoint -> 
closeRejectedEndpoint(endpoint, exception));
+        throw exception;
+      }
+    }
+  }
+
+  private void enqueueEndpointData(final CloseableEndpointStreamPair 
endpointRequest)
+      throws SQLException {
+    try {
+      flightEndpointDataQueue.enqueue(endpointRequest);
+    } catch (final IllegalStateException e) {
+      throw normalizeClosedQueueException(flightEndpointDataQueue, e);
+    }
+  }
+
+  private static void closeRejectedEndpoint(
+      final CloseableEndpointStreamPair endpoint, final SQLException 
exception) {
+    try {
+      endpoint.close();
+    } catch (final Exception closeException) {
+      exception.addSuppressed(closeException);
+    }
+  }
+
+  private static SQLException normalizeClosedQueueException(
+      final FlightEndpointDataQueue queue, final IllegalStateException 
exception) {
+    if (queue.isClosed()) {
+      return AvaticaConnection.HELPER.createException("Statement canceled");
     }
+    throw exception;
   }
 }
diff --git 
a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcVectorSchemaRootResultSet.java
 
b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcVectorSchemaRootResultSet.java
index ad6670a00..d1d2ddc23 100644
--- 
a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcVectorSchemaRootResultSet.java
+++ 
b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcVectorSchemaRootResultSet.java
@@ -73,7 +73,7 @@ public class ArrowFlightJdbcVectorSchemaRootResultSet extends 
AvaticaResultSet {
     final TimeZone timeZone = TimeZone.getDefault();
     final QueryState state = new QueryState();
 
-    final Meta.Signature signature = ArrowFlightMetaImpl.newSignature(null, 
null, null, null);
+    final Meta.Signature signature = 
ArrowFlightMetaImpl.buildDefaultSignature();
 
     final AvaticaResultSetMetaData resultSetMetaData =
         new AvaticaResultSetMetaData(null, null, signature);
diff --git 
a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightMetaImpl.java
 
b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightMetaImpl.java
index 0d85b5edd..b085f6537 100644
--- 
a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightMetaImpl.java
+++ 
b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightMetaImpl.java
@@ -17,20 +17,17 @@
 package org.apache.arrow.driver.jdbc;
 
 import java.sql.Connection;
+import java.sql.ResultSet;
 import java.sql.SQLException;
-import java.sql.SQLTimeoutException;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import 
org.apache.arrow.driver.jdbc.client.ArrowFlightSqlClientHandler.PreparedStatement;
-import org.apache.arrow.driver.jdbc.utils.AvaticaParameterBinder;
 import org.apache.arrow.driver.jdbc.utils.ConvertUtils;
 import org.apache.arrow.util.Preconditions;
 import org.apache.arrow.vector.types.pojo.Schema;
 import org.apache.calcite.avatica.AvaticaConnection;
 import org.apache.calcite.avatica.AvaticaParameter;
+import org.apache.calcite.avatica.AvaticaStatement;
 import org.apache.calcite.avatica.ColumnMetaData;
 import org.apache.calcite.avatica.MetaImpl;
 import org.apache.calcite.avatica.NoSuchStatementException;
@@ -39,8 +36,6 @@ import org.apache.calcite.avatica.remote.TypedValue;
 
 /** Metadata handler for Arrow Flight. */
 public class ArrowFlightMetaImpl extends MetaImpl {
-  private final Map<StatementHandleKey, PreparedStatement> 
statementHandlePreparedStatementMap;
-
   /**
    * Constructs a {@link MetaImpl} object specific for Arrow Flight.
    *
@@ -48,50 +43,14 @@ public class ArrowFlightMetaImpl extends MetaImpl {
    */
   public ArrowFlightMetaImpl(final AvaticaConnection connection) {
     super(connection);
-    this.statementHandlePreparedStatementMap = new ConcurrentHashMap<>();
     setDefaultConnectionProperties();
   }
 
-  /** Construct a signature. */
-  static Signature newSignature(
-      final String sql, Schema resultSetSchema, Schema parameterSchema, 
Boolean isUpdate) {
-    List<ColumnMetaData> columnMetaData =
-        resultSetSchema == null
-            ? new ArrayList<>()
-            : 
ConvertUtils.convertArrowFieldsToColumnMetaDataList(resultSetSchema.getFields());
-    List<AvaticaParameter> parameters =
-        parameterSchema == null
-            ? new ArrayList<>()
-            : 
ConvertUtils.convertArrowFieldsToAvaticaParameters(parameterSchema.getFields());
-    // If the server provided the is_update field, use it to determine the 
statement type
-    StatementType statementType;
-    if (isUpdate != null) {
-      statementType = isUpdate ? StatementType.IS_DML : StatementType.SELECT;
-    } else {
-      // Fall back to the legacy logic: check if the result set schema is empty
-      statementType =
-          resultSetSchema == null || resultSetSchema.getFields().isEmpty()
-              ? StatementType.IS_DML
-              : StatementType.SELECT;
-    }
-    return new Signature(
-        columnMetaData,
-        sql,
-        parameters,
-        Collections.emptyMap(),
-        null, // unnecessary, as SQL requests use ArrowFlightJdbcCursor
-        statementType);
-  }
-
   @Override
   public void closeStatement(final StatementHandle statementHandle) {
-    PreparedStatement preparedStatement =
-        statementHandlePreparedStatementMap.remove(new 
StatementHandleKey(statementHandle));
-    // Testing if the prepared statement was created because the statement can 
be
-    // not created until
-    // this moment
-    if (preparedStatement != null) {
-      preparedStatement.close();
+    final AvaticaStatement statement = getStatement(statementHandle);
+    if (statement instanceof ArrowFlightPreparedStatement) {
+      ((ArrowFlightPreparedStatement) statement).closePreparedResources();
     }
   }
 
@@ -105,36 +64,8 @@ public class ArrowFlightMetaImpl extends MetaImpl {
       final StatementHandle statementHandle,
       final List<TypedValue> typedValues,
       final long maxRowCount) {
-    Preconditions.checkArgument(
-        connection.id.equals(statementHandle.connectionId), "Connection IDs 
are not consistent");
-    PreparedStatement preparedStatement = 
getPreparedStatement(statementHandle);
-
-    if (preparedStatement == null) {
-      throw new IllegalStateException("Prepared statement not found: " + 
statementHandle);
-    }
-
-    new AvaticaParameterBinder(
-            preparedStatement, ((ArrowFlightConnection) 
connection).getBufferAllocator())
-        .bind(typedValues);
-
-    if (statementHandle.signature == null
-        || statementHandle.signature.statementType == StatementType.IS_DML) {
-      // Update query
-      long updatedCount = preparedStatement.executeUpdate();
-      return new ExecuteResult(
-          Collections.singletonList(
-              MetaResultSet.count(statementHandle.connectionId, 
statementHandle.id, updatedCount)));
-    } else {
-      // TODO Why is maxRowCount ignored?
-      return new ExecuteResult(
-          Collections.singletonList(
-              MetaResultSet.create(
-                  statementHandle.connectionId,
-                  statementHandle.id,
-                  true,
-                  statementHandle.signature,
-                  null)));
-    }
+    return getPreparedStatement(statementHandle)
+        .executeWithTypedValues(statementHandle, typedValues, maxRowCount);
   }
 
   @Override
@@ -149,24 +80,8 @@ public class ArrowFlightMetaImpl extends MetaImpl {
   public ExecuteBatchResult executeBatch(
       final StatementHandle statementHandle, final List<List<TypedValue>> 
parameterValuesList)
       throws IllegalStateException {
-    Preconditions.checkArgument(
-        connection.id.equals(statementHandle.connectionId), "Connection IDs 
are not consistent");
-    PreparedStatement preparedStatement = 
getPreparedStatement(statementHandle);
-
-    if (preparedStatement == null) {
-      throw new IllegalStateException("Prepared statement not found: " + 
statementHandle);
-    }
-
-    final AvaticaParameterBinder binder =
-        new AvaticaParameterBinder(
-            preparedStatement, ((ArrowFlightConnection) 
connection).getBufferAllocator());
-    for (int i = 0; i < parameterValuesList.size(); i++) {
-      binder.bind(parameterValuesList.get(i), i);
-    }
-
-    // Update query
-    long[] updatedCounts = {preparedStatement.executeUpdate()};
-    return new ExecuteBatchResult(updatedCounts);
+    return getPreparedStatement(statementHandle)
+        .executeBatchWithTypedValues(statementHandle, parameterValuesList);
   }
 
   @Override
@@ -181,25 +96,20 @@ public class ArrowFlightMetaImpl extends MetaImpl {
         String.format("%s does not use frames.", this), 
AvaticaConnection.HELPER.unsupported());
   }
 
-  private PreparedStatement prepareForHandle(final String query, 
StatementHandle handle) {
-    final PreparedStatement preparedStatement =
-        ((ArrowFlightConnection) connection).getClientHandler().prepare(query);
-    handle.signature =
-        newSignature(
-            query,
-            preparedStatement.getDataSetSchema(),
-            preparedStatement.getParameterSchema(),
-            preparedStatement.isUpdate());
-    statementHandlePreparedStatementMap.put(new StatementHandleKey(handle), 
preparedStatement);
-    return preparedStatement;
-  }
-
   @Override
   public StatementHandle prepare(
       final ConnectionHandle connectionHandle, final String query, final long 
maxRowCount) {
-    final StatementHandle handle = super.createStatement(connectionHandle);
-    prepareForHandle(query, handle);
-    return handle;
+    validateConnectionId(connectionHandle.id);
+    try {
+      // This is the Avatica entry point used by 
Connection.prepareStatement(String).
+      ArrowFlightPreparedStatement stmt =
+          (ArrowFlightPreparedStatement)
+              connection.prepareStatement(
+                  query, ResultSet.TYPE_FORWARD_ONLY, 
ResultSet.CONCUR_READ_ONLY);
+      return stmt.handle;
+    } catch (SQLException e) {
+      throw new RuntimeException(e);
+    }
   }
 
   @Override
@@ -222,26 +132,18 @@ public class ArrowFlightMetaImpl extends MetaImpl {
       final PrepareCallback callback)
       throws NoSuchStatementException {
     try {
-      PreparedStatement preparedStatement = prepareForHandle(query, handle);
-      final StatementType statementType = preparedStatement.getType();
-
-      final long updateCount =
-          statementType.equals(StatementType.UPDATE) ? 
preparedStatement.executeUpdate() : -1;
-      synchronized (callback.getMonitor()) {
-        callback.clear();
-        callback.assign(handle.signature, null, updateCount);
+      final AvaticaStatement statement = getStatement(handle);
+      if (statement instanceof ArrowFlightStatement) {
+        return ((ArrowFlightStatement) statement)
+            .prepareAndExecuteInternal(query, maxRowCount, 
maxRowsInFirstFrame, callback);
       }
-      callback.execute();
-      final MetaResultSet metaResultSet =
-          MetaResultSet.create(handle.connectionId, handle.id, false, 
handle.signature, null);
-      return new ExecuteResult(Collections.singletonList(metaResultSet));
-    } catch (SQLTimeoutException e) {
-      // So far AvaticaStatement(executeInternal) only handles NoSuchStatement 
and
-      // Runtime
-      // Exceptions.
-      throw new RuntimeException(e);
+      return ((ArrowFlightPreparedStatement) statement)
+          .prepareAndExecuteInternal(query, maxRowCount, maxRowsInFirstFrame, 
callback);
     } catch (SQLException e) {
-      throw new NoSuchStatementException(handle);
+      // AvaticaStatement.executeInternal handles RuntimeException and 
preserves it as the cause of
+      // the public SQLException. NoSuchStatementException would incorrectly 
trigger a statement
+      // reset/retry and discard the actual server failure.
+      throw new RuntimeException(e.getMessage(), e);
     }
   }
 
@@ -291,45 +193,81 @@ public class ArrowFlightMetaImpl extends MetaImpl {
         .setTransactionIsolation(Connection.TRANSACTION_NONE);
   }
 
-  PreparedStatement getPreparedStatement(StatementHandle statementHandle) {
-    return statementHandlePreparedStatementMap.get(new 
StatementHandleKey(statementHandle));
+  private AvaticaStatement getStatement(final StatementHandle statementHandle) 
{
+    validateConnectionId(statementHandle.connectionId);
+    final AvaticaStatement statement = 
connection.statementMap.get(statementHandle.id);
+    if (statement instanceof ArrowFlightStatement
+        || statement instanceof ArrowFlightPreparedStatement) {
+      return statement;
+    }
+    throw new IllegalStateException("Statement not found: " + statementHandle);
   }
 
-  // Helper used to look up prepared statement instances later. Avatica doesn't
-  // give us the
-  // signature in
-  // an UPDATE code path so we can't directly use StatementHandle as a map key.
-  private static final class StatementHandleKey {
-    public final String connectionId;
-    public final int id;
-
-    StatementHandleKey(StatementHandle statementHandle) {
-      this.connectionId = statementHandle.connectionId;
-      this.id = statementHandle.id;
+  private ArrowFlightPreparedStatement getPreparedStatement(final 
StatementHandle statementHandle) {
+    final AvaticaStatement statement = getStatement(statementHandle);
+    if (statement instanceof ArrowFlightPreparedStatement) {
+      return (ArrowFlightPreparedStatement) statement;
     }
+    throw new IllegalStateException(
+        "Statement operation is not supported for handle: " + statementHandle);
+  }
 
-    @Override
-    public boolean equals(Object o) {
-      if (this == o) {
-        return true;
-      }
-      if (o == null || getClass() != o.getClass()) {
-        return false;
-      }
+  private void validateConnectionId(final String connectionId) {
+    Preconditions.checkArgument(
+        connection.id.equals(connectionId), "Connection IDs are not 
consistent");
+  }
 
-      StatementHandleKey that = (StatementHandleKey) o;
+  static Signature buildDefaultSignature() {
+    return buildSignature(null, StatementType.SELECT);
+  }
 
-      if (id != that.id) {
-        return false;
-      }
-      return connectionId.equals(that.connectionId);
-    }
+  static Signature buildSignature(final String sql, final StatementType type) {
+    return buildSignature(sql, null, null, type);
+  }
 
-    @Override
-    public int hashCode() {
-      int result = connectionId.hashCode();
-      result = 31 * result + id;
-      return result;
+  /** Builds an Avatica signature from Arrow result and parameter schemas. */
+  static Signature buildSignature(
+      final String sql, final Schema resultSetSchema, final Schema 
parameterSchema) {
+    return buildSignature(sql, resultSetSchema, parameterSchema, (Boolean) 
null);
+  }
+
+  /** Builds an Avatica signature, honoring the server-provided statement 
classification. */
+  static Signature buildSignature(
+      final String sql,
+      final Schema resultSetSchema,
+      final Schema parameterSchema,
+      final Boolean isUpdate) {
+    final StatementType statementType;
+    if (isUpdate != null) {
+      statementType = isUpdate ? StatementType.IS_DML : StatementType.SELECT;
+    } else {
+      statementType =
+          resultSetSchema == null || resultSetSchema.getFields().isEmpty()
+              ? StatementType.IS_DML
+              : StatementType.SELECT;
     }
+    return buildSignature(sql, resultSetSchema, parameterSchema, 
statementType);
+  }
+
+  private static Signature buildSignature(
+      final String sql,
+      final Schema resultSetSchema,
+      final Schema parameterSchema,
+      final StatementType statementType) {
+    List<ColumnMetaData> columnMetaData =
+        resultSetSchema == null
+            ? new ArrayList<>()
+            : 
ConvertUtils.convertArrowFieldsToColumnMetaDataList(resultSetSchema.getFields());
+    List<AvaticaParameter> parameters =
+        parameterSchema == null
+            ? new ArrayList<>()
+            : 
ConvertUtils.convertArrowFieldsToAvaticaParameters(parameterSchema.getFields());
+    return new Signature(
+        columnMetaData,
+        sql,
+        parameters,
+        Collections.emptyMap(),
+        null, // unnecessary, as SQL requests use ArrowFlightJdbcCursor
+        statementType);
   }
 }
diff --git 
a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightPreparedStatement.java
 
b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightPreparedStatement.java
index d7af6902f..30878ad8b 100644
--- 
a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightPreparedStatement.java
+++ 
b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightPreparedStatement.java
@@ -16,51 +16,49 @@
  */
 package org.apache.arrow.driver.jdbc;
 
-import java.sql.PreparedStatement;
 import java.sql.SQLException;
+import java.util.Collections;
+import java.util.List;
 import org.apache.arrow.driver.jdbc.client.ArrowFlightSqlClientHandler;
+import org.apache.arrow.driver.jdbc.utils.AvaticaParameterBinder;
 import org.apache.arrow.flight.FlightInfo;
+import org.apache.arrow.flight.FlightRuntimeException;
 import org.apache.arrow.util.Preconditions;
+import org.apache.arrow.vector.types.pojo.Schema;
 import org.apache.calcite.avatica.AvaticaPreparedStatement;
+import org.apache.calcite.avatica.AvaticaStatement;
+import org.apache.calcite.avatica.Meta.ExecuteBatchResult;
+import org.apache.calcite.avatica.Meta.ExecuteResult;
+import org.apache.calcite.avatica.Meta.MetaResultSet;
+import org.apache.calcite.avatica.Meta.PrepareCallback;
 import org.apache.calcite.avatica.Meta.Signature;
 import org.apache.calcite.avatica.Meta.StatementHandle;
+import org.apache.calcite.avatica.Meta.StatementType;
+import org.apache.calcite.avatica.remote.TypedValue;
 
-/** Arrow Flight JBCS's implementation {@link PreparedStatement}. */
+/** Arrow Flight JDBC's implementation {@link java.sql.PreparedStatement}. */
 public class ArrowFlightPreparedStatement extends AvaticaPreparedStatement
     implements ArrowFlightInfoStatement {
 
-  private final ArrowFlightSqlClientHandler.PreparedStatement 
preparedStatement;
+  private ArrowFlightSqlClientHandler.PreparedStatement preparedStatement;
 
   private ArrowFlightPreparedStatement(
       final ArrowFlightConnection connection,
-      final ArrowFlightSqlClientHandler.PreparedStatement preparedStatement,
       final StatementHandle handle,
       final Signature signature,
+      final ArrowFlightSqlClientHandler.PreparedStatement preparedStatement,
       final int resultSetType,
       final int resultSetConcurrency,
       final int resultSetHoldability)
       throws SQLException {
     super(connection, handle, signature, resultSetType, resultSetConcurrency, 
resultSetHoldability);
     this.preparedStatement = Preconditions.checkNotNull(preparedStatement);
+    this.handle.signature = signature;
+    setSignature(signature);
   }
 
-  static ArrowFlightPreparedStatement newPreparedStatement(
-      final ArrowFlightConnection connection,
-      final ArrowFlightSqlClientHandler.PreparedStatement preparedStmt,
-      final StatementHandle statementHandle,
-      final Signature signature,
-      final int resultSetType,
-      final int resultSetConcurrency,
-      final int resultSetHoldability)
-      throws SQLException {
-    return new ArrowFlightPreparedStatement(
-        connection,
-        preparedStmt,
-        statementHandle,
-        signature,
-        resultSetType,
-        resultSetConcurrency,
-        resultSetHoldability);
+  static Builder builder(final ArrowFlightConnection connection) {
+    return new Builder(connection);
   }
 
   @Override
@@ -68,14 +66,213 @@ public class ArrowFlightPreparedStatement extends 
AvaticaPreparedStatement
     return (ArrowFlightConnection) super.getConnection();
   }
 
+  ExecuteResult prepareAndExecuteInternal(final PrepareCallback callback) 
throws SQLException {
+    ensurePrepared();
+    final StatementType statementType = preparedStatement.getType();
+    final long updateCount =
+        statementType.equals(StatementType.UPDATE) ? 
preparedStatement.executeUpdate() : -1;
+    synchronized (callback.getMonitor()) {
+      callback.clear();
+      callback.assign(handle.signature, null, updateCount);
+    }
+    callback.execute();
+    final MetaResultSet metaResultSet =
+        MetaResultSet.create(handle.connectionId, handle.id, false, 
handle.signature, null);
+    return new ExecuteResult(Collections.singletonList(metaResultSet));
+  }
+
+  ExecuteResult prepareAndExecuteInternal(
+      final String query,
+      final long maxRowCount,
+      final int maxRowsInFirstFrame,
+      final PrepareCallback callback)
+      throws SQLException {
+
+    return ArrowFlightPreparedStatement.builder(getConnection())
+        .withQuery(query)
+        .withExistingStatement(this)
+        .build()
+        .prepareAndExecuteInternal(callback);
+  }
+
+  Schema getDataSetSchema() {
+    ensurePrepared();
+    return preparedStatement.getDataSetSchema();
+  }
+
   @Override
-  public synchronized void close() throws SQLException {
-    this.preparedStatement.close();
-    super.close();
+  protected void close_() {
+    RuntimeException closeFailure = null;
+    try {
+      super.close_();
+    } catch (final RuntimeException e) {
+      closeFailure = e;
+    }
+    try {
+      closePreparedResources();
+    } catch (final RuntimeException e) {
+      if (closeFailure == null) {
+        closeFailure = e;
+      } else {
+        closeFailure.addSuppressed(e);
+      }
+    }
+    ((ArrowFlightConnection) connection).unregisterStatementOwner(this);
+    if (closeFailure != null) {
+      throw closeFailure;
+    }
+  }
+
+  void closePreparedResources() {
+    final ArrowFlightSqlClientHandler.PreparedStatement statement = 
preparedStatement;
+    preparedStatement = null;
+    if (statement != null) {
+      statement.close();
+    }
+  }
+
+  ExecuteResult executeWithTypedValues(
+      final StatementHandle statementHandle,
+      final List<TypedValue> typedValues,
+      final long maxRowCount) {
+    ensurePrepared();
+    Preconditions.checkArgument(
+        connection.id.equals(statementHandle.connectionId), "Connection IDs 
are not consistent");
+    new AvaticaParameterBinder(
+            preparedStatement, ((ArrowFlightConnection) 
connection).getBufferAllocator())
+        .bind(typedValues);
+
+    if (statementHandle.signature == null
+        || statementHandle.signature.statementType == StatementType.IS_DML) {
+      long updatedCount = preparedStatement.executeUpdate();
+      return new ExecuteResult(
+          Collections.singletonList(
+              MetaResultSet.count(statementHandle.connectionId, 
statementHandle.id, updatedCount)));
+    }
+
+    // TODO Why is maxRowCount ignored?
+    return new ExecuteResult(
+        Collections.singletonList(
+            MetaResultSet.create(
+                statementHandle.connectionId,
+                statementHandle.id,
+                true,
+                statementHandle.signature,
+                null)));
+  }
+
+  ExecuteBatchResult executeBatchWithTypedValues(
+      final StatementHandle statementHandle, final List<List<TypedValue>> 
parameterValuesList) {
+    ensurePrepared();
+    Preconditions.checkArgument(
+        connection.id.equals(statementHandle.connectionId), "Connection IDs 
are not consistent");
+    final AvaticaParameterBinder binder =
+        new AvaticaParameterBinder(
+            preparedStatement, ((ArrowFlightConnection) 
connection).getBufferAllocator());
+    for (int i = 0; i < parameterValuesList.size(); i++) {
+      binder.bind(parameterValuesList.get(i), i);
+    }
+
+    long[] updatedCounts = {preparedStatement.executeUpdate()};
+    return new ExecuteBatchResult(updatedCounts);
   }
 
   @Override
   public FlightInfo executeFlightInfoQuery() throws SQLException {
+    ensurePrepared();
     return preparedStatement.executeQuery();
   }
+
+  private void ensurePrepared() {
+    if (preparedStatement == null) {
+      throw new IllegalStateException("PreparedStatement is already closed.");
+    }
+  }
+
+  static final class Builder {
+    private final ArrowFlightConnection connection;
+    private StatementHandle handle;
+    private String query;
+    private Integer resultSetType;
+    private Integer resultSetConcurrency;
+    private Integer resultSetHoldability;
+    private boolean generateHandle;
+
+    private Builder(final ArrowFlightConnection connection) {
+      this.connection = Preconditions.checkNotNull(connection);
+    }
+
+    Builder withQuery(final String query) {
+      this.query = Preconditions.checkNotNull(query);
+      return this;
+    }
+
+    Builder withGeneratedHandle() {
+      this.generateHandle = true;
+      this.handle = null;
+      return this;
+    }
+
+    Builder withExistingStatement(final AvaticaStatement statement) throws 
SQLException {
+      Preconditions.checkNotNull(statement);
+      this.generateHandle = false;
+      this.handle = Preconditions.checkNotNull(statement.handle);
+      this.resultSetType = statement.getResultSetType();
+      this.resultSetConcurrency = statement.getResultSetConcurrency();
+      this.resultSetHoldability = statement.getResultSetHoldability();
+      return this;
+    }
+
+    Builder withResultSetType(final int resultSetType) {
+      this.resultSetType = resultSetType;
+      return this;
+    }
+
+    Builder withResultSetConcurrency(final int resultSetConcurrency) {
+      this.resultSetConcurrency = resultSetConcurrency;
+      return this;
+    }
+
+    Builder withResultSetHoldability(final int resultSetHoldability) {
+      this.resultSetHoldability = resultSetHoldability;
+      return this;
+    }
+
+    ArrowFlightPreparedStatement build() throws SQLException {
+      Preconditions.checkNotNull(query);
+      Preconditions.checkNotNull(resultSetType);
+      Preconditions.checkNotNull(resultSetConcurrency);
+      Preconditions.checkNotNull(resultSetHoldability);
+      if (!generateHandle && handle == null) {
+        throw new IllegalStateException("PreparedStatement builder requires a 
handle.");
+      }
+
+      final ArrowFlightSqlClientHandler.PreparedStatement preparedStatement;
+      try {
+        preparedStatement = connection.getClientHandler().prepare(query);
+      } catch (final FlightRuntimeException e) {
+        throw new SQLException(e.getMessage(), e);
+      }
+      final Signature signature =
+          ArrowFlightMetaImpl.buildSignature(
+              query,
+              preparedStatement.getDataSetSchema(),
+              preparedStatement.getParameterSchema(),
+              preparedStatement.isUpdate());
+
+      final ArrowFlightPreparedStatement statement =
+          new ArrowFlightPreparedStatement(
+              connection,
+              generateHandle ? null : handle,
+              signature,
+              preparedStatement,
+              resultSetType,
+              resultSetConcurrency,
+              resultSetHoldability);
+      if (generateHandle) {
+        connection.registerStatementOwner(statement);
+      }
+      return statement;
+    }
+  }
 }
diff --git 
a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightStatement.java
 
b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightStatement.java
index ff3d060c5..eb170c18c 100644
--- 
a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightStatement.java
+++ 
b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightStatement.java
@@ -16,14 +16,21 @@
  */
 package org.apache.arrow.driver.jdbc;
 
+import java.sql.ResultSet;
 import java.sql.SQLException;
-import 
org.apache.arrow.driver.jdbc.client.ArrowFlightSqlClientHandler.PreparedStatement;
 import org.apache.arrow.driver.jdbc.utils.ConvertUtils;
 import org.apache.arrow.flight.FlightInfo;
+import org.apache.arrow.flight.FlightRuntimeException;
+import org.apache.arrow.flight.FlightStatusCode;
 import org.apache.arrow.vector.types.pojo.Schema;
+import org.apache.calcite.avatica.AvaticaConnection;
+import org.apache.calcite.avatica.AvaticaResultSet;
 import org.apache.calcite.avatica.AvaticaStatement;
 import org.apache.calcite.avatica.Meta;
+import org.apache.calcite.avatica.Meta.ExecuteResult;
+import org.apache.calcite.avatica.Meta.PrepareCallback;
 import org.apache.calcite.avatica.Meta.StatementHandle;
+import org.apache.calcite.avatica.Meta.StatementType;
 
 /** A SQL statement for querying data from an Arrow Flight server. */
 public class ArrowFlightStatement extends AvaticaStatement implements 
ArrowFlightInfoStatement {
@@ -35,6 +42,16 @@ public class ArrowFlightStatement extends AvaticaStatement 
implements ArrowFligh
       final int resultSetConcurrency,
       final int resultSetHoldability) {
     super(connection, handle, resultSetType, resultSetConcurrency, 
resultSetHoldability);
+    connection.registerStatementOwner(this);
+  }
+
+  @Override
+  protected void close_() {
+    try {
+      super.close_();
+    } finally {
+      ((ArrowFlightConnection) connection).unregisterStatementOwner(this);
+    }
   }
 
   @Override
@@ -42,21 +59,139 @@ public class ArrowFlightStatement extends AvaticaStatement 
implements ArrowFligh
     return (ArrowFlightConnection) super.getConnection();
   }
 
+  ExecuteResult prepareAndExecuteInternal(
+      final String query,
+      final long maxRowCount,
+      final int maxRowsInFirstFrame,
+      final PrepareCallback callback)
+      throws SQLException {
+    // Keep Avatica Statement.execute(String) behavior: Avatica calls 
Meta.prepareAndExecute,
+    // which resolves to this statement hook.
+    return ArrowFlightPreparedStatement.builder(getConnection())
+        .withQuery(query)
+        .withExistingStatement(this)
+        .build()
+        .prepareAndExecuteInternal(callback);
+  }
+
+  @Override
+  public ResultSet executeQuery(final String sql) throws SQLException {
+    checkOpen();
+    clearOpenResultSet();
+    updateCount = -1;
+    try {
+      switchToDirectStatementMode();
+      final Meta.Signature signature =
+          ArrowFlightMetaImpl.buildSignature(sql, StatementType.SELECT);
+      setSignature(signature);
+      return executeQueryInternal(signature, false);
+    } catch (Exception exception) {
+      throw wrapStatementExecutionException(sql, exception);
+    }
+  }
+
+  @Override
+  public long executeLargeUpdate(final String sql) throws SQLException {
+    checkOpen();
+    clearOpenResultSet();
+    updateCount = -1;
+
+    try {
+      switchToDirectStatementMode();
+      final long updatedCount = 
getConnection().getClientHandler().executeUpdate(sql);
+      setSignature(ArrowFlightMetaImpl.buildSignature(sql, 
StatementType.IS_DML));
+      updateCount = updatedCount;
+      return updatedCount;
+    } catch (Exception exception) {
+      throw wrapStatementExecutionException(sql, exception);
+    }
+  }
+
   @Override
   public FlightInfo executeFlightInfoQuery() throws SQLException {
-    final PreparedStatement preparedStatement =
-        getConnection().getMeta().getPreparedStatement(handle);
+    final ArrowFlightConnection connection = getConnection();
     final Meta.Signature signature = getSignature();
     if (signature == null) {
       return null;
     }
 
-    final Schema resultSetSchema = preparedStatement.getDataSetSchema();
-    signature.columns.clear();
-    signature.columns.addAll(
-        
ConvertUtils.convertArrowFieldsToColumnMetaDataList(resultSetSchema.getFields()));
-    setSignature(signature);
+    // A Statement handle can point to either this direct statement instance 
or a prepared
+    // statement instance created by Avatica Statement.execute(String) through
+    // Meta.prepareAndExecute.
+    final AvaticaStatement currentStatement = 
connection.statementMap.get(handle.id);
+    if (currentStatement instanceof ArrowFlightPreparedStatement) {
+      // Prepared path: reuse the current statement implementation associated 
with the handle.
+      final FlightInfo flightInfo =
+          ((ArrowFlightPreparedStatement) 
currentStatement).executeFlightInfoQuery();
+      updateSignatureColumnsFromFlightInfo(signature, flightInfo);
+      return flightInfo;
+    }
 
-    return preparedStatement.executeQuery();
+    // Direct Statement.executeQuery(String) / executeUpdate(String) path.
+    final FlightInfo flightInfo = 
connection.getClientHandler().getInfo(signature.sql);
+    updateSignatureColumnsFromFlightInfo(signature, flightInfo);
+    return flightInfo;
+  }
+
+  private void updateSignatureColumnsFromFlightInfo(
+      final Meta.Signature signature, final FlightInfo flightInfo) {
+    final Schema resultSetSchema = flightInfo.getSchemaOptional().orElse(null);
+    if (resultSetSchema != null) {
+      signature.columns.clear();
+      signature.columns.addAll(
+          
ConvertUtils.convertArrowFieldsToColumnMetaDataList(resultSetSchema.getFields()));
+      setSignature(signature);
+    }
+  }
+
+  private SQLException wrapStatementExecutionException(final String sql, final 
Exception exception)
+      throws SQLException {
+    if (!(exception instanceof SQLException)) {
+      return AvaticaConnection.HELPER.createException(
+          "Error while executing SQL \"" + sql + "\": " + 
exception.getMessage(), exception);
+    }
+    final SQLException sqlException = (SQLException) exception;
+    final String prefix = "Error while executing SQL \"" + sql + "\"";
+    final String message = sqlException.getMessage();
+    if (message != null && message.startsWith(prefix)) {
+      return sqlException;
+    }
+    final Throwable cause = sqlException.getCause();
+    if (cause instanceof FlightRuntimeException) {
+      final FlightStatusCode statusCode = ((FlightRuntimeException) 
cause).status().code();
+      if (statusCode == FlightStatusCode.UNAVAILABLE) {
+        return sqlException;
+      }
+    }
+    return AvaticaConnection.HELPER.createException(prefix + ": " + message, 
sqlException);
+  }
+
+  private void clearOpenResultSet() throws SQLException {
+    synchronized (this) {
+      if (openResultSet != null) {
+        final AvaticaResultSet resultSet = openResultSet;
+        openResultSet = null;
+        try {
+          resultSet.close();
+        } catch (Exception exception) {
+          throw AvaticaConnection.HELPER.createException(
+              "Error while closing previous result set", exception);
+        }
+      }
+    }
+  }
+
+  private void switchToDirectStatementMode() throws SQLException {
+    final ArrowFlightConnection connection = getConnection();
+    final AvaticaStatement existingStatement = 
connection.statementMap.get(handle.id);
+    if (existingStatement == this) {
+      return;
+    }
+    if (existingStatement instanceof ArrowFlightPreparedStatement) {
+      // Release resources from previously attached statement implementation 
before switching back
+      // to direct statement mode for executeQuery/executeUpdate.
+      ((ArrowFlightPreparedStatement) 
existingStatement).closePreparedResources();
+    }
+    connection.statementMap.put(handle.id, this);
   }
 }
diff --git 
a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java
 
b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java
index c49aa110f..716dc5057 100644
--- 
a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java
+++ 
b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java
@@ -268,6 +268,16 @@ public final class ArrowFlightSqlClientHandler implements 
AutoCloseable {
     return sqlClient.execute(query, getOptions());
   }
 
+  /**
+   * Executes an update query directly, without creating a prepared statement 
first.
+   *
+   * @param query The update query.
+   * @return the number of rows affected.
+   */
+  public long executeUpdate(final String query) {
+    return sqlClient.executeUpdate(query, getOptions());
+  }
+
   @Override
   public void close() throws SQLException {
     if (catalog.isPresent()) {
diff --git 
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcConnectionPoolDataSourceTest.java
 
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcConnectionPoolDataSourceTest.java
index 18ff45bbd..a2a789b69 100644
--- 
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcConnectionPoolDataSourceTest.java
+++ 
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcConnectionPoolDataSourceTest.java
@@ -22,10 +22,21 @@ import static org.junit.jupiter.api.Assertions.assertSame;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Collections;
 import javax.sql.PooledConnection;
 import org.apache.arrow.driver.jdbc.authentication.UserPasswordAuthentication;
 import org.apache.arrow.driver.jdbc.utils.ConnectionWrapper;
 import org.apache.arrow.driver.jdbc.utils.MockFlightSqlProducer;
+import org.apache.arrow.memory.BufferAllocator;
+import org.apache.arrow.memory.RootAllocator;
+import org.apache.arrow.vector.IntVector;
+import org.apache.arrow.vector.VectorSchemaRoot;
+import org.apache.arrow.vector.types.Types.MinorType;
+import org.apache.arrow.vector.types.pojo.Field;
+import org.apache.arrow.vector.types.pojo.Schema;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
@@ -33,6 +44,10 @@ import org.junit.jupiter.api.extension.RegisterExtension;
 
 public class ArrowFlightJdbcConnectionPoolDataSourceTest {
 
+  private static final String SELECT_QUERY = "SELECT * FROM 
POOLED_CONNECTION_RESET";
+  private static final Schema QUERY_SCHEMA =
+      new Schema(Collections.singletonList(Field.nullable("id", 
MinorType.INT.getType())));
+
   @RegisterExtension public static final FlightServerTestExtension 
FLIGHT_SERVER_TEST_EXTENSION;
 
   private static final MockFlightSqlProducer PRODUCER = new 
MockFlightSqlProducer();
@@ -49,6 +64,25 @@ public class ArrowFlightJdbcConnectionPoolDataSourceTest {
             .authentication(authentication)
             .producer(PRODUCER)
             .build();
+
+    PRODUCER.addSelectQuery(
+        SELECT_QUERY,
+        QUERY_SCHEMA,
+        Collections.singletonList(
+            listener -> {
+              try (final BufferAllocator allocator = new 
RootAllocator(Long.MAX_VALUE);
+                  final VectorSchemaRoot root = 
VectorSchemaRoot.create(QUERY_SCHEMA, allocator)) {
+                final IntVector vector = (IntVector) root.getVector("id");
+                vector.setSafe(0, 1);
+                root.setRowCount(1);
+                listener.start(root);
+                listener.putNext();
+              } catch (final Throwable throwable) {
+                listener.error(throwable);
+              } finally {
+                listener.completed();
+              }
+            }));
   }
 
   private ArrowFlightJdbcConnectionPoolDataSource dataSource;
@@ -79,6 +113,8 @@ public class ArrowFlightJdbcConnectionPoolDataSourceTest {
     assertFalse(connection.isClosed());
     connection.close();
     assertTrue(connection.isClosed());
+    connection.close();
+    assertTrue(connection.isClosed());
   }
 
   @Test
@@ -114,6 +150,70 @@ public class ArrowFlightJdbcConnectionPoolDataSourceTest {
         connection2.unwrap(ArrowFlightConnection.class));
   }
 
+  @Test
+  public void 
testShouldResetOpenStatementExecuteResultSetWhenReusingConnection() throws 
Exception {
+    final PooledConnection pooledConnection = 
dataSource.getPooledConnection("user1", "pass1");
+    final Connection connection;
+    try {
+      connection = pooledConnection.getConnection();
+    } catch (final SQLException e) {
+      closePooledConnectionAfterFailedCheckout(pooledConnection, e);
+      throw e;
+    }
+
+    try (connection) {
+      final ArrowFlightConnection physicalConnection =
+          connection.unwrap(ArrowFlightConnection.class);
+      final Statement statement = connection.createStatement();
+      assertTrue(statement.execute(SELECT_QUERY));
+      final ResultSet resultSet = statement.getResultSet();
+
+      assertFalse(statement.isClosed());
+      assertFalse(resultSet.isClosed());
+      connection.close();
+      assertFalse(statement.isClosed());
+      assertFalse(resultSet.isClosed());
+
+      final PooledConnection reusedPooledConnection;
+      try {
+        reusedPooledConnection = dataSource.getPooledConnection("user1", 
"pass1");
+      } catch (final SQLException e) {
+        closePooledConnectionAfterFailedCheckout(pooledConnection, e);
+        throw e;
+      }
+
+      final Connection reusedConnection;
+      try {
+        reusedConnection = reusedPooledConnection.getConnection();
+      } catch (final SQLException e) {
+        closePooledConnectionAfterFailedCheckout(reusedPooledConnection, e);
+        throw e;
+      }
+
+      try (reusedConnection) {
+        assertSame(pooledConnection, reusedPooledConnection);
+        assertSame(physicalConnection, 
reusedConnection.unwrap(ArrowFlightConnection.class));
+        assertTrue(statement.isClosed());
+        assertTrue(resultSet.isClosed());
+        assertFalse(reusedConnection.isClosed());
+
+        try (Statement reusedStatement = reusedConnection.createStatement();
+            ResultSet reusedResultSet = 
reusedStatement.executeQuery(SELECT_QUERY)) {
+          assertTrue(reusedResultSet.next());
+        }
+      }
+    }
+  }
+
+  private static void closePooledConnectionAfterFailedCheckout(
+      final PooledConnection pooledConnection, final SQLException failure) {
+    try {
+      pooledConnection.close();
+    } catch (final SQLException closeFailure) {
+      failure.addSuppressed(closeFailure);
+    }
+  }
+
   @Test
   public void testShouldNotMixConnectionsForDifferentUsers() throws Exception {
     PooledConnection pooledConnection = 
dataSource.getPooledConnection("user1", "pass1");
diff --git 
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSetTest.java
 
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSetTest.java
new file mode 100644
index 000000000..7c8f53ea3
--- /dev/null
+++ 
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSetTest.java
@@ -0,0 +1,86 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.arrow.driver.jdbc;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
+import java.sql.SQLException;
+import java.util.AbstractList;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import org.apache.arrow.driver.jdbc.client.CloseableEndpointStreamPair;
+import org.apache.arrow.driver.jdbc.utils.FlightEndpointDataQueue;
+import org.apache.arrow.flight.FlightStream;
+import org.junit.jupiter.api.Test;
+
+public class ArrowFlightJdbcFlightStreamResultSetTest {
+
+  @Test
+  public void 
testClosedQueueDuringCollectionHandoffClosesUnacceptedEndpoints() throws 
Exception {
+    final FlightStream acceptedStream = mock(FlightStream.class);
+    final FlightStream rejectedStream = mock(FlightStream.class);
+    final FlightStream unacceptedStream = mock(FlightStream.class);
+    final List<CloseableEndpointStreamPair> endpoints =
+        List.of(
+            new CloseableEndpointStreamPair(acceptedStream, null),
+            new CloseableEndpointStreamPair(rejectedStream, null),
+            new CloseableEndpointStreamPair(unacceptedStream, null));
+    final Exception closeFailure = new Exception("Failed to close rejected 
endpoint");
+    doThrow(closeFailure).when(rejectedStream).close();
+    final ExecutorService executor = Executors.newSingleThreadExecutor();
+    try (final FlightEndpointDataQueue queue = 
FlightEndpointDataQueue.createNewQueue(executor)) {
+      final List<CloseableEndpointStreamPair> closingEndpoints =
+          new AbstractList<>() {
+            @Override
+            public CloseableEndpointStreamPair get(final int index) {
+              if (index == 1) {
+                // Close between handing off the first and second endpoint.
+                assertDoesNotThrow(queue::close);
+              }
+              return endpoints.get(index);
+            }
+
+            @Override
+            public int size() {
+              return endpoints.size();
+            }
+          };
+      final SQLException exception =
+          assertThrows(
+              SQLException.class,
+              () ->
+                  ArrowFlightJdbcFlightStreamResultSet.enqueueEndpointData(
+                      queue, closingEndpoints));
+
+      assertEquals("Statement canceled", exception.getMessage());
+      assertEquals(1, exception.getSuppressed().length);
+      assertSame(closeFailure, exception.getSuppressed()[0]);
+      verify(acceptedStream).close();
+      verify(rejectedStream).close();
+      verify(unacceptedStream).close();
+    } finally {
+      executor.shutdownNow();
+    }
+  }
+}
diff --git 
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightPreparedStatementTest.java
 
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightPreparedStatementTest.java
index 73ece4640..f3de2b67f 100644
--- 
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightPreparedStatementTest.java
+++ 
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightPreparedStatementTest.java
@@ -17,10 +17,13 @@
 package org.apache.arrow.driver.jdbc;
 
 import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.instanceOf;
 import static org.hamcrest.MatcherAssert.assertThat;
 import static org.junit.jupiter.api.Assertions.assertAll;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
+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 java.nio.charset.StandardCharsets;
@@ -33,8 +36,10 @@ import java.time.LocalDate;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
+import java.util.TimeZone;
 import org.apache.arrow.driver.jdbc.utils.CoreMockedSqlProducers;
 import org.apache.arrow.driver.jdbc.utils.MockFlightSqlProducer;
+import org.apache.arrow.flight.FlightRuntimeException;
 import org.apache.arrow.flight.sql.FlightSqlUtils;
 import org.apache.arrow.memory.BufferAllocator;
 import org.apache.arrow.memory.RootAllocator;
@@ -47,6 +52,10 @@ import org.apache.arrow.vector.types.pojo.Field;
 import org.apache.arrow.vector.types.pojo.FieldType;
 import org.apache.arrow.vector.types.pojo.Schema;
 import org.apache.arrow.vector.util.Text;
+import org.apache.calcite.avatica.AvaticaResultSet;
+import org.apache.calcite.avatica.AvaticaStatement;
+import org.apache.calcite.avatica.Meta;
+import org.apache.calcite.avatica.QueryState;
 import org.junit.jupiter.api.AfterAll;
 import org.junit.jupiter.api.BeforeAll;
 import org.junit.jupiter.api.BeforeEach;
@@ -135,6 +144,138 @@ public class ArrowFlightPreparedStatementTest {
     }
   }
 
+  @Test
+  public void testConnectionCloseClosesPreparedStatementAndResultSet() throws 
SQLException {
+    try (final Connection localConnection = 
FLIGHT_SERVER_TEST_EXTENSION.getConnection(false);
+        final PreparedStatement preparedStatement =
+            
localConnection.prepareStatement(CoreMockedSqlProducers.LEGACY_REGULAR_SQL_CMD);
+        final ResultSet resultSet = preparedStatement.executeQuery()) {
+      assertTrue(resultSet.next());
+
+      localConnection.close();
+
+      assertTrue(preparedStatement.isClosed());
+      assertTrue(resultSet.isClosed());
+      assertEquals(
+          1,
+          PRODUCER
+              .getActionTypeCounter()
+              
.getOrDefault(FlightSqlUtils.FLIGHT_SQL_CLOSE_PREPARED_STATEMENT.getType(), 0));
+    }
+  }
+
+  @Test
+  public void testPrepareFailureIsReportedAsSQLException() {
+    final SQLException exception =
+        assertThrows(
+            SQLException.class,
+            () -> connection.prepareStatement("SELECT * FROM 
unregistered_table"));
+
+    assertThat(exception.getCause(), instanceOf(FlightRuntimeException.class));
+  }
+
+  @Test
+  public void testNullQueryIsReportedAsSQLException() {
+    assertThrows(SQLException.class, () -> connection.prepareStatement(null));
+  }
+
+  @Test
+  public void testCloseReleasesPreparedResourcesWhenResultSetCloseFails() 
throws Exception {
+    final RuntimeException resultSetCloseFailure = new 
RuntimeException("Result set close failed");
+    final ArrowFlightJdbcFactory factory =
+        new ArrowFlightJdbcFactory() {
+          @Override
+          public ArrowFlightJdbcVectorSchemaRootResultSet newResultSet(
+              final AvaticaStatement statement,
+              final QueryState state,
+              final Meta.Signature signature,
+              final TimeZone timeZone,
+              final Meta.Frame frame)
+              throws SQLException {
+            return new ArrowFlightJdbcVectorSchemaRootResultSet(
+                statement,
+                state,
+                signature,
+                newResultSetMetaData(statement, signature),
+                timeZone,
+                frame) {
+              @Override
+              protected AvaticaResultSet execute() {
+                populateData(VectorSchemaRoot.of());
+                return this;
+              }
+
+              @Override
+              public void close() {
+                super.close();
+                throw resultSetCloseFailure;
+              }
+            };
+          }
+        };
+    try (final Connection localConnection =
+            factory.newConnection(
+                new ArrowFlightJdbcDriver(),
+                factory,
+                connection.getMetaData().getURL(),
+                connection.getClientInfo());
+        final PreparedStatement preparedStatement =
+            
localConnection.prepareStatement(CoreMockedSqlProducers.LEGACY_REGULAR_SQL_CMD))
 {
+      final ResultSet resultSet = preparedStatement.executeQuery();
+
+      final SQLException exception = assertThrows(SQLException.class, 
preparedStatement::close);
+
+      assertSame(resultSetCloseFailure, exception.getCause());
+      assertTrue(preparedStatement.isClosed());
+      assertTrue(resultSet.isClosed());
+      assertEquals(
+          1,
+          PRODUCER
+              .getActionTypeCounter()
+              
.getOrDefault(FlightSqlUtils.FLIGHT_SQL_CLOSE_PREPARED_STATEMENT.getType(), 0));
+    }
+  }
+
+  @Test
+  public void testMetaRejectsForeignStatementHandle() throws SQLException {
+    try (final ArrowFlightConnection firstConnection =
+            (ArrowFlightConnection) 
FLIGHT_SERVER_TEST_EXTENSION.getConnection(false);
+        final ArrowFlightConnection secondConnection =
+            (ArrowFlightConnection) 
FLIGHT_SERVER_TEST_EXTENSION.getConnection(false);
+        final PreparedStatement firstStatement =
+            
firstConnection.prepareStatement(CoreMockedSqlProducers.LEGACY_REGULAR_SQL_CMD);
+        final PreparedStatement secondStatement =
+            secondConnection.prepareStatement(
+                CoreMockedSqlProducers.UUID_PREPARED_SELECT_SQL_CMD)) {
+      final ArrowFlightPreparedStatement firstPreparedStatement =
+          (ArrowFlightPreparedStatement) firstStatement;
+      final ArrowFlightPreparedStatement secondPreparedStatement =
+          (ArrowFlightPreparedStatement) secondStatement;
+      assertEquals(firstPreparedStatement.handle.id, 
secondPreparedStatement.handle.id);
+
+      assertThrows(
+          IllegalArgumentException.class,
+          () -> 
firstConnection.getMeta().closeStatement(secondPreparedStatement.handle));
+      assertFalse(firstPreparedStatement.isClosed());
+    }
+  }
+
+  @Test
+  public void testMetaRejectsForeignConnectionHandle() throws SQLException {
+    try (final ArrowFlightConnection firstConnection =
+            (ArrowFlightConnection) 
FLIGHT_SERVER_TEST_EXTENSION.getConnection(false);
+        final ArrowFlightConnection secondConnection =
+            (ArrowFlightConnection) 
FLIGHT_SERVER_TEST_EXTENSION.getConnection(false)) {
+      assertThrows(
+          IllegalArgumentException.class,
+          () ->
+              firstConnection
+                  .getMeta()
+                  .prepare(
+                      secondConnection.handle, 
CoreMockedSqlProducers.LEGACY_REGULAR_SQL_CMD, -1));
+    }
+  }
+
   @Test
   public void testQueryWithParameterBinding() throws SQLException {
     final String query = "Fake query with parameters";
@@ -177,8 +318,9 @@ public class ArrowFlightPreparedStatementTest {
           2, connection.createArrayOf("INTEGER", new Integer[] {1, 2, null}));
 
       try (final ResultSet resultSet = preparedStatement.executeQuery()) {
-        resultSet.next();
-        assert true;
+        assertTrue(resultSet.next());
+        assertEquals(10, resultSet.getInt(1));
+        assertFalse(resultSet.next());
       }
     }
   }
@@ -220,8 +362,9 @@ public class ArrowFlightPreparedStatementTest {
       preparedStatement.setDate(1, Date.valueOf(date));
 
       try (final ResultSet resultSet = preparedStatement.executeQuery()) {
-        resultSet.next();
-        assert true;
+        assertTrue(resultSet.next());
+        assertEquals(10, resultSet.getInt(1));
+        assertFalse(resultSet.next());
       }
     }
   }
diff --git 
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightStatementExecuteTest.java
 
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightStatementExecuteTest.java
index 6acce9c2a..602ffdc6f 100644
--- 
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightStatementExecuteTest.java
+++ 
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightStatementExecuteTest.java
@@ -17,11 +17,14 @@
 package org.apache.arrow.driver.jdbc;
 
 import static org.hamcrest.CoreMatchers.allOf;
+import static org.hamcrest.CoreMatchers.containsString;
 import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.instanceOf;
 import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.not;
 import static org.hamcrest.CoreMatchers.nullValue;
 import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 
 import java.sql.Connection;
 import java.sql.ResultSet;
@@ -33,6 +36,9 @@ import java.util.Set;
 import java.util.stream.Collectors;
 import java.util.stream.IntStream;
 import org.apache.arrow.driver.jdbc.utils.MockFlightSqlProducer;
+import org.apache.arrow.flight.CallStatus;
+import org.apache.arrow.flight.FlightRuntimeException;
+import org.apache.arrow.flight.sql.FlightSqlUtils;
 import org.apache.arrow.memory.BufferAllocator;
 import org.apache.arrow.memory.RootAllocator;
 import org.apache.arrow.util.AutoCloseables;
@@ -41,7 +47,6 @@ import org.apache.arrow.vector.VectorSchemaRoot;
 import org.apache.arrow.vector.types.Types.MinorType;
 import org.apache.arrow.vector.types.pojo.Field;
 import org.apache.arrow.vector.types.pojo.Schema;
-import org.apache.calcite.avatica.AvaticaUtils;
 import org.junit.jupiter.api.AfterAll;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeAll;
@@ -165,6 +170,96 @@ public class ArrowFlightStatementExecuteTest {
         is(allOf(equalTo(statement.getLargeUpdateCount()), equalTo(-1L))));
   }
 
+  @Test
+  public void testExecutePrepareFailurePreservesServerError() {
+    final SQLException exception =
+        assertThrows(
+            SQLException.class, () -> statement.execute("SELECT * FROM 
unregistered_table"));
+
+    assertThat(exception.getMessage(), containsString("Query not found"));
+  }
+
+  @Test
+  public void testConnectionCloseClosesStatementAndResultSetAfterExecute() 
throws SQLException {
+    PRODUCER.clearActionTypeCounter();
+
+    assertThat(statement.execute(SAMPLE_QUERY_CMD), is(true));
+    final ResultSet resultSet = statement.getResultSet();
+    assertNotNull(resultSet);
+
+    connection.close();
+
+    assertThat(statement.isClosed(), is(true));
+    assertThat(resultSet.isClosed(), is(true));
+    assertThat(
+        PRODUCER
+            .getActionTypeCounter()
+            
.getOrDefault(FlightSqlUtils.FLIGHT_SQL_CLOSE_PREPARED_STATEMENT.getType(), 0),
+        is(1));
+  }
+
+  @Test
+  public void testExecuteQueryReplacesResultSetAndRemainsConnectionOwned() 
throws SQLException {
+    assertThat(statement.execute(SAMPLE_QUERY_CMD), is(true));
+    final ResultSet previousResultSet = statement.getResultSet();
+
+    try (ResultSet resultSet = statement.executeQuery(SAMPLE_QUERY_CMD)) {
+      assertThat(previousResultSet.isClosed(), is(true));
+      assertThat(resultSet.next(), is(true));
+      assertThat(resultSet.getByte(1), is((byte) 0));
+
+      connection.close();
+
+      assertThat(statement.isClosed(), is(true));
+      assertThat(resultSet.isClosed(), is(true));
+    }
+  }
+
+  @Test
+  public void testExecuteQueryMapsPreparedStatementCloseFailureToSQLException()
+      throws SQLException {
+    assertThat(statement.execute(SAMPLE_QUERY_CMD), is(true));
+    final ResultSet previousResultSet = statement.getResultSet();
+    PRODUCER.setClosePreparedStatementFailure(
+        CallStatus.INTERNAL.withDescription("Prepared statement close 
failed"));
+
+    try {
+      final SQLException exception =
+          assertThrows(SQLException.class, () -> 
statement.executeQuery(SAMPLE_QUERY_CMD));
+
+      assertThat(exception.getCause(), 
instanceOf(FlightRuntimeException.class));
+      final FlightRuntimeException cause = (FlightRuntimeException) 
exception.getCause();
+      assertThat(cause.status().code(), is(CallStatus.INTERNAL.code()));
+      assertThat(cause.status().description(), containsString("Prepared 
statement close failed"));
+      assertThat(previousResultSet.isClosed(), is(true));
+    } finally {
+      PRODUCER.setClosePreparedStatementFailure(null);
+    }
+  }
+
+  @Test
+  public void 
testExecuteLargeUpdateMapsPreparedStatementCloseFailureToSQLException()
+      throws SQLException {
+    assertThat(statement.execute(SAMPLE_QUERY_CMD), is(true));
+    final ResultSet previousResultSet = statement.getResultSet();
+    PRODUCER.setClosePreparedStatementFailure(
+        CallStatus.INTERNAL.withDescription("Prepared statement close 
failed"));
+
+    try {
+      final SQLException exception =
+          assertThrows(
+              SQLException.class, () -> 
statement.executeLargeUpdate(SAMPLE_LARGE_UPDATE_QUERY));
+
+      assertThat(exception.getCause(), 
instanceOf(FlightRuntimeException.class));
+      final FlightRuntimeException cause = (FlightRuntimeException) 
exception.getCause();
+      assertThat(cause.status().code(), is(CallStatus.INTERNAL.code()));
+      assertThat(cause.status().description(), containsString("Prepared 
statement close failed"));
+      assertThat(previousResultSet.isClosed(), is(true));
+    } finally {
+      PRODUCER.setClosePreparedStatementFailure(null);
+    }
+  }
+
   @Test
   public void testExecuteShouldRunUpdateQueryForSmallUpdate() throws 
SQLException {
     assertThat(statement.execute(SAMPLE_UPDATE_QUERY), is(false)); // Means 
this is an UPDATE query.
@@ -180,12 +275,7 @@ public class ArrowFlightStatementExecuteTest {
     final long updateCountSmall = statement.getUpdateCount();
     final long updateCountLarge = statement.getLargeUpdateCount();
     assertThat(updateCountLarge, is(equalTo(SAMPLE_LARGE_UPDATE_COUNT)));
-    assertThat(
-        updateCountSmall,
-        is(
-            allOf(
-                equalTo((long) AvaticaUtils.toSaturatedInt(updateCountLarge)),
-                not(equalTo(updateCountLarge)))));
+    assertThat(updateCountSmall, is((long) Integer.MAX_VALUE));
     assertThat(statement.getResultSet(), is(nullValue()));
   }
 
@@ -226,12 +316,7 @@ public class ArrowFlightStatementExecuteTest {
     final long updateCountSmall = statement.getUpdateCount();
     final long updateCountLarge = statement.getLargeUpdateCount();
     assertThat(updateCountLarge, is(equalTo(SAMPLE_LARGE_UPDATE_COUNT)));
-    assertThat(
-        updateCountSmall,
-        is(
-            allOf(
-                equalTo((long) AvaticaUtils.toSaturatedInt(updateCountLarge)),
-                not(equalTo(updateCountLarge)))));
+    assertThat(updateCountSmall, is((long) Integer.MAX_VALUE));
     assertThat(statement.getResultSet(), is(nullValue()));
   }
 }
diff --git 
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightStatementExecuteUpdateTest.java
 
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightStatementExecuteUpdateTest.java
index f7c31c590..23b660aad 100644
--- 
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightStatementExecuteUpdateTest.java
+++ 
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightStatementExecuteUpdateTest.java
@@ -17,11 +17,9 @@
 package org.apache.arrow.driver.jdbc;
 
 import static java.lang.String.format;
-import static org.hamcrest.CoreMatchers.allOf;
-import static org.hamcrest.CoreMatchers.equalTo;
 import static org.hamcrest.CoreMatchers.instanceOf;
 import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.CoreMatchers.startsWith;
 import static org.hamcrest.MatcherAssert.assertThat;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 
@@ -38,7 +36,6 @@ import org.apache.arrow.vector.VectorSchemaRoot;
 import org.apache.arrow.vector.types.Types.MinorType;
 import org.apache.arrow.vector.types.pojo.Field;
 import org.apache.arrow.vector.types.pojo.Schema;
-import org.apache.calcite.avatica.AvaticaUtils;
 import org.junit.jupiter.api.AfterAll;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeAll;
@@ -115,16 +112,7 @@ public class ArrowFlightStatementExecuteUpdateTest {
   public void 
testExecuteUpdateShouldReturnSaturatedNumColsAffectedIfDoesNotFitInInt()
       throws SQLException {
     final long result = statement.executeUpdate(LARGE_UPDATE_SAMPLE_QUERY);
-    final long expectedRowCountRaw = LARGE_UPDATE_SAMPLE_QUERY_AFFECTED_COLS;
-    assertThat(
-        result,
-        is(
-            allOf(
-                not(equalTo(expectedRowCountRaw)),
-                equalTo(
-                    (long)
-                        AvaticaUtils.toSaturatedInt(
-                            expectedRowCountRaw))))); // Because of 
long-to-integer overflow.
+    assertThat(result, is((long) Integer.MAX_VALUE));
   }
 
   @Test
@@ -224,4 +212,13 @@ public class ArrowFlightStatementExecuteUpdateTest {
     }
     assertThat(count, is(1));
   }
+
+  @Test
+  public void testExecuteLargeUpdateShouldWrapBadStatement() {
+    final String badQuery = "BAD INVALID UPDATE";
+    final SQLException exception =
+        assertThrows(SQLException.class, () -> 
statement.executeLargeUpdate(badQuery));
+    assertThat(
+        exception.getMessage(), startsWith(format("Error while executing SQL 
\"%s\"", badQuery)));
+  }
 }
diff --git 
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightStatementProtocolTest.java
 
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightStatementProtocolTest.java
new file mode 100644
index 000000000..58a607067
--- /dev/null
+++ 
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightStatementProtocolTest.java
@@ -0,0 +1,539 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.arrow.driver.jdbc;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import com.google.protobuf.Message;
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Collections;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Consumer;
+import org.apache.arrow.driver.jdbc.utils.MockFlightSqlProducer;
+import org.apache.arrow.flight.FlightProducer.ServerStreamListener;
+import org.apache.arrow.flight.sql.FlightSqlProducer.Schemas;
+import org.apache.arrow.flight.sql.FlightSqlUtils;
+import org.apache.arrow.flight.sql.impl.FlightSql.CommandGetDbSchemas;
+import org.apache.arrow.memory.BufferAllocator;
+import org.apache.arrow.memory.RootAllocator;
+import org.apache.arrow.util.AutoCloseables;
+import org.apache.arrow.vector.IntVector;
+import org.apache.arrow.vector.VarCharVector;
+import org.apache.arrow.vector.VectorSchemaRoot;
+import org.apache.arrow.vector.types.Types.MinorType;
+import org.apache.arrow.vector.types.pojo.Field;
+import org.apache.arrow.vector.types.pojo.Schema;
+import org.apache.arrow.vector.util.Text;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+public class ArrowFlightStatementProtocolTest {
+  private static final String SELECT_QUERY = "SELECT * FROM PROTOCOL_SELECT";
+  private static final String UPDATE_QUERY = "UPDATE PROTOCOL_UPDATE";
+  private static final Schema QUERY_SCHEMA =
+      new Schema(Collections.singletonList(Field.nullable("id", 
MinorType.INT.getType())));
+
+  private static final MockFlightSqlProducer PRODUCER = new 
MockFlightSqlProducer();
+
+  @RegisterExtension
+  public static final FlightServerTestExtension FLIGHT_SERVER_TEST_EXTENSION =
+      FlightServerTestExtension.createStandardTestExtension(PRODUCER);
+
+  private Connection connection;
+
+  @BeforeAll
+  public static void setUpBeforeClass() {
+    PRODUCER.addSelectQuery(
+        SELECT_QUERY,
+        QUERY_SCHEMA,
+        Collections.singletonList(
+            listener -> {
+              try (final BufferAllocator allocator = new 
RootAllocator(Long.MAX_VALUE);
+                  final VectorSchemaRoot root = 
VectorSchemaRoot.create(QUERY_SCHEMA, allocator)) {
+                IntVector vector = (IntVector) root.getVector("id");
+                vector.setSafe(0, 1);
+                root.setRowCount(1);
+                listener.start(root);
+                listener.putNext();
+              } catch (final Throwable throwable) {
+                listener.error(throwable);
+              } finally {
+                listener.completed();
+              }
+            }));
+    PRODUCER.addUpdateQuery(UPDATE_QUERY, 1);
+
+    final Message commandGetDbSchemas = 
CommandGetDbSchemas.getDefaultInstance();
+    final Consumer<ServerStreamListener> commandGetSchemasResultProducer =
+        listener -> {
+          try (final BufferAllocator allocator = new 
RootAllocator(Long.MAX_VALUE);
+              final VectorSchemaRoot root =
+                  VectorSchemaRoot.create(Schemas.GET_SCHEMAS_SCHEMA, 
allocator)) {
+            final VarCharVector catalogName = (VarCharVector) 
root.getVector("catalog_name");
+            final VarCharVector schemaName = (VarCharVector) 
root.getVector("db_schema_name");
+            catalogName.setSafe(0, new Text("catalog_name #0"));
+            schemaName.setSafe(0, new Text("db_schema_name #0"));
+            root.setRowCount(1);
+            listener.start(root);
+            listener.putNext();
+          } catch (final Throwable throwable) {
+            listener.error(throwable);
+          } finally {
+            listener.completed();
+          }
+        };
+    PRODUCER.addCatalogQuery(commandGetDbSchemas, 
commandGetSchemasResultProducer);
+  }
+
+  @BeforeEach
+  public void setUp() throws SQLException {
+    PRODUCER.clearActionTypeCounter();
+    PRODUCER.clearCommandTypeCounter();
+    connection = FLIGHT_SERVER_TEST_EXTENSION.getConnection(false);
+  }
+
+  @AfterEach
+  public void tearDown() throws Exception {
+    AutoCloseables.close(connection);
+  }
+
+  @AfterAll
+  public static void tearDownAfterClass() throws Exception {
+    AutoCloseables.close(PRODUCER);
+  }
+
+  @Test
+  public void testCancelWhileNextIsBlockedReportsSQLException() throws 
Exception {
+    final String query = "SELECT * FROM BLOCKED_CANCELLATION";
+    final int endpointCount = 8;
+    final CountDownLatch streamsStarted = new CountDownLatch(endpointCount);
+    final CountDownLatch releaseStreams = new CountDownLatch(1);
+    PRODUCER.addSelectQuery(
+        query,
+        QUERY_SCHEMA,
+        Collections.nCopies(
+            endpointCount,
+            listener -> {
+              try (final BufferAllocator allocator = new 
RootAllocator(Long.MAX_VALUE);
+                  final VectorSchemaRoot root = 
VectorSchemaRoot.create(QUERY_SCHEMA, allocator)) {
+                ((IntVector) root.getVector("id")).setSafe(0, 1);
+                root.setRowCount(1);
+                listener.start(root);
+                listener.putNext();
+                streamsStarted.countDown();
+                assertTrue(releaseStreams.await(10, TimeUnit.SECONDS), "Stream 
was not released");
+              } catch (final Throwable throwable) {
+                listener.error(throwable);
+              } finally {
+                listener.completed();
+              }
+            }));
+
+    try (Statement statement = connection.createStatement();
+        ResultSet resultSet = statement.executeQuery(query)) {
+      assertTrue(streamsStarted.await(5, TimeUnit.SECONDS), "Streams did not 
start");
+      assertTrue(resultSet.next());
+      final AtomicReference<Throwable> readerFailure = new AtomicReference<>();
+      final Thread reader =
+          new Thread(
+              () -> {
+                try {
+                  resultSet.next();
+                } catch (final Throwable throwable) {
+                  readerFailure.set(throwable);
+                }
+              },
+              "blocked-result-set-reader");
+      reader.start();
+      try {
+        final long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
+        while (reader.isAlive()
+            && reader.getState() != Thread.State.WAITING
+            && System.nanoTime() < deadline) {
+          Thread.sleep(1);
+        }
+        assertEquals(Thread.State.WAITING, reader.getState(), "Reader did not 
block");
+
+        statement.cancel();
+        reader.join(5000);
+
+        assertFalse(reader.isAlive(), "Reader did not observe cancellation");
+        final SQLException exception = assertInstanceOf(SQLException.class, 
readerFailure.get());
+        assertEquals("Statement canceled", exception.getMessage());
+      } finally {
+        releaseStreams.countDown();
+        reader.interrupt();
+        reader.join(5000);
+      }
+    } finally {
+      releaseStreams.countDown();
+    }
+  }
+
+  @Test
+  public void testStatementExecuteQueryUsesStatementProtocol() throws 
SQLException {
+    try (Statement statement = connection.createStatement();
+        ResultSet resultSet = statement.executeQuery(SELECT_QUERY)) {
+      assertTrue(resultSet.next());
+    }
+
+    assertThat(
+        PRODUCER
+            .getActionTypeCounter()
+            
.getOrDefault(FlightSqlUtils.FLIGHT_SQL_CREATE_PREPARED_STATEMENT.getType(), 0),
+        is(0));
+    assertThat(
+        PRODUCER
+            .getCommandTypeCounter()
+            .getOrDefault(MockFlightSqlProducer.COMMAND_STATEMENT_QUERY, 0),
+        is(1));
+    assertThat(
+        PRODUCER
+            .getCommandTypeCounter()
+            
.getOrDefault(MockFlightSqlProducer.COMMAND_PREPARED_STATEMENT_QUERY, 0),
+        is(0));
+  }
+
+  @Test
+  public void testStatementExecuteUsesPreparedProtocolForQuery() throws 
SQLException {
+    try (Statement statement = connection.createStatement()) {
+      assertThat(statement.execute(SELECT_QUERY), is(true));
+      try (ResultSet resultSet = statement.getResultSet()) {
+        assertTrue(resultSet.next());
+      }
+    }
+
+    assertThat(
+        PRODUCER
+            .getActionTypeCounter()
+            
.getOrDefault(FlightSqlUtils.FLIGHT_SQL_CREATE_PREPARED_STATEMENT.getType(), 0),
+        is(1));
+    assertThat(
+        PRODUCER
+            .getCommandTypeCounter()
+            
.getOrDefault(MockFlightSqlProducer.COMMAND_PREPARED_STATEMENT_QUERY, 0),
+        is(1));
+    assertThat(
+        PRODUCER
+            .getCommandTypeCounter()
+            .getOrDefault(MockFlightSqlProducer.COMMAND_STATEMENT_QUERY, 0),
+        is(0));
+    assertThat(
+        PRODUCER
+            .getActionTypeCounter()
+            
.getOrDefault(FlightSqlUtils.FLIGHT_SQL_CLOSE_PREPARED_STATEMENT.getType(), 0),
+        is(1));
+  }
+
+  @Test
+  public void testStatementExecuteUpdateUsesStatementProtocol() throws 
SQLException {
+    try (Statement statement = connection.createStatement()) {
+      assertThat(statement.executeUpdate(UPDATE_QUERY), is(1));
+    }
+
+    assertThat(
+        PRODUCER
+            .getActionTypeCounter()
+            
.getOrDefault(FlightSqlUtils.FLIGHT_SQL_CREATE_PREPARED_STATEMENT.getType(), 0),
+        is(0));
+    assertThat(
+        PRODUCER
+            .getCommandTypeCounter()
+            .getOrDefault(MockFlightSqlProducer.COMMAND_STATEMENT_UPDATE, 0),
+        is(1));
+    assertThat(
+        PRODUCER
+            .getCommandTypeCounter()
+            
.getOrDefault(MockFlightSqlProducer.COMMAND_PREPARED_STATEMENT_UPDATE, 0),
+        is(0));
+  }
+
+  @Test
+  public void testStatementExecuteUsesPreparedProtocolForUpdate() throws 
SQLException {
+    try (Statement statement = connection.createStatement()) {
+      assertThat(statement.execute(UPDATE_QUERY), is(false));
+      assertThat(statement.getUpdateCount(), is(1));
+    }
+
+    assertThat(
+        PRODUCER
+            .getActionTypeCounter()
+            
.getOrDefault(FlightSqlUtils.FLIGHT_SQL_CREATE_PREPARED_STATEMENT.getType(), 0),
+        is(1));
+    assertThat(
+        PRODUCER
+            .getCommandTypeCounter()
+            
.getOrDefault(MockFlightSqlProducer.COMMAND_PREPARED_STATEMENT_UPDATE, 0),
+        is(1));
+    assertThat(
+        PRODUCER
+            .getCommandTypeCounter()
+            .getOrDefault(MockFlightSqlProducer.COMMAND_STATEMENT_UPDATE, 0),
+        is(0));
+    assertThat(
+        PRODUCER
+            .getActionTypeCounter()
+            
.getOrDefault(FlightSqlUtils.FLIGHT_SQL_CLOSE_PREPARED_STATEMENT.getType(), 0),
+        is(1));
+  }
+
+  @Test
+  public void testStatementExecuteThenExecuteUpdateUsesStatementProtocol() 
throws SQLException {
+    try (Statement statement = connection.createStatement()) {
+      assertThat(statement.execute(SELECT_QUERY), is(true));
+      try (ResultSet resultSet = statement.getResultSet()) {
+        assertTrue(resultSet.next());
+      }
+      assertThat(statement.executeUpdate(UPDATE_QUERY), is(1));
+    }
+
+    assertThat(
+        PRODUCER
+            .getActionTypeCounter()
+            
.getOrDefault(FlightSqlUtils.FLIGHT_SQL_CREATE_PREPARED_STATEMENT.getType(), 0),
+        is(1));
+    assertThat(
+        PRODUCER
+            .getCommandTypeCounter()
+            
.getOrDefault(MockFlightSqlProducer.COMMAND_PREPARED_STATEMENT_QUERY, 0),
+        is(1));
+    assertThat(
+        PRODUCER
+            .getCommandTypeCounter()
+            .getOrDefault(MockFlightSqlProducer.COMMAND_STATEMENT_UPDATE, 0),
+        is(1));
+    assertThat(
+        PRODUCER
+            .getActionTypeCounter()
+            
.getOrDefault(FlightSqlUtils.FLIGHT_SQL_CLOSE_PREPARED_STATEMENT.getType(), 0),
+        is(1));
+  }
+
+  @Test
+  public void testStatementExecuteUpdateThenExecuteQueryUsesStatementProtocol()
+      throws SQLException {
+    try (Statement statement = connection.createStatement()) {
+      assertThat(statement.execute(UPDATE_QUERY), is(false));
+      assertThat(statement.getUpdateCount(), is(1));
+      try (ResultSet resultSet = statement.executeQuery(SELECT_QUERY)) {
+        assertTrue(resultSet.next());
+      }
+    }
+
+    assertThat(
+        PRODUCER
+            .getActionTypeCounter()
+            
.getOrDefault(FlightSqlUtils.FLIGHT_SQL_CREATE_PREPARED_STATEMENT.getType(), 0),
+        is(1));
+    assertThat(
+        PRODUCER
+            .getCommandTypeCounter()
+            
.getOrDefault(MockFlightSqlProducer.COMMAND_PREPARED_STATEMENT_UPDATE, 0),
+        is(1));
+    assertThat(
+        PRODUCER
+            .getCommandTypeCounter()
+            .getOrDefault(MockFlightSqlProducer.COMMAND_STATEMENT_QUERY, 0),
+        is(1));
+    assertThat(
+        PRODUCER
+            .getActionTypeCounter()
+            
.getOrDefault(FlightSqlUtils.FLIGHT_SQL_CLOSE_PREPARED_STATEMENT.getType(), 0),
+        is(1));
+  }
+
+  @Test
+  public void testStatementExecuteQueryThenExecuteUsesPreparedProtocol() 
throws SQLException {
+    try (Statement statement = connection.createStatement()) {
+      try (ResultSet resultSet = statement.executeQuery(SELECT_QUERY)) {
+        assertTrue(resultSet.next());
+      }
+      assertThat(statement.execute(SELECT_QUERY), is(true));
+      try (ResultSet resultSet = statement.getResultSet()) {
+        assertTrue(resultSet.next());
+      }
+    }
+
+    assertThat(
+        PRODUCER
+            .getCommandTypeCounter()
+            .getOrDefault(MockFlightSqlProducer.COMMAND_STATEMENT_QUERY, 0),
+        is(1));
+    assertThat(
+        PRODUCER
+            .getActionTypeCounter()
+            
.getOrDefault(FlightSqlUtils.FLIGHT_SQL_CREATE_PREPARED_STATEMENT.getType(), 0),
+        is(1));
+    assertThat(
+        PRODUCER
+            .getCommandTypeCounter()
+            
.getOrDefault(MockFlightSqlProducer.COMMAND_PREPARED_STATEMENT_QUERY, 0),
+        is(1));
+  }
+
+  @Test
+  public void testStatementExecuteUpdateThenExecuteUsesPreparedProtocol() 
throws SQLException {
+    try (Statement statement = connection.createStatement()) {
+      assertThat(statement.executeUpdate(UPDATE_QUERY), is(1));
+      assertThat(statement.execute(UPDATE_QUERY), is(false));
+      assertThat(statement.getUpdateCount(), is(1));
+    }
+
+    assertThat(
+        PRODUCER
+            .getCommandTypeCounter()
+            .getOrDefault(MockFlightSqlProducer.COMMAND_STATEMENT_UPDATE, 0),
+        is(1));
+    assertThat(
+        PRODUCER
+            .getActionTypeCounter()
+            
.getOrDefault(FlightSqlUtils.FLIGHT_SQL_CREATE_PREPARED_STATEMENT.getType(), 0),
+        is(1));
+    assertThat(
+        PRODUCER
+            .getCommandTypeCounter()
+            
.getOrDefault(MockFlightSqlProducer.COMMAND_PREPARED_STATEMENT_UPDATE, 0),
+        is(1));
+  }
+
+  @Test
+  public void testPreparedStatementExecuteQueryUsesPreparedProtocol() throws 
SQLException {
+    try (PreparedStatement statement = 
connection.prepareStatement(SELECT_QUERY);
+        ResultSet resultSet = statement.executeQuery()) {
+      assertTrue(resultSet.next());
+    }
+
+    assertThat(
+        PRODUCER
+            .getActionTypeCounter()
+            
.getOrDefault(FlightSqlUtils.FLIGHT_SQL_CREATE_PREPARED_STATEMENT.getType(), 0),
+        is(1));
+    assertThat(
+        PRODUCER
+            .getCommandTypeCounter()
+            
.getOrDefault(MockFlightSqlProducer.COMMAND_PREPARED_STATEMENT_QUERY, 0),
+        is(1));
+    assertThat(
+        PRODUCER
+            .getCommandTypeCounter()
+            .getOrDefault(MockFlightSqlProducer.COMMAND_STATEMENT_QUERY, 0),
+        is(0));
+  }
+
+  @Test
+  public void testPreparedStatementExecuteUsesPreparedProtocolForQuery() 
throws SQLException {
+    try (PreparedStatement statement = 
connection.prepareStatement(SELECT_QUERY)) {
+      assertThat(statement.execute(), is(true));
+      try (ResultSet resultSet = statement.getResultSet()) {
+        assertTrue(resultSet.next());
+      }
+    }
+
+    assertThat(
+        PRODUCER
+            .getActionTypeCounter()
+            
.getOrDefault(FlightSqlUtils.FLIGHT_SQL_CREATE_PREPARED_STATEMENT.getType(), 0),
+        is(1));
+    assertThat(
+        PRODUCER
+            .getCommandTypeCounter()
+            
.getOrDefault(MockFlightSqlProducer.COMMAND_PREPARED_STATEMENT_QUERY, 0),
+        is(1));
+    assertThat(
+        PRODUCER
+            .getCommandTypeCounter()
+            .getOrDefault(MockFlightSqlProducer.COMMAND_STATEMENT_QUERY, 0),
+        is(0));
+  }
+
+  @Test
+  public void testPreparedStatementExecuteUpdateUsesPreparedProtocol() throws 
SQLException {
+    try (PreparedStatement statement = 
connection.prepareStatement(UPDATE_QUERY)) {
+      assertThat(statement.executeUpdate(), is(1));
+    }
+
+    assertThat(
+        PRODUCER
+            .getActionTypeCounter()
+            
.getOrDefault(FlightSqlUtils.FLIGHT_SQL_CREATE_PREPARED_STATEMENT.getType(), 0),
+        is(1));
+    assertThat(
+        PRODUCER
+            .getCommandTypeCounter()
+            
.getOrDefault(MockFlightSqlProducer.COMMAND_PREPARED_STATEMENT_UPDATE, 0),
+        is(1));
+    assertThat(
+        PRODUCER
+            .getCommandTypeCounter()
+            .getOrDefault(MockFlightSqlProducer.COMMAND_STATEMENT_UPDATE, 0),
+        is(0));
+  }
+
+  @Test
+  public void testPreparedStatementExecuteUsesPreparedProtocolForUpdate() 
throws SQLException {
+    try (PreparedStatement statement = 
connection.prepareStatement(UPDATE_QUERY)) {
+      assertThat(statement.execute(), is(false));
+      assertThat(statement.getUpdateCount(), is(1));
+    }
+
+    assertThat(
+        PRODUCER
+            .getActionTypeCounter()
+            
.getOrDefault(FlightSqlUtils.FLIGHT_SQL_CREATE_PREPARED_STATEMENT.getType(), 0),
+        is(1));
+    assertThat(
+        PRODUCER
+            .getCommandTypeCounter()
+            
.getOrDefault(MockFlightSqlProducer.COMMAND_PREPARED_STATEMENT_UPDATE, 0),
+        is(1));
+    assertThat(
+        PRODUCER
+            .getCommandTypeCounter()
+            .getOrDefault(MockFlightSqlProducer.COMMAND_STATEMENT_UPDATE, 0),
+        is(0));
+  }
+
+  @Test
+  public void testMetadataGetSchemasUsesJdbcApi() throws SQLException {
+    final DatabaseMetaData metaData = connection.getMetaData();
+    try (ResultSet resultSet = metaData.getSchemas()) {
+      assertTrue(resultSet.next());
+    }
+
+    assertThat(
+        PRODUCER
+            .getActionTypeCounter()
+            
.getOrDefault(FlightSqlUtils.FLIGHT_SQL_CREATE_PREPARED_STATEMENT.getType(), 0),
+        is(0));
+  }
+}
diff --git 
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ResultSetTest.java
 
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ResultSetTest.java
index 3a5a39be3..7d1bf67e4 100644
--- 
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ResultSetTest.java
+++ 
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ResultSetTest.java
@@ -235,6 +235,38 @@ public class ResultSetTest {
     }
   }
 
+  @Test
+  public void 
testCloseOnCompletionUnregistersDirectStatementWhenResultSetClosedEarly()
+      throws Exception {
+    try (Statement statement = connection.createStatement()) {
+      final ResultSet resultSet =
+          
statement.executeQuery(CoreMockedSqlProducers.LEGACY_REGULAR_SQL_CMD);
+      statement.closeOnCompletion();
+      assertThat(((ArrowFlightConnection) 
connection).isStatementOwner(statement), is(true));
+
+      resultSet.close();
+
+      assertThat(statement.isClosed(), is(true));
+      assertThat(((ArrowFlightConnection) 
connection).isStatementOwner(statement), is(false));
+    }
+  }
+
+  @Test
+  public void 
testCloseOnCompletionUnregistersPreparedStatementWhenResultSetClosedEarly()
+      throws Exception {
+    try (PreparedStatement statement =
+        
connection.prepareStatement(CoreMockedSqlProducers.LEGACY_REGULAR_SQL_CMD)) {
+      final ResultSet resultSet = statement.executeQuery();
+      statement.closeOnCompletion();
+      assertThat(((ArrowFlightConnection) 
connection).isStatementOwner(statement), is(true));
+
+      resultSet.close();
+
+      assertThat(statement.isClosed(), is(true));
+      assertThat(((ArrowFlightConnection) 
connection).isStatementOwner(statement), is(false));
+    }
+  }
+
   /**
    * Tests whether the {@link ArrowFlightJdbcDriver} close the statement after 
complete ResultSet
    * with max rows limit when call {@link
@@ -303,7 +335,8 @@ public class ResultSetTest {
   public void testShouldInterruptFlightStreamsIfQueryIsCancelledMidQuerying()
       throws SQLException, InterruptedException {
     try (final Statement statement = connection.createStatement()) {
-      final CountDownLatch latch = new CountDownLatch(1);
+      final CountDownLatch executed = new CountDownLatch(1);
+      final CountDownLatch canceled = new CountDownLatch(1);
       final Set<Exception> exceptions = synchronizedSet(new HashSet<>(1));
       final Thread thread =
           new Thread(
@@ -311,19 +344,27 @@ public class ResultSetTest {
                 try (final ResultSet resultSet =
                     
statement.executeQuery(CoreMockedSqlProducers.LEGACY_REGULAR_SQL_CMD)) {
                   final int cachedColumnCount = 
resultSet.getMetaData().getColumnCount();
-                  Thread.sleep(300);
+                  executed.countDown();
+                  canceled.await();
                   while (resultSet.next()) {
                     resultSet.getObject(RANDOM.nextInt(cachedColumnCount) + 1);
                   }
                 } catch (final SQLException | InterruptedException e) {
                   exceptions.add(e);
                 } finally {
-                  latch.countDown();
+                  executed.countDown();
                 }
               });
       thread.setName("Test Case: interrupt query execution before first 
retrieval");
       thread.start();
-      statement.cancel();
+      // Cancel only after executeQuery returns, so the cancellation lands 
before the first
+      // retrieval instead of racing with query execution.
+      executed.await();
+      try {
+        statement.cancel();
+      } finally {
+        canceled.countDown();
+      }
       thread.join();
       assertThat(
           exceptions.stream()
diff --git 
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/MockFlightSqlProducer.java
 
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/MockFlightSqlProducer.java
index 6627d91ab..36c07ce5d 100644
--- 
a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/MockFlightSqlProducer.java
+++ 
b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/MockFlightSqlProducer.java
@@ -39,6 +39,7 @@ import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Objects;
 import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.function.BiConsumer;
 import java.util.function.Consumer;
 import java.util.stream.IntStream;
@@ -104,7 +105,14 @@ public final class MockFlightSqlProducer implements 
FlightSqlProducer {
   private final Map<String, List<List<Object>>> expectedParameterValues = new 
HashMap<>();
   private final Map<String, Boolean> isUpdateMap = new HashMap<>();
 
-  private final Map<String, Integer> actionTypeCounter = new HashMap<>();
+  private final Map<String, Integer> actionTypeCounter = new 
ConcurrentHashMap<>();
+  private final Map<String, Integer> commandTypeCounter = new 
ConcurrentHashMap<>();
+  private volatile @Nullable CallStatus closePreparedStatementFailure;
+
+  public static final String COMMAND_STATEMENT_QUERY = "statement_query";
+  public static final String COMMAND_STATEMENT_UPDATE = "statement_update";
+  public static final String COMMAND_PREPARED_STATEMENT_QUERY = 
"prepared_statement_query";
+  public static final String COMMAND_PREPARED_STATEMENT_UPDATE = 
"prepared_statement_update";
 
   private static FlightInfo getFlightInfoExportedAndImportedKeys(
       final Message message, final FlightDescriptor descriptor) {
@@ -302,8 +310,16 @@ public final class MockFlightSqlProducer implements 
FlightSqlProducer {
       final ActionClosePreparedStatementRequest 
actionClosePreparedStatementRequest,
       final CallContext callContext,
       final StreamListener<Result> streamListener) {
-    // TODO Implement this method.
-    streamListener.onCompleted();
+    final CallStatus failure = closePreparedStatementFailure;
+    if (failure == null) {
+      streamListener.onCompleted();
+    } else {
+      streamListener.onError(failure.toRuntimeException());
+    }
+  }
+
+  public void setClosePreparedStatementFailure(final @Nullable CallStatus 
failure) {
+    closePreparedStatementFailure = failure;
   }
 
   @Override
@@ -311,6 +327,7 @@ public final class MockFlightSqlProducer implements 
FlightSqlProducer {
       final CommandStatementQuery commandStatementQuery,
       final CallContext callContext,
       final FlightDescriptor flightDescriptor) {
+    incrementCommandTypeCounter(COMMAND_STATEMENT_QUERY);
     final String query = commandStatementQuery.getQuery();
     final Entry<Schema, List<UUID>> queryInfo =
         Preconditions.checkNotNull(
@@ -331,6 +348,7 @@ public final class MockFlightSqlProducer implements 
FlightSqlProducer {
       final CommandPreparedStatementQuery commandPreparedStatementQuery,
       final CallContext callContext,
       final FlightDescriptor flightDescriptor) {
+    incrementCommandTypeCounter(COMMAND_PREPARED_STATEMENT_QUERY);
     final ByteString preparedStatementHandle =
         commandPreparedStatementQuery.getPreparedStatementHandle();
 
@@ -398,8 +416,15 @@ public final class MockFlightSqlProducer implements 
FlightSqlProducer {
       final CallContext callContext,
       final FlightStream flightStream,
       final StreamListener<PutResult> streamListener) {
+    incrementCommandTypeCounter(COMMAND_STATEMENT_UPDATE);
+    return acceptUpdate(commandStatementUpdate.getQuery(), flightStream, 
streamListener);
+  }
+
+  private Runnable acceptUpdate(
+      final String query,
+      final FlightStream flightStream,
+      final StreamListener<PutResult> streamListener) {
     return () -> {
-      final String query = commandStatementUpdate.getQuery();
       final BiConsumer<FlightStream, StreamListener<PutResult>> resultProvider 
=
           Preconditions.checkNotNull(
               updateResultProviders.get(query),
@@ -471,6 +496,7 @@ public final class MockFlightSqlProducer implements 
FlightSqlProducer {
       final CallContext callContext,
       final FlightStream flightStream,
       final StreamListener<PutResult> streamListener) {
+    incrementCommandTypeCounter(COMMAND_PREPARED_STATEMENT_UPDATE);
     final ByteString handle = 
commandPreparedStatementUpdate.getPreparedStatementHandle();
     final String query =
         Preconditions.checkNotNull(
@@ -481,11 +507,7 @@ public final class MockFlightSqlProducer implements 
FlightSqlProducer {
       return () -> {};
     }
 
-    return acceptPutStatement(
-        CommandStatementUpdate.newBuilder().setQuery(query).build(),
-        callContext,
-        flightStream,
-        streamListener);
+    return acceptUpdate(query, flightStream, streamListener);
   }
 
   @Override
@@ -680,9 +702,8 @@ public final class MockFlightSqlProducer implements 
FlightSqlProducer {
 
   @Override
   public void doAction(CallContext context, Action action, 
StreamListener<Result> listener) {
+    actionTypeCounter.merge(action.getType(), 1, Integer::sum);
     FlightSqlProducer.super.doAction(context, action, listener);
-    actionTypeCounter.put(
-        action.getType(), actionTypeCounter.getOrDefault(action.getType(), 0) 
+ 1);
   }
 
   /**
@@ -693,10 +714,22 @@ public final class MockFlightSqlProducer implements 
FlightSqlProducer {
     actionTypeCounter.clear();
   }
 
+  public void clearCommandTypeCounter() {
+    commandTypeCounter.clear();
+  }
+
   public Map<String, Integer> getActionTypeCounter() {
     return actionTypeCounter;
   }
 
+  public Map<String, Integer> getCommandTypeCounter() {
+    return commandTypeCounter;
+  }
+
+  private void incrementCommandTypeCounter(String commandType) {
+    commandTypeCounter.merge(commandType, 1, Integer::sum);
+  }
+
   private void getStreamCatalogFunctions(
       final Message ticket, final ServerStreamListener serverStreamListener) {
     Preconditions.checkNotNull(

Reply via email to