Skip to content

Commit 054c7b8

Browse files
xborderjbonofre
andauthored
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é <jbonofre@apache.org>
1 parent 8d9407c commit 054c7b8

16 files changed

Lines changed: 1719 additions & 271 deletions

‎flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java‎

Lines changed: 75 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,18 @@
1919
import static org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty.replaceSemiColons;
2020

2121
import io.netty.util.concurrent.DefaultThreadFactory;
22+
import java.sql.PreparedStatement;
23+
import java.sql.ResultSet;
2224
import java.sql.SQLException;
25+
import java.sql.Statement;
2326
import java.util.ArrayList;
27+
import java.util.Collections;
2428
import java.util.HashMap;
29+
import java.util.HashSet;
30+
import java.util.IdentityHashMap;
2531
import java.util.Map;
2632
import java.util.Properties;
33+
import java.util.Set;
2734
import java.util.concurrent.ExecutorService;
2835
import java.util.concurrent.Executors;
2936
import org.apache.arrow.driver.jdbc.client.ArrowFlightSqlClientHandler;
@@ -33,8 +40,10 @@
3340
import org.apache.arrow.memory.BufferAllocator;
3441
import org.apache.arrow.util.AutoCloseables;
3542
import org.apache.arrow.util.Preconditions;
43+
import org.apache.arrow.util.VisibleForTesting;
3644
import org.apache.calcite.avatica.AvaticaConnection;
3745
import org.apache.calcite.avatica.AvaticaFactory;
46+
import org.apache.calcite.avatica.AvaticaStatement;
3847
import org.apache.calcite.avatica.DriverVersion;
3948

4049
/** Connection to the Arrow Flight server. */
@@ -45,7 +54,11 @@ public final class ArrowFlightConnection extends AvaticaConnection {
4554
private final ArrowFlightConnectionConfigImpl config;
4655
private ExecutorService executorService;
4756
private int metadataResultSetCount;
57+
// Track metadata result sets so connection close can release them.
4858
private Map<Integer, ArrowFlightJdbcFlightStreamResultSet> metadataResultSetMap = new HashMap<>();
59+
// Track original statement owners when execution replaces their statement-map entries.
60+
private final Set<AvaticaStatement> statementOwners =
61+
Collections.newSetFromMap(new IdentityHashMap<>());
4962

5063
/**
5164
* Creates a new {@link ArrowFlightConnection}.
@@ -143,7 +156,7 @@ private static ArrowFlightSqlClientHandler createNewClientHandler(
143156
void reset() throws SQLException {
144157
// Clean up any open Statements
145158
try {
146-
AutoCloseables.close(statementMap.values());
159+
AutoCloseables.close(getStatementsToClose());
147160
} catch (final Exception e) {
148161
throw AvaticaConnection.HELPER.createException(e.getMessage(), e);
149162
}
@@ -204,6 +217,33 @@ void onResultSetClose(Integer id) {
204217
metadataResultSetMap.remove(id);
205218
}
206219

220+
synchronized void registerStatementOwner(final AvaticaStatement statement) {
221+
statementOwners.add(statement);
222+
}
223+
224+
synchronized void unregisterStatementOwner(final AvaticaStatement statement) {
225+
statementOwners.remove(statement);
226+
}
227+
228+
@VisibleForTesting
229+
synchronized boolean isStatementOwner(final Statement statement) {
230+
return statementOwners.contains(statement);
231+
}
232+
233+
private synchronized ArrayList<AutoCloseable> getStatementsToClose() {
234+
final ArrayList<AutoCloseable> statements = new ArrayList<>(statementOwners);
235+
final Set<Integer> ownedHandles = new HashSet<>();
236+
for (AvaticaStatement statement : statementOwners) {
237+
ownedHandles.add(statement.handle.id);
238+
}
239+
for (Map.Entry<Integer, AvaticaStatement> entry : statementMap.entrySet()) {
240+
if (!ownedHandles.contains(entry.getKey())) {
241+
statements.add(entry.getValue());
242+
}
243+
}
244+
return statements;
245+
}
246+
207247
@Override
208248
public Properties getClientInfo() {
209249
final Properties copy = new Properties();
@@ -222,7 +262,7 @@ public void close() throws SQLException {
222262
topLevelException = e;
223263
}
224264
// copies of the collections are used to avoid concurrent modification problems
225-
ArrayList<AutoCloseable> closeables = new ArrayList<>(statementMap.values());
265+
ArrayList<AutoCloseable> closeables = getStatementsToClose();
226266
closeables.addAll(new ArrayList<>(metadataResultSetMap.values()));
227267
closeables.add(clientHandler);
228268
closeables.addAll(allocator.getChildAllocators());
@@ -258,4 +298,37 @@ BufferAllocator getBufferAllocator() {
258298
public ArrowFlightMetaImpl getMeta() {
259299
return (ArrowFlightMetaImpl) this.meta;
260300
}
301+
302+
@Override
303+
public PreparedStatement prepareStatement(final String sql) throws SQLException {
304+
return prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
305+
}
306+
307+
@Override
308+
public PreparedStatement prepareStatement(
309+
final String sql, final int resultSetType, final int resultSetConcurrency)
310+
throws SQLException {
311+
return prepareStatement(sql, resultSetType, resultSetConcurrency, getHoldability());
312+
}
313+
314+
@Override
315+
public PreparedStatement prepareStatement(
316+
final String sql,
317+
final int resultSetType,
318+
final int resultSetConcurrency,
319+
final int resultSetHoldability)
320+
throws SQLException {
321+
checkOpen();
322+
try {
323+
return ArrowFlightPreparedStatement.builder(this)
324+
.withQuery(sql)
325+
.withGeneratedHandle()
326+
.withResultSetType(resultSetType)
327+
.withResultSetConcurrency(resultSetConcurrency)
328+
.withResultSetHoldability(resultSetHoldability)
329+
.build();
330+
} catch (final RuntimeException e) {
331+
throw HELPER.createException("while preparing SQL:" + sql, e);
332+
}
333+
}
261334
}

‎flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFactory.java‎

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
import java.sql.SQLException;
2121
import java.util.Properties;
2222
import java.util.TimeZone;
23-
import org.apache.arrow.driver.jdbc.client.ArrowFlightSqlClientHandler;
2423
import org.apache.arrow.memory.RootAllocator;
2524
import org.apache.calcite.avatica.AvaticaConnection;
2625
import org.apache.calcite.avatica.AvaticaFactory;
@@ -82,17 +81,18 @@ public ArrowFlightPreparedStatement newPreparedStatement(
8281
final int resultSetHoldability)
8382
throws SQLException {
8483
final ArrowFlightConnection flightConnection = (ArrowFlightConnection) connection;
85-
ArrowFlightSqlClientHandler.PreparedStatement preparedStatement =
86-
flightConnection.getMeta().getPreparedStatement(statementHandle);
84+
final AvaticaStatement existingStatement =
85+
flightConnection.statementMap.get(statementHandle.id);
86+
if (existingStatement instanceof ArrowFlightPreparedStatement) {
87+
return (ArrowFlightPreparedStatement) existingStatement;
88+
}
89+
if (existingStatement != null) {
90+
throw new IllegalStateException(
91+
"Unexpected statement type found for prepared statement handle: " + statementHandle);
92+
}
8793

88-
return ArrowFlightPreparedStatement.newPreparedStatement(
89-
flightConnection,
90-
preparedStatement,
91-
statementHandle,
92-
signature,
93-
resultType,
94-
resultSetConcurrency,
95-
resultSetHoldability);
94+
throw new IllegalStateException(
95+
"PreparedStatement was not pre-created for handle: " + statementHandle);
9696
}
9797

9898
@Override

‎flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java‎

Lines changed: 88 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -21,17 +21,22 @@
2121
import java.sql.ResultSet;
2222
import java.sql.ResultSetMetaData;
2323
import java.sql.SQLException;
24+
import java.util.Collection;
25+
import java.util.Iterator;
2426
import java.util.Optional;
2527
import java.util.TimeZone;
2628
import java.util.concurrent.TimeUnit;
2729
import org.apache.arrow.driver.jdbc.client.CloseableEndpointStreamPair;
2830
import org.apache.arrow.driver.jdbc.utils.FlightEndpointDataQueue;
2931
import org.apache.arrow.driver.jdbc.utils.VectorSchemaRootTransformer;
32+
import org.apache.arrow.flight.CallStatus;
3033
import org.apache.arrow.flight.FlightInfo;
34+
import org.apache.arrow.flight.FlightRuntimeException;
3135
import org.apache.arrow.flight.FlightStream;
3236
import org.apache.arrow.util.AutoCloseables;
3337
import org.apache.arrow.vector.VectorSchemaRoot;
3438
import org.apache.arrow.vector.types.pojo.Schema;
39+
import org.apache.calcite.avatica.AvaticaConnection;
3540
import org.apache.calcite.avatica.AvaticaResultSet;
3641
import org.apache.calcite.avatica.AvaticaResultSetMetaData;
3742
import org.apache.calcite.avatica.AvaticaStatement;
@@ -49,6 +54,7 @@ public final class ArrowFlightJdbcFlightStreamResultSet
4954
private final FlightInfo flightInfo;
5055
private CloseableEndpointStreamPair currentEndpointData;
5156
private FlightEndpointDataQueue flightEndpointDataQueue;
57+
private volatile boolean cancelled;
5258

5359
private VectorSchemaRootTransformer transformer;
5460
private VectorSchemaRoot currentVectorSchemaRoot;
@@ -106,7 +112,7 @@ static ArrowFlightJdbcFlightStreamResultSet fromFlightInfo(
106112
final TimeZone timeZone = TimeZone.getDefault();
107113
final QueryState state = new QueryState();
108114

109-
final Meta.Signature signature = ArrowFlightMetaImpl.newSignature(null, null, null, null);
115+
final Meta.Signature signature = ArrowFlightMetaImpl.buildDefaultSignature();
110116

111117
final AvaticaResultSetMetaData resultSetMetaData =
112118
new AvaticaResultSetMetaData(null, null, signature);
@@ -143,7 +149,8 @@ protected AvaticaResultSet execute() throws SQLException {
143149

144150
private void populateData() throws SQLException {
145151
loadNewQueue();
146-
flightEndpointDataQueue.enqueue(connection.getClientHandler().getStreams(flightInfo));
152+
enqueueEndpointData(
153+
flightEndpointDataQueue, connection.getClientHandler().getStreams(flightInfo));
147154
loadNewFlightStream();
148155

149156
// Ownership of the root will be passed onto the cursor.
@@ -192,23 +199,38 @@ public boolean next() throws SQLException {
192199
return true;
193200
}
194201

195-
if (currentEndpointData != null) {
196-
currentEndpointData.getStream().getRoot().clear();
197-
if (currentEndpointData.getStream().next()) {
198-
populateDataForCurrentFlightStream();
199-
continue;
202+
try {
203+
if (currentEndpointData != null) {
204+
currentEndpointData.getStream().getRoot().clear();
205+
if (currentEndpointData.getStream().next()) {
206+
populateDataForCurrentFlightStream();
207+
continue;
208+
}
209+
210+
enqueueEndpointData(currentEndpointData);
200211
}
201212

202-
flightEndpointDataQueue.enqueue(currentEndpointData);
213+
currentEndpointData = getNextEndpointStream(false);
214+
} catch (final FlightRuntimeException e) {
215+
// A concurrent statement.cancel() (or close) cancels in-flight FlightStreams,
216+
// which surface here as CANCELLED. Normalize to Avatica's "Statement canceled".
217+
if ((cancelled || flightEndpointDataQueue.isClosed())
218+
&& e.status().code() == CallStatus.CANCELLED.code()) {
219+
throw AvaticaConnection.HELPER.createException("Statement canceled");
220+
}
221+
throw e;
203222
}
204223

205-
currentEndpointData = getNextEndpointStream(false);
206-
207224
if (currentEndpointData != null) {
208225
populateDataForCurrentFlightStream();
209226
continue;
210227
}
211228

229+
// Cancellation can wake the reader before queue cleanup completes.
230+
if (cancelled || flightEndpointDataQueue.isClosed()) {
231+
throw AvaticaConnection.HELPER.createException("Statement canceled");
232+
}
233+
212234
if (statement != null && statement.isCloseOnCompletion()) {
213235
statement.close();
214236
}
@@ -219,6 +241,7 @@ public boolean next() throws SQLException {
219241

220242
@Override
221243
protected void cancel() {
244+
cancelled = true;
222245
super.cancel();
223246
final CloseableEndpointStreamPair currentEndpoint = this.currentEndpointData;
224247
if (currentEndpoint != null) {
@@ -259,13 +282,61 @@ public synchronized void close() {
259282

260283
private CloseableEndpointStreamPair getNextEndpointStream(final boolean canTimeout)
261284
throws SQLException {
262-
if (canTimeout) {
263-
final int statementTimeout = statement != null ? statement.getQueryTimeout() : 0;
264-
return statementTimeout != 0
265-
? flightEndpointDataQueue.next(statementTimeout, TimeUnit.SECONDS)
266-
: flightEndpointDataQueue.next();
267-
} else {
268-
return flightEndpointDataQueue.next();
285+
try {
286+
if (canTimeout) {
287+
final int statementTimeout = statement != null ? statement.getQueryTimeout() : 0;
288+
return statementTimeout != 0
289+
? flightEndpointDataQueue.next(statementTimeout, TimeUnit.SECONDS)
290+
: flightEndpointDataQueue.next();
291+
} else {
292+
return flightEndpointDataQueue.next();
293+
}
294+
} catch (final IllegalStateException e) {
295+
throw normalizeClosedQueueException(flightEndpointDataQueue, e);
296+
}
297+
}
298+
299+
static void enqueueEndpointData(
300+
final FlightEndpointDataQueue queue,
301+
final Collection<CloseableEndpointStreamPair> endpointRequests)
302+
throws SQLException {
303+
final Iterator<CloseableEndpointStreamPair> endpointIterator = endpointRequests.iterator();
304+
while (endpointIterator.hasNext()) {
305+
final CloseableEndpointStreamPair endpointRequest = endpointIterator.next();
306+
try {
307+
queue.enqueue(endpointRequest);
308+
} catch (final IllegalStateException e) {
309+
final SQLException exception = normalizeClosedQueueException(queue, e);
310+
closeRejectedEndpoint(endpointRequest, exception);
311+
endpointIterator.forEachRemaining(endpoint -> closeRejectedEndpoint(endpoint, exception));
312+
throw exception;
313+
}
314+
}
315+
}
316+
317+
private void enqueueEndpointData(final CloseableEndpointStreamPair endpointRequest)
318+
throws SQLException {
319+
try {
320+
flightEndpointDataQueue.enqueue(endpointRequest);
321+
} catch (final IllegalStateException e) {
322+
throw normalizeClosedQueueException(flightEndpointDataQueue, e);
323+
}
324+
}
325+
326+
private static void closeRejectedEndpoint(
327+
final CloseableEndpointStreamPair endpoint, final SQLException exception) {
328+
try {
329+
endpoint.close();
330+
} catch (final Exception closeException) {
331+
exception.addSuppressed(closeException);
332+
}
333+
}
334+
335+
private static SQLException normalizeClosedQueueException(
336+
final FlightEndpointDataQueue queue, final IllegalStateException exception) {
337+
if (queue.isClosed()) {
338+
return AvaticaConnection.HELPER.createException("Statement canceled");
269339
}
340+
throw exception;
270341
}
271342
}

‎flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcVectorSchemaRootResultSet.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ public static ArrowFlightJdbcVectorSchemaRootResultSet fromVectorSchemaRoot(
7373
final TimeZone timeZone = TimeZone.getDefault();
7474
final QueryState state = new QueryState();
7575

76-
final Meta.Signature signature = ArrowFlightMetaImpl.newSignature(null, null, null, null);
76+
final Meta.Signature signature = ArrowFlightMetaImpl.buildDefaultSignature();
7777

7878
final AvaticaResultSetMetaData resultSetMetaData =
7979
new AvaticaResultSetMetaData(null, null, signature);

0 commit comments

Comments
 (0)