From da34c0c8be95f691ebaae4d1bfd382e60116609b Mon Sep 17 00:00:00 2001 From: Steve Lord Date: Tue, 12 Mar 2024 14:15:04 -0700 Subject: [PATCH 01/16] GH-37720: [Java][FlightSQL] Implement stateless prepared statements --- .../arrow/flight/sql/FlightSqlClient.java | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/java/flight/flight-sql/src/main/java/org/apache/arrow/flight/sql/FlightSqlClient.java b/java/flight/flight-sql/src/main/java/org/apache/arrow/flight/sql/FlightSqlClient.java index 6fe31fae9216..9a46cbf6f7c7 100644 --- a/java/flight/flight-sql/src/main/java/org/apache/arrow/flight/sql/FlightSqlClient.java +++ b/java/flight/flight-sql/src/main/java/org/apache/arrow/flight/sql/FlightSqlClient.java @@ -78,6 +78,7 @@ import org.apache.arrow.flight.SetSessionOptionsResult; import org.apache.arrow.flight.SyncPutListener; import org.apache.arrow.flight.Ticket; +import org.apache.arrow.flight.sql.impl.FlightSql; import org.apache.arrow.flight.sql.impl.FlightSql.ActionCreatePreparedStatementResult; import org.apache.arrow.flight.sql.impl.FlightSql.CommandPreparedStatementQuery; import org.apache.arrow.flight.sql.util.TableRef; @@ -1048,15 +1049,31 @@ private Schema deserializeSchema(final ByteString bytes) { public FlightInfo execute(final CallOption... options) { checkOpen(); - final FlightDescriptor descriptor = FlightDescriptor + FlightDescriptor descriptor = FlightDescriptor .command(Any.pack(CommandPreparedStatementQuery.newBuilder() .setPreparedStatementHandle(preparedStatementResult.getPreparedStatementHandle()) .build()) .toByteArray()); if (parameterBindingRoot != null && parameterBindingRoot.getRowCount() > 0) { - try (final SyncPutListener listener = putParameters(descriptor, options)) { - listener.getResult(); + try (final SyncPutListener putListener = putParameters(descriptor, options)) { + final PutResult read = putListener.read(); + if (read != null) { + try (final ArrowBuf metadata = read.getApplicationMetadata()) { + final FlightSql.DoPutPreparedStatementResult doPutPreparedStatementResult = + FlightSql.DoPutPreparedStatementResult.parseFrom(metadata.nioBuffer()); + descriptor = FlightDescriptor + .command(Any.pack(CommandPreparedStatementQuery.newBuilder() + .setPreparedStatementHandle( + doPutPreparedStatementResult.getPreparedStatementHandle()) + .build()) + .toByteArray()); + } + } + } catch (final InterruptedException | ExecutionException e) { + throw CallStatus.CANCELLED.withCause(e).toRuntimeException(); + } catch (final InvalidProtocolBufferException e) { + throw CallStatus.INVALID_ARGUMENT.withCause(e).toRuntimeException(); } } From 218cb00488b6ad97bb426733a311317b6f0cfc5e Mon Sep 17 00:00:00 2001 From: Steve Lord Date: Sat, 16 Mar 2024 09:56:56 -0700 Subject: [PATCH 02/16] GH-37720: [Java][FlightSQL] Implement stateless prepared statements Add tests --- .../adapter/jdbc/JdbcParameterBinder.java | 27 ++++++++++++++++--- .../adapter/jdbc/JdbcParameterBinderTest.java | 25 ++++++++++++----- .../flight/sql/example/FlightSqlExample.java | 26 ++++++++++++++++-- 3 files changed, 67 insertions(+), 11 deletions(-) diff --git a/java/adapter/jdbc/src/main/java/org/apache/arrow/adapter/jdbc/JdbcParameterBinder.java b/java/adapter/jdbc/src/main/java/org/apache/arrow/adapter/jdbc/JdbcParameterBinder.java index 2dfc0658cb8d..5fd02d08636b 100644 --- a/java/adapter/jdbc/src/main/java/org/apache/arrow/adapter/jdbc/JdbcParameterBinder.java +++ b/java/adapter/jdbc/src/main/java/org/apache/arrow/adapter/jdbc/JdbcParameterBinder.java @@ -17,6 +17,11 @@ package org.apache.arrow.adapter.jdbc; +import static java.nio.charset.StandardCharsets.UTF_8; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectOutputStream; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.HashMap; @@ -38,6 +43,7 @@ public class JdbcParameterBinder { private final ColumnBinder[] binders; private final int[] parameterIndices; private int nextRowIndex; + private byte[] bindersAsByteArray; /** * Create a new parameter binder. @@ -51,7 +57,8 @@ private JdbcParameterBinder( final PreparedStatement statement, final VectorSchemaRoot root, final ColumnBinder[] binders, - int[] parameterIndices) { + int[] parameterIndices, + byte[] bindersAsByteArray) { Preconditions.checkArgument( binders.length == parameterIndices.length, "Number of column binders (%s) must equal number of parameter indices (%s)", @@ -61,6 +68,7 @@ private JdbcParameterBinder( this.binders = binders; this.parameterIndices = parameterIndices; this.nextRowIndex = 0; + this.bindersAsByteArray = bindersAsByteArray; } /** @@ -137,7 +145,7 @@ public Builder bind(int parameterIndex, ColumnBinder binder) { } /** Build the binder. */ - public JdbcParameterBinder build() { + public JdbcParameterBinder build() throws IOException { ColumnBinder[] binders = new ColumnBinder[bindings.size()]; int[] parameterIndices = new int[bindings.size()]; int index = 0; @@ -146,7 +154,20 @@ public JdbcParameterBinder build() { parameterIndices[index] = entry.getKey(); index++; } - return new JdbcParameterBinder(statement, root, binders, parameterIndices); + + // Convert parameters to byte array + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + try (ObjectOutputStream outObject = new ObjectOutputStream(outStream)) { + outObject.writeObject(bindings.toString().getBytes(UTF_8)); + outObject.flush(); + } + + // return new JdbcParameterBinder(statement, root, binders, parameterIndices, outStream.toByteArray()); + return new JdbcParameterBinder(statement, root, binders, parameterIndices, outStream.toByteArray()); } } + + public byte[] getBindersAsByteArray() { + return bindersAsByteArray; + } } diff --git a/java/adapter/jdbc/src/test/java/org/apache/arrow/adapter/jdbc/JdbcParameterBinderTest.java b/java/adapter/jdbc/src/test/java/org/apache/arrow/adapter/jdbc/JdbcParameterBinderTest.java index 15b9ab038615..fc64891cf91e 100644 --- a/java/adapter/jdbc/src/test/java/org/apache/arrow/adapter/jdbc/JdbcParameterBinderTest.java +++ b/java/adapter/jdbc/src/test/java/org/apache/arrow/adapter/jdbc/JdbcParameterBinderTest.java @@ -19,6 +19,7 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.io.IOException; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.sql.Date; @@ -80,6 +81,7 @@ import org.apache.arrow.vector.types.pojo.Schema; import org.apache.arrow.vector.util.JsonStringHashMap; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -98,7 +100,7 @@ void afterEach() { } @Test - void bindOrder() throws SQLException { + void bindOrder() throws SQLException, IOException { final Schema schema = new Schema( Arrays.asList( @@ -159,7 +161,7 @@ void bindOrder() throws SQLException { } @Test - void customBinder() throws SQLException { + void customBinder() throws SQLException, IOException { final Schema schema = new Schema(Collections.singletonList( Field.nullable("ints0", new ArrowType.Int(32, true)))); @@ -562,7 +564,7 @@ void testSimpleType(ArrowType arrowType, int jdbcType try (final MockPreparedStatement statement = new MockPreparedStatement(); final VectorSchemaRoot root = VectorSchemaRoot.create(schema, allocator)) { final JdbcParameterBinder binder = - JdbcParameterBinder.builder(statement, root).bindAll().build(); + JdbcParameterBinder.builder(statement, root).bindAll().build(); assertThat(binder.next()).isFalse(); @SuppressWarnings("unchecked") @@ -605,6 +607,8 @@ void testSimpleType(ArrowType arrowType, int jdbcType assertThat(binder.next()).isTrue(); assertThat(statement.getParamValue(1)).isEqualTo(values.get(1)); assertThat(binder.next()).isFalse(); + } catch (IOException e) { + Assertions.fail("Unexpected binding error."); } // Non-nullable (since some types have a specialized binder) @@ -647,6 +651,8 @@ void testSimpleType(ArrowType arrowType, int jdbcType assertThat(binder.next()).isTrue(); assertThat(statement.getParamValue(1)).isEqualTo(values.get(1)); assertThat(binder.next()).isFalse(); + } catch (IOException e) { + Assertions.fail("Unexpected binding error."); } } @@ -660,11 +666,10 @@ void testListType(ArrowType arrowType, TriConsumer void testListType(ArrowType arrowType, TriConsumer void testListType(ArrowType arrowType, TriConsumer void testMapType(ArrowType arrowType, TriConsumer void testMapType(ArrowType arrowType, TriConsumer { assert statementContext != null; PreparedStatement preparedStatement = statementContext.getStatement(); + JdbcParameterBinder binder = null; try { while (flightStream.next()) { final VectorSchemaRoot root = flightStream.getRoot(); - final JdbcParameterBinder binder = JdbcParameterBinder.builder(preparedStatement, root).bindAll().build(); + binder = JdbcParameterBinder.builder(preparedStatement, root).bindAll().build(); while (binder.next()) { // Do not execute() - will be done in a getStream call } @@ -927,6 +931,24 @@ public Runnable acceptPutPreparedStatementQuery(CommandPreparedStatementQuery co .withCause(e) .toRuntimeException()); return; + } catch (IOException e) { + ackStream.onError(CallStatus.INTERNAL + .withDescription("Failed to bind parameters: " + e.getMessage()) + .withCause(e) + .toRuntimeException()); + return; + } + + if (binder != null && binder.getBindersAsByteArray() != null) { + final byte[] byteArray = binder.getBindersAsByteArray(); + final DoPutPreparedStatementResult build = + DoPutPreparedStatementResult.newBuilder() + .setPreparedStatementHandle(ByteString.copyFrom(ByteBuffer.wrap(byteArray))).build(); + + try (final ArrowBuf buffer = rootAllocator.buffer(build.getSerializedSize())) { + buffer.writeBytes(build.toByteArray()); + ackStream.onNext(PutResult.metadata(buffer)); + } } ackStream.onCompleted(); }; From c615f7ad77d4f6cc1a0a81abc82af2bcd201048f Mon Sep 17 00:00:00 2001 From: Steve Lord Date: Mon, 18 Mar 2024 15:19:57 -0700 Subject: [PATCH 03/16] GH-37720: [Java][FlightSQL] Implement stateless prepared statements Part fixed caching of statementContext --- .../adapter/jdbc/JdbcParameterBinder.java | 27 ++----------- .../adapter/jdbc/JdbcParameterBinderTest.java | 25 +++--------- .../flight/sql/example/FlightSqlExample.java | 40 ++++++++++++------- 3 files changed, 35 insertions(+), 57 deletions(-) diff --git a/java/adapter/jdbc/src/main/java/org/apache/arrow/adapter/jdbc/JdbcParameterBinder.java b/java/adapter/jdbc/src/main/java/org/apache/arrow/adapter/jdbc/JdbcParameterBinder.java index 5fd02d08636b..2dfc0658cb8d 100644 --- a/java/adapter/jdbc/src/main/java/org/apache/arrow/adapter/jdbc/JdbcParameterBinder.java +++ b/java/adapter/jdbc/src/main/java/org/apache/arrow/adapter/jdbc/JdbcParameterBinder.java @@ -17,11 +17,6 @@ package org.apache.arrow.adapter.jdbc; -import static java.nio.charset.StandardCharsets.UTF_8; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectOutputStream; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.HashMap; @@ -43,7 +38,6 @@ public class JdbcParameterBinder { private final ColumnBinder[] binders; private final int[] parameterIndices; private int nextRowIndex; - private byte[] bindersAsByteArray; /** * Create a new parameter binder. @@ -57,8 +51,7 @@ private JdbcParameterBinder( final PreparedStatement statement, final VectorSchemaRoot root, final ColumnBinder[] binders, - int[] parameterIndices, - byte[] bindersAsByteArray) { + int[] parameterIndices) { Preconditions.checkArgument( binders.length == parameterIndices.length, "Number of column binders (%s) must equal number of parameter indices (%s)", @@ -68,7 +61,6 @@ private JdbcParameterBinder( this.binders = binders; this.parameterIndices = parameterIndices; this.nextRowIndex = 0; - this.bindersAsByteArray = bindersAsByteArray; } /** @@ -145,7 +137,7 @@ public Builder bind(int parameterIndex, ColumnBinder binder) { } /** Build the binder. */ - public JdbcParameterBinder build() throws IOException { + public JdbcParameterBinder build() { ColumnBinder[] binders = new ColumnBinder[bindings.size()]; int[] parameterIndices = new int[bindings.size()]; int index = 0; @@ -154,20 +146,7 @@ public JdbcParameterBinder build() throws IOException { parameterIndices[index] = entry.getKey(); index++; } - - // Convert parameters to byte array - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - try (ObjectOutputStream outObject = new ObjectOutputStream(outStream)) { - outObject.writeObject(bindings.toString().getBytes(UTF_8)); - outObject.flush(); - } - - // return new JdbcParameterBinder(statement, root, binders, parameterIndices, outStream.toByteArray()); - return new JdbcParameterBinder(statement, root, binders, parameterIndices, outStream.toByteArray()); + return new JdbcParameterBinder(statement, root, binders, parameterIndices); } } - - public byte[] getBindersAsByteArray() { - return bindersAsByteArray; - } } diff --git a/java/adapter/jdbc/src/test/java/org/apache/arrow/adapter/jdbc/JdbcParameterBinderTest.java b/java/adapter/jdbc/src/test/java/org/apache/arrow/adapter/jdbc/JdbcParameterBinderTest.java index fc64891cf91e..15b9ab038615 100644 --- a/java/adapter/jdbc/src/test/java/org/apache/arrow/adapter/jdbc/JdbcParameterBinderTest.java +++ b/java/adapter/jdbc/src/test/java/org/apache/arrow/adapter/jdbc/JdbcParameterBinderTest.java @@ -19,7 +19,6 @@ import static org.assertj.core.api.Assertions.assertThat; -import java.io.IOException; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.sql.Date; @@ -81,7 +80,6 @@ import org.apache.arrow.vector.types.pojo.Schema; import org.apache.arrow.vector.util.JsonStringHashMap; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -100,7 +98,7 @@ void afterEach() { } @Test - void bindOrder() throws SQLException, IOException { + void bindOrder() throws SQLException { final Schema schema = new Schema( Arrays.asList( @@ -161,7 +159,7 @@ void bindOrder() throws SQLException, IOException { } @Test - void customBinder() throws SQLException, IOException { + void customBinder() throws SQLException { final Schema schema = new Schema(Collections.singletonList( Field.nullable("ints0", new ArrowType.Int(32, true)))); @@ -564,7 +562,7 @@ void testSimpleType(ArrowType arrowType, int jdbcType try (final MockPreparedStatement statement = new MockPreparedStatement(); final VectorSchemaRoot root = VectorSchemaRoot.create(schema, allocator)) { final JdbcParameterBinder binder = - JdbcParameterBinder.builder(statement, root).bindAll().build(); + JdbcParameterBinder.builder(statement, root).bindAll().build(); assertThat(binder.next()).isFalse(); @SuppressWarnings("unchecked") @@ -607,8 +605,6 @@ void testSimpleType(ArrowType arrowType, int jdbcType assertThat(binder.next()).isTrue(); assertThat(statement.getParamValue(1)).isEqualTo(values.get(1)); assertThat(binder.next()).isFalse(); - } catch (IOException e) { - Assertions.fail("Unexpected binding error."); } // Non-nullable (since some types have a specialized binder) @@ -651,8 +647,6 @@ void testSimpleType(ArrowType arrowType, int jdbcType assertThat(binder.next()).isTrue(); assertThat(statement.getParamValue(1)).isEqualTo(values.get(1)); assertThat(binder.next()).isFalse(); - } catch (IOException e) { - Assertions.fail("Unexpected binding error."); } } @@ -666,10 +660,11 @@ void testListType(ArrowType arrowType, TriConsumer void testListType(ArrowType arrowType, TriConsumer void testListType(ArrowType arrowType, TriConsumer void testMapType(ArrowType arrowType, TriConsumer void testMapType(ArrowType arrowType, TriConsumer 0) { + final DoPutPreparedStatementResult doPutPreparedStatementResult = + DoPutPreparedStatementResult.newBuilder() + .setPreparedStatementHandle(ByteString.copyFrom(ByteBuffer.wrap(out.toByteArray()))) + .build(); + + // Update prepared statement cache by storing with new handle and remove old entry. + preparedStatementLoadingCache.put(doPutPreparedStatementResult.getPreparedStatementHandle(), + statementContext); + // TODO: If we invalidate old cached entry here this invalidates the statement, which is not what is needed. + // We need to re-cache the statementContext with a new key. + // preparedStatementLoadingCache.invalidate(command.getPreparedStatementHandle()); + + try (final ArrowBuf buffer = rootAllocator.buffer(doPutPreparedStatementResult.getSerializedSize())) { + buffer.writeBytes(doPutPreparedStatementResult.toByteArray()); + ackStream.onNext(PutResult.metadata(buffer)); + } + } } } catch (SQLException e) { @@ -939,17 +962,6 @@ public Runnable acceptPutPreparedStatementQuery(CommandPreparedStatementQuery co return; } - if (binder != null && binder.getBindersAsByteArray() != null) { - final byte[] byteArray = binder.getBindersAsByteArray(); - final DoPutPreparedStatementResult build = - DoPutPreparedStatementResult.newBuilder() - .setPreparedStatementHandle(ByteString.copyFrom(ByteBuffer.wrap(byteArray))).build(); - - try (final ArrowBuf buffer = rootAllocator.buffer(build.getSerializedSize())) { - buffer.writeBytes(build.toByteArray()); - ackStream.onNext(PutResult.metadata(buffer)); - } - } ackStream.onCompleted(); }; } From 417230c0175267ddc45e15d574d2b1270a9c9804 Mon Sep 17 00:00:00 2001 From: Steve Lord Date: Tue, 19 Mar 2024 14:04:25 -0700 Subject: [PATCH 04/16] GH-37720: [Java][FlightSQL] Implement stateless prepared statements PR update --- .../apache/arrow/flight/sql/example/FlightSqlExample.java | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java index 468620c2d2ea..d4dcc6aa7148 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java @@ -948,18 +948,12 @@ public Runnable acceptPutPreparedStatementQuery(CommandPreparedStatementQuery co } } - } catch (SQLException e) { + } catch (SQLException | IOException e) { ackStream.onError(CallStatus.INTERNAL .withDescription("Failed to bind parameters: " + e.getMessage()) .withCause(e) .toRuntimeException()); return; - } catch (IOException e) { - ackStream.onError(CallStatus.INTERNAL - .withDescription("Failed to bind parameters: " + e.getMessage()) - .withCause(e) - .toRuntimeException()); - return; } ackStream.onCompleted(); From 23c79b2d417c958e3406b66986236242a3299307 Mon Sep 17 00:00:00 2001 From: Steve Lord Date: Tue, 19 Mar 2024 15:10:18 -0700 Subject: [PATCH 05/16] GH-37720: [Java][FlightSQL] Implement stateless prepared statements PR update --- .../arrow/flight/sql/FlightSqlClient.java | 26 +++++++++++-------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/java/flight/flight-sql/src/main/java/org/apache/arrow/flight/sql/FlightSqlClient.java b/java/flight/flight-sql/src/main/java/org/apache/arrow/flight/sql/FlightSqlClient.java index 9a46cbf6f7c7..a94dc563cfbc 100644 --- a/java/flight/flight-sql/src/main/java/org/apache/arrow/flight/sql/FlightSqlClient.java +++ b/java/flight/flight-sql/src/main/java/org/apache/arrow/flight/sql/FlightSqlClient.java @@ -1057,17 +1057,21 @@ public FlightInfo execute(final CallOption... options) { if (parameterBindingRoot != null && parameterBindingRoot.getRowCount() > 0) { try (final SyncPutListener putListener = putParameters(descriptor, options)) { - final PutResult read = putListener.read(); - if (read != null) { - try (final ArrowBuf metadata = read.getApplicationMetadata()) { - final FlightSql.DoPutPreparedStatementResult doPutPreparedStatementResult = - FlightSql.DoPutPreparedStatementResult.parseFrom(metadata.nioBuffer()); - descriptor = FlightDescriptor - .command(Any.pack(CommandPreparedStatementQuery.newBuilder() - .setPreparedStatementHandle( - doPutPreparedStatementResult.getPreparedStatementHandle()) - .build()) - .toByteArray()); + if (getParameterSchema().getFields().size() > 0 && + parameterBindingRoot != null && + parameterBindingRoot.getRowCount() > 0) { + final PutResult read = putListener.read(); + if (read != null) { + try (final ArrowBuf metadata = read.getApplicationMetadata()) { + final FlightSql.DoPutPreparedStatementResult doPutPreparedStatementResult = + FlightSql.DoPutPreparedStatementResult.parseFrom(metadata.nioBuffer()); + descriptor = FlightDescriptor + .command(Any.pack(CommandPreparedStatementQuery.newBuilder() + .setPreparedStatementHandle( + doPutPreparedStatementResult.getPreparedStatementHandle()) + .build()) + .toByteArray()); + } } } } catch (final InterruptedException | ExecutionException e) { From 36df229424007e09716c6997e5caa77f5f491249 Mon Sep 17 00:00:00 2001 From: Steve Lord Date: Fri, 12 Apr 2024 16:24:13 -0700 Subject: [PATCH 06/16] Added tests for stateless server --- .../DoPutPreparedStatementResultPOJO.java | 38 ++++ .../flight/sql/example/FlightSqlExample.java | 39 +--- .../example/FlightSqlStatelessExample.java | 198 ++++++++++++++++++ .../arrow/flight/sql/test/TestFlightSql.java | 59 +++--- .../sql/test/TestFlightSqlStateless.java | 88 ++++++++ 5 files changed, 363 insertions(+), 59 deletions(-) create mode 100644 java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/DoPutPreparedStatementResultPOJO.java create mode 100644 java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java create mode 100644 java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/DoPutPreparedStatementResultPOJO.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/DoPutPreparedStatementResultPOJO.java new file mode 100644 index 000000000000..f85b06269443 --- /dev/null +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/DoPutPreparedStatementResultPOJO.java @@ -0,0 +1,38 @@ +/* + * 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.flight.sql.example; + +import java.io.Serializable; + +public class DoPutPreparedStatementResultPOJO implements Serializable { + private transient String query; + private transient byte[] parameters; + + public DoPutPreparedStatementResultPOJO(String query, byte[] parameters) { + this.query = query; + this.parameters = parameters.clone(); + } + + public String getQuery() { + return null; + } + + public byte[] getParameters() { + return null; + } +} diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java index d4dcc6aa7148..3ee3802b231d 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java @@ -124,7 +124,6 @@ import org.apache.arrow.vector.VectorUnloader; import org.apache.arrow.vector.complex.ListVector; import org.apache.arrow.vector.complex.impl.UnionListWriter; -import org.apache.arrow.vector.ipc.ArrowFileWriter; import org.apache.arrow.vector.ipc.WriteChannel; import org.apache.arrow.vector.ipc.message.MessageSerializer; import org.apache.arrow.vector.types.Types.MinorType; @@ -159,12 +158,12 @@ public class FlightSqlExample implements FlightSqlProducer, AutoCloseable { private static final String DATABASE_URI = "jdbc:derby:target/derbyDB"; private static final Logger LOGGER = getLogger(FlightSqlExample.class); - private static final Calendar DEFAULT_CALENDAR = JdbcToArrowUtils.getUtcCalendar(); + protected static final Calendar DEFAULT_CALENDAR = JdbcToArrowUtils.getUtcCalendar(); // ARROW-15315: Use ExecutorService to simulate an async scenario private final ExecutorService executorService = Executors.newFixedThreadPool(10); private final Location location; - private final PoolingDataSource dataSource; - private final BufferAllocator rootAllocator = new RootAllocator(); + protected final PoolingDataSource dataSource; + protected final BufferAllocator rootAllocator = new RootAllocator(); private final Cache> preparedStatementLoadingCache; private final Cache> statementLoadingCache; private final SqlInfoBuilder sqlInfoBuilder; @@ -779,7 +778,7 @@ public void createPreparedStatement(final ActionCreatePreparedStatementRequest r // Running on another thread Future unused = executorService.submit(() -> { try { - final ByteString preparedStatementHandle = copyFrom(randomUUID().toString().getBytes(StandardCharsets.UTF_8)); + final ByteString preparedStatementHandle = copyFrom(request.getQuery().getBytes(UTF_8)); // Ownership of the connection will be passed to the context. Do NOT close! final Connection connection = dataSource.getConnection(); final PreparedStatement preparedStatement = connection.prepareStatement(request.getQuery(), @@ -912,43 +911,17 @@ public Runnable acceptPutPreparedStatementQuery(CommandPreparedStatementQuery co return () -> { assert statementContext != null; PreparedStatement preparedStatement = statementContext.getStatement(); - JdbcParameterBinder binder = null; try { while (flightStream.next()) { final VectorSchemaRoot root = flightStream.getRoot(); - binder = JdbcParameterBinder.builder(preparedStatement, root).bindAll().build(); + final JdbcParameterBinder binder = JdbcParameterBinder.builder(preparedStatement, root).bindAll().build(); while (binder.next()) { // Do not execute() - will be done in a getStream call } - final ByteArrayOutputStream out = new ByteArrayOutputStream(); - try ( - ArrowFileWriter writer = new ArrowFileWriter(root, null, Channels.newChannel(out)) - ) { - writer.start(); - writer.writeBatch(); - } - if (out.size() > 0) { - final DoPutPreparedStatementResult doPutPreparedStatementResult = - DoPutPreparedStatementResult.newBuilder() - .setPreparedStatementHandle(ByteString.copyFrom(ByteBuffer.wrap(out.toByteArray()))) - .build(); - - // Update prepared statement cache by storing with new handle and remove old entry. - preparedStatementLoadingCache.put(doPutPreparedStatementResult.getPreparedStatementHandle(), - statementContext); - // TODO: If we invalidate old cached entry here this invalidates the statement, which is not what is needed. - // We need to re-cache the statementContext with a new key. - // preparedStatementLoadingCache.invalidate(command.getPreparedStatementHandle()); - - try (final ArrowBuf buffer = rootAllocator.buffer(doPutPreparedStatementResult.getSerializedSize())) { - buffer.writeBytes(doPutPreparedStatementResult.toByteArray()); - ackStream.onNext(PutResult.metadata(buffer)); - } - } } - } catch (SQLException | IOException e) { + } catch (SQLException e) { ackStream.onError(CallStatus.INTERNAL .withDescription("Failed to bind parameters: " + e.getMessage()) .withCause(e) diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java new file mode 100644 index 000000000000..65db3a90e276 --- /dev/null +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java @@ -0,0 +1,198 @@ +/* + * 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.flight.sql.example; + +import static java.lang.String.format; +import static org.apache.arrow.adapter.jdbc.JdbcToArrow.sqlToArrowVectorIterator; +import static org.apache.arrow.adapter.jdbc.JdbcToArrowUtils.jdbcToArrowSchema; +import static org.apache.arrow.flight.sql.impl.FlightSql.*; +import static org.slf4j.LoggerFactory.getLogger; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.nio.ByteBuffer; +import java.nio.channels.Channels; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.apache.arrow.adapter.jdbc.ArrowVectorIterator; +import org.apache.arrow.adapter.jdbc.JdbcParameterBinder; +import org.apache.arrow.flight.CallStatus; +import org.apache.arrow.flight.FlightServer; +import org.apache.arrow.flight.FlightStream; +import org.apache.arrow.flight.Location; +import org.apache.arrow.flight.PutResult; +import org.apache.arrow.flight.sql.FlightSqlProducer; +import org.apache.arrow.memory.ArrowBuf; +import org.apache.arrow.memory.BufferAllocator; +import org.apache.arrow.memory.RootAllocator; +import org.apache.arrow.vector.VectorLoader; +import org.apache.arrow.vector.VectorSchemaRoot; +import org.apache.arrow.vector.VectorUnloader; +import org.apache.arrow.vector.ipc.ArrowFileReader; +import org.apache.arrow.vector.ipc.ArrowFileWriter; +import org.apache.arrow.vector.ipc.SeekableReadChannel; +import org.apache.arrow.vector.ipc.message.ArrowBlock; +import org.apache.arrow.vector.types.pojo.Schema; +import org.apache.arrow.vector.util.ByteArrayReadableSeekableByteChannel; +import org.slf4j.Logger; + +import com.google.protobuf.ByteString; + +/** + * Example {@link FlightSqlProducer} implementation showing an Apache Derby backed Flight SQL server that generally + * supports all current features of Flight SQL. + */ +public class FlightSqlStatelessExample extends FlightSqlExample { + private static final Logger LOGGER = getLogger(FlightSqlStatelessExample.class); + + public static void main(String[] args) throws Exception { + Location location = Location.forGrpcInsecure("localhost", 55555); + final FlightSqlStatelessExample example = new FlightSqlStatelessExample(location); + Location listenLocation = Location.forGrpcInsecure("0.0.0.0", 55555); + try (final BufferAllocator allocator = new RootAllocator(); + final FlightServer server = FlightServer.builder(allocator, listenLocation, example).build()) { + server.start(); + server.awaitTermination(); + } + } + + public FlightSqlStatelessExample(final Location location) { + super(location); + } + + @Override + public Runnable acceptPutPreparedStatementQuery(CommandPreparedStatementQuery command, CallContext context, + FlightStream flightStream, StreamListener ackStream) { + + return () -> { + try { + final String query = new String(command.getPreparedStatementHandle().toString("UTF-8")); + final Connection connection = dataSource.getConnection(); + final PreparedStatement preparedStatement = connection.prepareStatement(query, + ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + + while (flightStream.next()) { + final VectorSchemaRoot root = flightStream.getRoot(); + final JdbcParameterBinder binder = JdbcParameterBinder.builder(preparedStatement, root).bindAll().build(); + while (binder.next()) { + // Do not execute() - will be done in a getStream call + } + + final ByteArrayOutputStream parametersStream = new ByteArrayOutputStream(); + try (ArrowFileWriter writer = new ArrowFileWriter(root, null, Channels.newChannel(parametersStream)) + ) { + writer.start(); + writer.writeBatch(); + } + + if (parametersStream.size() > 0) { + final DoPutPreparedStatementResultPOJO doPutPreparedStatementResultPOJO = + new DoPutPreparedStatementResultPOJO(query, parametersStream.toByteArray()); + try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(bos)) { + oos.writeObject((Object) doPutPreparedStatementResultPOJO); + final byte[] doPutPreparedStatementResultPOJOArr = bos.toByteArray(); + final DoPutPreparedStatementResult doPutPreparedStatementResult = + DoPutPreparedStatementResult.newBuilder() + .setPreparedStatementHandle( + ByteString.copyFrom(ByteBuffer.wrap(doPutPreparedStatementResultPOJOArr))) + .build(); + + try (final ArrowBuf buffer = rootAllocator.buffer(doPutPreparedStatementResult.getSerializedSize())) { + buffer.writeBytes(doPutPreparedStatementResult.toByteArray()); + ackStream.onNext(PutResult.metadata(buffer)); + } + } + } + } + + } catch (SQLException | IOException e) { + ackStream.onError(CallStatus.INTERNAL + .withDescription("Failed to bind parameters: " + e.getMessage()) + .withCause(e) + .toRuntimeException()); + return; + } + + ackStream.onCompleted(); + }; + } + + @Override + public void getStreamPreparedStatement(final CommandPreparedStatementQuery command, final CallContext context, + final ServerStreamListener listener) { + try { + final byte[] handle = command.getPreparedStatementHandle().asReadOnlyByteBuffer().array(); + try (ByteArrayInputStream bis = new ByteArrayInputStream(handle); + ObjectInputStream ois = new ObjectInputStream(bis)) { + final DoPutPreparedStatementResultPOJO doPutPreparedStatementResultPOJO = + (DoPutPreparedStatementResultPOJO) ois.readObject(); + final String query = doPutPreparedStatementResultPOJO.getQuery(); + final Connection connection = dataSource.getConnection(); + final PreparedStatement statement = connection.prepareStatement(query, + ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + + try (ArrowFileReader reader = new ArrowFileReader(new SeekableReadChannel( + new ByteArrayReadableSeekableByteChannel( + doPutPreparedStatementResultPOJO.getParameters())), rootAllocator)) { + + for (ArrowBlock arrowBlock : reader.getRecordBlocks()) { + reader.loadRecordBatch(arrowBlock); + VectorSchemaRoot vectorSchemaRootRecover = reader.getVectorSchemaRoot(); + JdbcParameterBinder binder = JdbcParameterBinder.builder(statement, vectorSchemaRootRecover) + .bindAll().build(); + + while (binder.next()) { + try (final ResultSet resultSet = statement.executeQuery()) { + final Schema schema = jdbcToArrowSchema(resultSet.getMetaData(), DEFAULT_CALENDAR); + try (final VectorSchemaRoot vectorSchemaRoot = VectorSchemaRoot.create(schema, rootAllocator)) { + final VectorLoader loader = new VectorLoader(vectorSchemaRoot); + listener.start(vectorSchemaRoot); + + final ArrowVectorIterator iterator = sqlToArrowVectorIterator(resultSet, rootAllocator); + while (iterator.hasNext()) { + final VectorSchemaRoot batch = iterator.next(); + if (batch.getRowCount() == 0) { + break; + } + final VectorUnloader unloader = new VectorUnloader(batch); + loader.load(unloader.getRecordBatch()); + listener.putNext(); + vectorSchemaRoot.clear(); + } + listener.putNext(); + } + } + } + } + } + } + } catch (final SQLException | IOException | ClassNotFoundException e) { + LOGGER.error(format("Failed to getStreamPreparedStatement: <%s>.", e.getMessage()), e); + listener.error(CallStatus.INTERNAL.withDescription("Failed to prepare statement: " + e).toRuntimeException()); + } finally { + listener.completed(); + } + } +} diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSql.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSql.java index a39736e939f0..fdfcb38116bb 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSql.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSql.java @@ -87,58 +87,65 @@ public class TestFlightSql { Field.nullable("FOREIGNID", MinorType.INT.getType()))); private static final List> EXPECTED_RESULTS_FOR_STAR_SELECT_QUERY = ImmutableList.of( asList("1", "one", "1", "1"), asList("2", "zero", "0", "1"), asList("3", "negative one", "-1", "1")); - private static final List> EXPECTED_RESULTS_FOR_PARAMETER_BINDING = ImmutableList.of( + protected static final List> EXPECTED_RESULTS_FOR_PARAMETER_BINDING = ImmutableList.of( asList("1", "one", "1", "1")); private static final Map GET_SQL_INFO_EXPECTED_RESULTS_MAP = new LinkedHashMap<>(); - private static final String LOCALHOST = "localhost"; - private static BufferAllocator allocator; - private static FlightServer server; - private static FlightSqlClient sqlClient; + protected static final String LOCALHOST = "localhost"; + protected static BufferAllocator allocator; + protected static FlightServer server; + protected static FlightSqlClient sqlClient; @BeforeAll public static void setUp() throws Exception { + setUpClientServer(); + setUpExpectedResultsMap(); + } + + private static void setUpClientServer() throws Exception { allocator = new RootAllocator(Integer.MAX_VALUE); final Location serverLocation = Location.forGrpcInsecure(LOCALHOST, 0); server = FlightServer.builder(allocator, serverLocation, new FlightSqlExample(serverLocation)) - .build() - .start(); + .build() + .start(); final Location clientLocation = Location.forGrpcInsecure(LOCALHOST, server.getPort()); sqlClient = new FlightSqlClient(FlightClient.builder(allocator, clientLocation).build()); + } + protected static void setUpExpectedResultsMap() { GET_SQL_INFO_EXPECTED_RESULTS_MAP - .put(Integer.toString(FlightSql.SqlInfo.FLIGHT_SQL_SERVER_NAME_VALUE), "Apache Derby"); + .put(Integer.toString(FlightSql.SqlInfo.FLIGHT_SQL_SERVER_NAME_VALUE), "Apache Derby"); GET_SQL_INFO_EXPECTED_RESULTS_MAP - .put(Integer.toString(FlightSql.SqlInfo.FLIGHT_SQL_SERVER_VERSION_VALUE), "10.14.2.0 - (1828579)"); + .put(Integer.toString(FlightSql.SqlInfo.FLIGHT_SQL_SERVER_VERSION_VALUE), "10.14.2.0 - (1828579)"); GET_SQL_INFO_EXPECTED_RESULTS_MAP - .put(Integer.toString(FlightSql.SqlInfo.FLIGHT_SQL_SERVER_ARROW_VERSION_VALUE), "10.14.2.0 - (1828579)"); + .put(Integer.toString(FlightSql.SqlInfo.FLIGHT_SQL_SERVER_ARROW_VERSION_VALUE), "10.14.2.0 - (1828579)"); GET_SQL_INFO_EXPECTED_RESULTS_MAP - .put(Integer.toString(FlightSql.SqlInfo.FLIGHT_SQL_SERVER_READ_ONLY_VALUE), "false"); + .put(Integer.toString(FlightSql.SqlInfo.FLIGHT_SQL_SERVER_READ_ONLY_VALUE), "false"); GET_SQL_INFO_EXPECTED_RESULTS_MAP - .put(Integer.toString(FlightSql.SqlInfo.SQL_ALL_TABLES_ARE_SELECTABLE_VALUE), "true"); + .put(Integer.toString(FlightSql.SqlInfo.SQL_ALL_TABLES_ARE_SELECTABLE_VALUE), "true"); GET_SQL_INFO_EXPECTED_RESULTS_MAP - .put( - Integer.toString(FlightSql.SqlInfo.SQL_NULL_ORDERING_VALUE), - Integer.toString(FlightSql.SqlNullOrdering.SQL_NULLS_SORTED_AT_END_VALUE)); + .put( + Integer.toString(FlightSql.SqlInfo.SQL_NULL_ORDERING_VALUE), + Integer.toString(FlightSql.SqlNullOrdering.SQL_NULLS_SORTED_AT_END_VALUE)); GET_SQL_INFO_EXPECTED_RESULTS_MAP - .put(Integer.toString(FlightSql.SqlInfo.SQL_DDL_CATALOG_VALUE), "false"); + .put(Integer.toString(FlightSql.SqlInfo.SQL_DDL_CATALOG_VALUE), "false"); GET_SQL_INFO_EXPECTED_RESULTS_MAP - .put(Integer.toString(FlightSql.SqlInfo.SQL_DDL_SCHEMA_VALUE), "true"); + .put(Integer.toString(FlightSql.SqlInfo.SQL_DDL_SCHEMA_VALUE), "true"); GET_SQL_INFO_EXPECTED_RESULTS_MAP - .put(Integer.toString(FlightSql.SqlInfo.SQL_DDL_TABLE_VALUE), "true"); + .put(Integer.toString(FlightSql.SqlInfo.SQL_DDL_TABLE_VALUE), "true"); GET_SQL_INFO_EXPECTED_RESULTS_MAP - .put( - Integer.toString(FlightSql.SqlInfo.SQL_IDENTIFIER_CASE_VALUE), - Integer.toString(SqlSupportedCaseSensitivity.SQL_CASE_SENSITIVITY_UPPERCASE_VALUE)); + .put( + Integer.toString(FlightSql.SqlInfo.SQL_IDENTIFIER_CASE_VALUE), + Integer.toString(SqlSupportedCaseSensitivity.SQL_CASE_SENSITIVITY_UPPERCASE_VALUE)); GET_SQL_INFO_EXPECTED_RESULTS_MAP - .put(Integer.toString(FlightSql.SqlInfo.SQL_IDENTIFIER_QUOTE_CHAR_VALUE), "\""); + .put(Integer.toString(FlightSql.SqlInfo.SQL_IDENTIFIER_QUOTE_CHAR_VALUE), "\""); GET_SQL_INFO_EXPECTED_RESULTS_MAP - .put( - Integer.toString(FlightSql.SqlInfo.SQL_QUOTED_IDENTIFIER_CASE_VALUE), - Integer.toString(SqlSupportedCaseSensitivity.SQL_CASE_SENSITIVITY_CASE_INSENSITIVE_VALUE)); + .put( + Integer.toString(FlightSql.SqlInfo.SQL_QUOTED_IDENTIFIER_CASE_VALUE), + Integer.toString(SqlSupportedCaseSensitivity.SQL_CASE_SENSITIVITY_CASE_INSENSITIVE_VALUE)); GET_SQL_INFO_EXPECTED_RESULTS_MAP - .put(Integer.toString(FlightSql.SqlInfo.SQL_MAX_COLUMNS_IN_TABLE_VALUE), "42"); + .put(Integer.toString(FlightSql.SqlInfo.SQL_MAX_COLUMNS_IN_TABLE_VALUE), "42"); } @AfterAll diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java new file mode 100644 index 000000000000..b9ef6f5ee56b --- /dev/null +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java @@ -0,0 +1,88 @@ +/* + * 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.flight.sql.test; + +import static org.apache.arrow.flight.sql.util.FlightStreamUtils.getResults; +import static org.hamcrest.CoreMatchers.*; + +import org.apache.arrow.flight.FlightClient; +import org.apache.arrow.flight.FlightInfo; +import org.apache.arrow.flight.FlightServer; +import org.apache.arrow.flight.FlightStream; +import org.apache.arrow.flight.Location; +import org.apache.arrow.flight.sql.FlightSqlClient; +import org.apache.arrow.flight.sql.FlightSqlClient.PreparedStatement; +import org.apache.arrow.flight.sql.example.FlightSqlStatelessExample; +import org.apache.arrow.memory.RootAllocator; +import org.apache.arrow.vector.IntVector; +import org.apache.arrow.vector.VectorSchemaRoot; +import org.apache.arrow.vector.types.pojo.Schema; +import org.hamcrest.MatcherAssert; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +/** + * Test direct usage of Flight SQL workflows. + */ +public class TestFlightSqlStateless extends TestFlightSql { + + @BeforeAll + public static void setUp() throws Exception { + setUpClientServer(); + setUpExpectedResultsMap(); + } + + private static void setUpClientServer() throws Exception { + allocator = new RootAllocator(Integer.MAX_VALUE); + + final Location serverLocation = Location.forGrpcInsecure(LOCALHOST, 0); + server = FlightServer.builder(allocator, serverLocation, new FlightSqlStatelessExample(serverLocation)) + .build() + .start(); + + final Location clientLocation = Location.forGrpcInsecure(LOCALHOST, server.getPort()); + sqlClient = new FlightSqlClient(FlightClient.builder(allocator, clientLocation).build()); + } + + @Test + public void testSimplePreparedStatementResultsWithParameterBinding() throws Exception { + try (PreparedStatement prepare = sqlClient.prepare("SELECT * FROM intTable WHERE id = ?")) { + final Schema parameterSchema = prepare.getParameterSchema(); + try (final VectorSchemaRoot insertRoot = VectorSchemaRoot.create(parameterSchema, allocator)) { + insertRoot.allocateNew(); + + final IntVector valueVector = (IntVector) insertRoot.getVector(0); + valueVector.setSafe(0, 1); + insertRoot.setRowCount(1); + + prepare.setParameters(insertRoot); + FlightInfo flightInfo = prepare.execute(); + + FlightStream stream = sqlClient.getStream(flightInfo + .getEndpoints() + .get(0).getTicket()); + + Assertions.assertAll( + () -> MatcherAssert.assertThat(stream.getSchema(), is(SCHEMA_INT_TABLE)), + () -> MatcherAssert.assertThat(getResults(stream), is(EXPECTED_RESULTS_FOR_PARAMETER_BINDING)) + ); + } + } + } +} From e758d348f172cc8a5977a5ba7b6edff80b29603e Mon Sep 17 00:00:00 2001 From: Steve Lord Date: Mon, 15 Apr 2024 18:13:45 -0700 Subject: [PATCH 07/16] Add handling for when not DoPutPreparedStatementResult --- .../DoPutPreparedStatementResultPOJO.java | 8 +- .../flight/sql/example/FlightSqlExample.java | 2 +- .../example/FlightSqlStatelessExample.java | 92 ++++++++++++++----- 3 files changed, 75 insertions(+), 27 deletions(-) diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/DoPutPreparedStatementResultPOJO.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/DoPutPreparedStatementResultPOJO.java index f85b06269443..ace78862b014 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/DoPutPreparedStatementResultPOJO.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/DoPutPreparedStatementResultPOJO.java @@ -20,8 +20,8 @@ import java.io.Serializable; public class DoPutPreparedStatementResultPOJO implements Serializable { - private transient String query; - private transient byte[] parameters; + private String query; + private byte[] parameters; public DoPutPreparedStatementResultPOJO(String query, byte[] parameters) { this.query = query; @@ -29,10 +29,10 @@ public DoPutPreparedStatementResultPOJO(String query, byte[] parameters) { } public String getQuery() { - return null; + return query; } public byte[] getParameters() { - return null; + return parameters; } } diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java index 3ee3802b231d..04dff1fc1498 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java @@ -1281,7 +1281,7 @@ public void getStreamStatement(final TicketStatementQuery ticketStatementQuery, } } - private FlightInfo getFlightInfoForSchema(final T request, final FlightDescriptor descriptor, + protected FlightInfo getFlightInfoForSchema(final T request, final FlightDescriptor descriptor, final Schema schema) { final Ticket ticket = new Ticket(pack(request).toByteArray()); // TODO Support multiple endpoints. diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java index 65db3a90e276..336f44a203a4 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java @@ -28,16 +28,20 @@ import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import java.io.StreamCorruptedException; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; +import java.sql.ResultSetMetaData; import java.sql.SQLException; import org.apache.arrow.adapter.jdbc.ArrowVectorIterator; import org.apache.arrow.adapter.jdbc.JdbcParameterBinder; import org.apache.arrow.flight.CallStatus; +import org.apache.arrow.flight.FlightDescriptor; +import org.apache.arrow.flight.FlightInfo; import org.apache.arrow.flight.FlightServer; import org.apache.arrow.flight.FlightStream; import org.apache.arrow.flight.Location; @@ -109,9 +113,10 @@ public Runnable acceptPutPreparedStatementQuery(CommandPreparedStatementQuery co if (parametersStream.size() > 0) { final DoPutPreparedStatementResultPOJO doPutPreparedStatementResultPOJO = new DoPutPreparedStatementResultPOJO(query, parametersStream.toByteArray()); + try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos)) { - oos.writeObject((Object) doPutPreparedStatementResultPOJO); + oos.writeObject(doPutPreparedStatementResultPOJO); final byte[] doPutPreparedStatementResultPOJOArr = bos.toByteArray(); final DoPutPreparedStatementResult doPutPreparedStatementResult = DoPutPreparedStatementResult.newBuilder() @@ -143,7 +148,8 @@ public Runnable acceptPutPreparedStatementQuery(CommandPreparedStatementQuery co public void getStreamPreparedStatement(final CommandPreparedStatementQuery command, final CallContext context, final ServerStreamListener listener) { try { - final byte[] handle = command.getPreparedStatementHandle().asReadOnlyByteBuffer().array(); + // Case where there are parameters + final byte[] handle = command.getPreparedStatementHandle().toByteArray(); try (ByteArrayInputStream bis = new ByteArrayInputStream(handle); ObjectInputStream ois = new ObjectInputStream(bis)) { final DoPutPreparedStatementResultPOJO doPutPreparedStatementResultPOJO = @@ -164,29 +170,17 @@ public void getStreamPreparedStatement(final CommandPreparedStatementQuery comma .bindAll().build(); while (binder.next()) { - try (final ResultSet resultSet = statement.executeQuery()) { - final Schema schema = jdbcToArrowSchema(resultSet.getMetaData(), DEFAULT_CALENDAR); - try (final VectorSchemaRoot vectorSchemaRoot = VectorSchemaRoot.create(schema, rootAllocator)) { - final VectorLoader loader = new VectorLoader(vectorSchemaRoot); - listener.start(vectorSchemaRoot); - - final ArrowVectorIterator iterator = sqlToArrowVectorIterator(resultSet, rootAllocator); - while (iterator.hasNext()) { - final VectorSchemaRoot batch = iterator.next(); - if (batch.getRowCount() == 0) { - break; - } - final VectorUnloader unloader = new VectorUnloader(batch); - loader.load(unloader.getRecordBatch()); - listener.putNext(); - vectorSchemaRoot.clear(); - } - listener.putNext(); - } - } + executeQuery(statement, listener); } } } + } catch (StreamCorruptedException e) { + // Case where there are no parameters + final String query = new String(command.getPreparedStatementHandle().toString("UTF-8")); + final Connection connection = dataSource.getConnection(); + final PreparedStatement preparedStatement = connection.prepareStatement(query, + ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + executeQuery(preparedStatement, listener); } } catch (final SQLException | IOException | ClassNotFoundException e) { LOGGER.error(format("Failed to getStreamPreparedStatement: <%s>.", e.getMessage()), e); @@ -195,4 +189,58 @@ public void getStreamPreparedStatement(final CommandPreparedStatementQuery comma listener.completed(); } } + + private void executeQuery(PreparedStatement statement, + final ServerStreamListener listener) throws IOException, SQLException { + try (final ResultSet resultSet = statement.executeQuery()) { + final Schema schema = jdbcToArrowSchema(resultSet.getMetaData(), DEFAULT_CALENDAR); + try (final VectorSchemaRoot vectorSchemaRoot = VectorSchemaRoot.create(schema, rootAllocator)) { + final VectorLoader loader = new VectorLoader(vectorSchemaRoot); + listener.start(vectorSchemaRoot); + + final ArrowVectorIterator iterator = sqlToArrowVectorIterator(resultSet, rootAllocator); + while (iterator.hasNext()) { + final VectorSchemaRoot batch = iterator.next(); + if (batch.getRowCount() == 0) { + break; + } + final VectorUnloader unloader = new VectorUnloader(batch); + loader.load(unloader.getRecordBatch()); + listener.putNext(); + vectorSchemaRoot.clear(); + } + listener.putNext(); + } + } + } + + @Override + public FlightInfo getFlightInfoPreparedStatement(final CommandPreparedStatementQuery command, + final CallContext context, + final FlightDescriptor descriptor) { + String query = null; + try { + final byte[] handle = command.getPreparedStatementHandle().toByteArray(); + try (ByteArrayInputStream bis = new ByteArrayInputStream(handle); + ObjectInputStream ois = new ObjectInputStream(bis)) { + final DoPutPreparedStatementResultPOJO doPutPreparedStatementResultPOJO = + (DoPutPreparedStatementResultPOJO) ois.readObject(); + query = doPutPreparedStatementResultPOJO.getQuery(); + } catch (StreamCorruptedException e) { + query = new String(command.getPreparedStatementHandle().toString("UTF-8")); + } + final Connection connection = dataSource.getConnection(); + final PreparedStatement statement = connection.prepareStatement(query, + ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + + ResultSetMetaData metaData = statement.getMetaData(); + return getFlightInfoForSchema(command, descriptor, + jdbcToArrowSchema(metaData, DEFAULT_CALENDAR)); + } catch (final SQLException | IOException | ClassNotFoundException e) { + LOGGER.error( + format("There was a problem executing the prepared statement: <%s>.", e.getMessage()), + e); + throw CallStatus.INTERNAL.withCause(e).toRuntimeException(); + } + } } From 6dd7a9f295c0804030f158924bf1eb77ccd0ab90 Mon Sep 17 00:00:00 2001 From: Steve Lord Date: Tue, 16 Apr 2024 13:41:29 -0700 Subject: [PATCH 08/16] GH 37720:[Java][FlightSQL] Implement stateless prepared statement Code clean up --- .../example/FlightSqlStatelessExample.java | 81 ++++++++++--------- .../sql/test/TestFlightSqlStateless.java | 13 ++- 2 files changed, 54 insertions(+), 40 deletions(-) diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java index 336f44a203a4..3c522528512a 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java @@ -91,10 +91,8 @@ public Runnable acceptPutPreparedStatementQuery(CommandPreparedStatementQuery co return () -> { try { - final String query = new String(command.getPreparedStatementHandle().toString("UTF-8")); - final Connection connection = dataSource.getConnection(); - final PreparedStatement preparedStatement = connection.prepareStatement(query, - ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + final String query = new String(command.getPreparedStatementHandle().toStringUtf8()); + final PreparedStatement preparedStatement = createPreparedStatement(query); while (flightStream.next()) { final VectorSchemaRoot root = flightStream.getRoot(); @@ -114,20 +112,16 @@ public Runnable acceptPutPreparedStatementQuery(CommandPreparedStatementQuery co final DoPutPreparedStatementResultPOJO doPutPreparedStatementResultPOJO = new DoPutPreparedStatementResultPOJO(query, parametersStream.toByteArray()); - try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(bos)) { - oos.writeObject(doPutPreparedStatementResultPOJO); - final byte[] doPutPreparedStatementResultPOJOArr = bos.toByteArray(); - final DoPutPreparedStatementResult doPutPreparedStatementResult = - DoPutPreparedStatementResult.newBuilder() - .setPreparedStatementHandle( - ByteString.copyFrom(ByteBuffer.wrap(doPutPreparedStatementResultPOJOArr))) - .build(); - - try (final ArrowBuf buffer = rootAllocator.buffer(doPutPreparedStatementResult.getSerializedSize())) { - buffer.writeBytes(doPutPreparedStatementResult.toByteArray()); - ackStream.onNext(PutResult.metadata(buffer)); - } + final byte[] doPutPreparedStatementResultPOJOArr = serializePOJO(doPutPreparedStatementResultPOJO); + final DoPutPreparedStatementResult doPutPreparedStatementResult = + DoPutPreparedStatementResult.newBuilder() + .setPreparedStatementHandle( + ByteString.copyFrom(ByteBuffer.wrap(doPutPreparedStatementResultPOJOArr))) + .build(); + + try (final ArrowBuf buffer = rootAllocator.buffer(doPutPreparedStatementResult.getSerializedSize())) { + buffer.writeBytes(doPutPreparedStatementResult.toByteArray()); + ackStream.onNext(PutResult.metadata(buffer)); } } } @@ -150,14 +144,11 @@ public void getStreamPreparedStatement(final CommandPreparedStatementQuery comma try { // Case where there are parameters final byte[] handle = command.getPreparedStatementHandle().toByteArray(); - try (ByteArrayInputStream bis = new ByteArrayInputStream(handle); - ObjectInputStream ois = new ObjectInputStream(bis)) { + try { final DoPutPreparedStatementResultPOJO doPutPreparedStatementResultPOJO = - (DoPutPreparedStatementResultPOJO) ois.readObject(); + deserializePOJO(handle); final String query = doPutPreparedStatementResultPOJO.getQuery(); - final Connection connection = dataSource.getConnection(); - final PreparedStatement statement = connection.prepareStatement(query, - ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + final PreparedStatement statement = createPreparedStatement(query); try (ArrowFileReader reader = new ArrowFileReader(new SeekableReadChannel( new ByteArrayReadableSeekableByteChannel( @@ -176,10 +167,8 @@ public void getStreamPreparedStatement(final CommandPreparedStatementQuery comma } } catch (StreamCorruptedException e) { // Case where there are no parameters - final String query = new String(command.getPreparedStatementHandle().toString("UTF-8")); - final Connection connection = dataSource.getConnection(); - final PreparedStatement preparedStatement = connection.prepareStatement(query, - ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + final String query = new String(command.getPreparedStatementHandle().toStringUtf8()); + final PreparedStatement preparedStatement = createPreparedStatement(query); executeQuery(preparedStatement, listener); } } catch (final SQLException | IOException | ClassNotFoundException e) { @@ -218,20 +207,16 @@ private void executeQuery(PreparedStatement statement, public FlightInfo getFlightInfoPreparedStatement(final CommandPreparedStatementQuery command, final CallContext context, final FlightDescriptor descriptor) { - String query = null; + String query; try { final byte[] handle = command.getPreparedStatementHandle().toByteArray(); - try (ByteArrayInputStream bis = new ByteArrayInputStream(handle); - ObjectInputStream ois = new ObjectInputStream(bis)) { - final DoPutPreparedStatementResultPOJO doPutPreparedStatementResultPOJO = - (DoPutPreparedStatementResultPOJO) ois.readObject(); - query = doPutPreparedStatementResultPOJO.getQuery(); + final DoPutPreparedStatementResultPOJO doPutPreparedStatementResultPOJO = null; + try { + query = deserializePOJO(handle).getQuery(); } catch (StreamCorruptedException e) { - query = new String(command.getPreparedStatementHandle().toString("UTF-8")); + query = new String(command.getPreparedStatementHandle().toStringUtf8()); } - final Connection connection = dataSource.getConnection(); - final PreparedStatement statement = connection.prepareStatement(query, - ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + final PreparedStatement statement = createPreparedStatement(query); ResultSetMetaData metaData = statement.getMetaData(); return getFlightInfoForSchema(command, descriptor, @@ -243,4 +228,24 @@ public FlightInfo getFlightInfoPreparedStatement(final CommandPreparedStatementQ throw CallStatus.INTERNAL.withCause(e).toRuntimeException(); } } + + private DoPutPreparedStatementResultPOJO deserializePOJO(byte[] handle) throws IOException, ClassNotFoundException { + try (ByteArrayInputStream bis = new ByteArrayInputStream(handle); + ObjectInputStream ois = new ObjectInputStream(bis)) { + return (DoPutPreparedStatementResultPOJO) ois.readObject(); + } + } + + private byte[] serializePOJO(DoPutPreparedStatementResultPOJO doPutPreparedStatementResultPOJO) throws IOException { + try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(bos)) { + oos.writeObject(doPutPreparedStatementResultPOJO); + return bos.toByteArray(); + } + } + + private PreparedStatement createPreparedStatement(String query) throws SQLException { + final Connection connection = dataSource.getConnection(); + return connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + } } diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java index b9ef6f5ee56b..77f140da0e32 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java @@ -18,6 +18,7 @@ package org.apache.arrow.flight.sql.test; import static org.apache.arrow.flight.sql.util.FlightStreamUtils.getResults; +import static org.apache.arrow.util.AutoCloseables.close; import static org.hamcrest.CoreMatchers.*; import org.apache.arrow.flight.FlightClient; @@ -33,6 +34,7 @@ import org.apache.arrow.vector.VectorSchemaRoot; import org.apache.arrow.vector.types.pojo.Schema; import org.hamcrest.MatcherAssert; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -48,6 +50,11 @@ public static void setUp() throws Exception { setUpExpectedResultsMap(); } + @AfterAll + public static void tearDown() throws Exception { + close(sqlClient, server, allocator); + } + private static void setUpClientServer() throws Exception { allocator = new RootAllocator(Integer.MAX_VALUE); @@ -72,12 +79,14 @@ public void testSimplePreparedStatementResultsWithParameterBinding() throws Exce insertRoot.setRowCount(1); prepare.setParameters(insertRoot); - FlightInfo flightInfo = prepare.execute(); + final FlightInfo flightInfo = prepare.execute(); - FlightStream stream = sqlClient.getStream(flightInfo + final FlightStream stream = sqlClient.getStream(flightInfo .getEndpoints() .get(0).getTicket()); + // TODO: root is null and getSchema hangs when run as complete suite. + // This works when run as an individual test. Assertions.assertAll( () -> MatcherAssert.assertThat(stream.getSchema(), is(SCHEMA_INT_TABLE)), () -> MatcherAssert.assertThat(getResults(stream), is(EXPECTED_RESULTS_FOR_PARAMETER_BINDING)) From 82a86abc5be6d94dea02923e3ab86fade8cef95d Mon Sep 17 00:00:00 2001 From: Steve Lord Date: Wed, 17 Apr 2024 11:28:53 -0700 Subject: [PATCH 09/16] GH 41262:[Java][FlightSQL] Implement stateless prepared statement PR comment updates --- .../example/FlightSqlStatelessExample.java | 36 +++++++++---------- .../sql/test/TestFlightSqlStateless.java | 20 +++++------ 2 files changed, 26 insertions(+), 30 deletions(-) diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java index 3c522528512a..8cd5d622f738 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java @@ -90,10 +90,8 @@ public Runnable acceptPutPreparedStatementQuery(CommandPreparedStatementQuery co FlightStream flightStream, StreamListener ackStream) { return () -> { - try { - final String query = new String(command.getPreparedStatementHandle().toStringUtf8()); - final PreparedStatement preparedStatement = createPreparedStatement(query); - + final String query = new String(command.getPreparedStatementHandle().toStringUtf8()); + try (PreparedStatement preparedStatement = createPreparedStatement(query)) { while (flightStream.next()) { final VectorSchemaRoot root = flightStream.getRoot(); final JdbcParameterBinder binder = JdbcParameterBinder.builder(preparedStatement, root).bindAll().build(); @@ -141,16 +139,16 @@ public Runnable acceptPutPreparedStatementQuery(CommandPreparedStatementQuery co @Override public void getStreamPreparedStatement(final CommandPreparedStatementQuery command, final CallContext context, final ServerStreamListener listener) { + final byte[] handle = command.getPreparedStatementHandle().toByteArray(); try { // Case where there are parameters - final byte[] handle = command.getPreparedStatementHandle().toByteArray(); try { final DoPutPreparedStatementResultPOJO doPutPreparedStatementResultPOJO = deserializePOJO(handle); final String query = doPutPreparedStatementResultPOJO.getQuery(); - final PreparedStatement statement = createPreparedStatement(query); - try (ArrowFileReader reader = new ArrowFileReader(new SeekableReadChannel( + try (PreparedStatement statement = createPreparedStatement(query); + ArrowFileReader reader = new ArrowFileReader(new SeekableReadChannel( new ByteArrayReadableSeekableByteChannel( doPutPreparedStatementResultPOJO.getParameters())), rootAllocator)) { @@ -168,8 +166,9 @@ public void getStreamPreparedStatement(final CommandPreparedStatementQuery comma } catch (StreamCorruptedException e) { // Case where there are no parameters final String query = new String(command.getPreparedStatementHandle().toStringUtf8()); - final PreparedStatement preparedStatement = createPreparedStatement(query); - executeQuery(preparedStatement, listener); + try (PreparedStatement preparedStatement = createPreparedStatement(query)) { + executeQuery(preparedStatement, listener); + } } } catch (final SQLException | IOException | ClassNotFoundException e) { LOGGER.error(format("Failed to getStreamPreparedStatement: <%s>.", e.getMessage()), e); @@ -207,24 +206,21 @@ private void executeQuery(PreparedStatement statement, public FlightInfo getFlightInfoPreparedStatement(final CommandPreparedStatementQuery command, final CallContext context, final FlightDescriptor descriptor) { - String query; + final byte[] handle = command.getPreparedStatementHandle().toByteArray(); try { - final byte[] handle = command.getPreparedStatementHandle().toByteArray(); - final DoPutPreparedStatementResultPOJO doPutPreparedStatementResultPOJO = null; + String query; try { query = deserializePOJO(handle).getQuery(); } catch (StreamCorruptedException e) { query = new String(command.getPreparedStatementHandle().toStringUtf8()); } - final PreparedStatement statement = createPreparedStatement(query); - - ResultSetMetaData metaData = statement.getMetaData(); - return getFlightInfoForSchema(command, descriptor, - jdbcToArrowSchema(metaData, DEFAULT_CALENDAR)); + try (PreparedStatement statement = createPreparedStatement(query)) { + ResultSetMetaData metaData = statement.getMetaData(); + return getFlightInfoForSchema(command, descriptor, + jdbcToArrowSchema(metaData, DEFAULT_CALENDAR)); + } } catch (final SQLException | IOException | ClassNotFoundException e) { - LOGGER.error( - format("There was a problem executing the prepared statement: <%s>.", e.getMessage()), - e); + LOGGER.error(format("There was a problem executing the prepared statement: <%s>.", e.getMessage()), e); throw CallStatus.INTERNAL.withCause(e).toRuntimeException(); } } diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java index 77f140da0e32..264caf079658 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java @@ -81,16 +81,16 @@ public void testSimplePreparedStatementResultsWithParameterBinding() throws Exce prepare.setParameters(insertRoot); final FlightInfo flightInfo = prepare.execute(); - final FlightStream stream = sqlClient.getStream(flightInfo - .getEndpoints() - .get(0).getTicket()); - - // TODO: root is null and getSchema hangs when run as complete suite. - // This works when run as an individual test. - Assertions.assertAll( - () -> MatcherAssert.assertThat(stream.getSchema(), is(SCHEMA_INT_TABLE)), - () -> MatcherAssert.assertThat(getResults(stream), is(EXPECTED_RESULTS_FOR_PARAMETER_BINDING)) - ); + try (FlightStream stream = sqlClient.getStream(flightInfo.getEndpoints().get(0).getTicket())) { + // TODO: root is null and getSchema hangs when run as complete suite. + // This works when run as an individual test. + final VectorSchemaRoot root = stream.getRoot(); + final Schema schema = root.getSchema(); + Assertions.assertAll( + () -> MatcherAssert.assertThat(schema, is(SCHEMA_INT_TABLE)), + () -> MatcherAssert.assertThat(getResults(stream), is(EXPECTED_RESULTS_FOR_PARAMETER_BINDING)) + ); + } } } } From 15d7b4eb984490b517888620ae3c8935b0cb1f60 Mon Sep 17 00:00:00 2001 From: Steve Lord Date: Wed, 17 Apr 2024 13:40:52 -0700 Subject: [PATCH 10/16] GH 41262:[Java][FlightSQL] Implement stateless prepared statement PR updates --- .../example/FlightSqlStatelessExample.java | 14 ------------- .../sql/test/TestFlightSqlStateless.java | 21 +++++++++++-------- 2 files changed, 12 insertions(+), 23 deletions(-) diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java index 8cd5d622f738..02f679b3efaf 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java @@ -42,14 +42,11 @@ import org.apache.arrow.flight.CallStatus; import org.apache.arrow.flight.FlightDescriptor; import org.apache.arrow.flight.FlightInfo; -import org.apache.arrow.flight.FlightServer; import org.apache.arrow.flight.FlightStream; import org.apache.arrow.flight.Location; import org.apache.arrow.flight.PutResult; import org.apache.arrow.flight.sql.FlightSqlProducer; import org.apache.arrow.memory.ArrowBuf; -import org.apache.arrow.memory.BufferAllocator; -import org.apache.arrow.memory.RootAllocator; import org.apache.arrow.vector.VectorLoader; import org.apache.arrow.vector.VectorSchemaRoot; import org.apache.arrow.vector.VectorUnloader; @@ -70,17 +67,6 @@ public class FlightSqlStatelessExample extends FlightSqlExample { private static final Logger LOGGER = getLogger(FlightSqlStatelessExample.class); - public static void main(String[] args) throws Exception { - Location location = Location.forGrpcInsecure("localhost", 55555); - final FlightSqlStatelessExample example = new FlightSqlStatelessExample(location); - Location listenLocation = Location.forGrpcInsecure("0.0.0.0", 55555); - try (final BufferAllocator allocator = new RootAllocator(); - final FlightServer server = FlightServer.builder(allocator, listenLocation, example).build()) { - server.start(); - server.awaitTermination(); - } - } - public FlightSqlStatelessExample(final Location location) { super(location); } diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java index 264caf079658..b99a17221fc6 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java @@ -22,6 +22,7 @@ import static org.hamcrest.CoreMatchers.*; import org.apache.arrow.flight.FlightClient; +import org.apache.arrow.flight.FlightEndpoint; import org.apache.arrow.flight.FlightInfo; import org.apache.arrow.flight.FlightServer; import org.apache.arrow.flight.FlightStream; @@ -81,15 +82,17 @@ public void testSimplePreparedStatementResultsWithParameterBinding() throws Exce prepare.setParameters(insertRoot); final FlightInfo flightInfo = prepare.execute(); - try (FlightStream stream = sqlClient.getStream(flightInfo.getEndpoints().get(0).getTicket())) { - // TODO: root is null and getSchema hangs when run as complete suite. - // This works when run as an individual test. - final VectorSchemaRoot root = stream.getRoot(); - final Schema schema = root.getSchema(); - Assertions.assertAll( - () -> MatcherAssert.assertThat(schema, is(SCHEMA_INT_TABLE)), - () -> MatcherAssert.assertThat(getResults(stream), is(EXPECTED_RESULTS_FOR_PARAMETER_BINDING)) - ); + for (FlightEndpoint endpoint: flightInfo.getEndpoints()) { + try (FlightStream stream = sqlClient.getStream(endpoint.getTicket())) { + // TODO: root is null and getSchema hangs when run as complete suite. + // This works when run as an individual test. + final VectorSchemaRoot root = stream.getRoot(); + final Schema schema = root.getSchema(); + Assertions.assertAll( + () -> MatcherAssert.assertThat(schema, is(SCHEMA_INT_TABLE)), + () -> MatcherAssert.assertThat(getResults(stream), is(EXPECTED_RESULTS_FOR_PARAMETER_BINDING)) + ); + } } } } From 46d50dc55dafd0ad21b73b0d42d0e48141fa377c Mon Sep 17 00:00:00 2001 From: Steve Lord Date: Thu, 18 Apr 2024 11:35:16 -0700 Subject: [PATCH 11/16] GH 41262:[Java][FlightSQL] Implement stateless prepared statement Build error fix --- .../org/apache/arrow/flight/sql/example/FlightSqlExample.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java index 04dff1fc1498..bb7444856668 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java @@ -778,7 +778,7 @@ public void createPreparedStatement(final ActionCreatePreparedStatementRequest r // Running on another thread Future unused = executorService.submit(() -> { try { - final ByteString preparedStatementHandle = copyFrom(request.getQuery().getBytes(UTF_8)); + final ByteString preparedStatementHandle = copyFrom(request.getQuery().getBytes(StandardCharsets.UTF_8)); // Ownership of the connection will be passed to the context. Do NOT close! final Connection connection = dataSource.getConnection(); final PreparedStatement preparedStatement = connection.prepareStatement(request.getQuery(), From fe4ad62b3ffb9d2bc3cd2f0e53196e1d6b367b41 Mon Sep 17 00:00:00 2001 From: Mateusz Rzeszutek Date: Tue, 7 May 2024 17:39:57 +0200 Subject: [PATCH 12/16] Fix the TestFlightSqlStateless test --- .../flight/sql/example/FlightSqlExample.java | 15 +++++++++++++++ .../sql/example/FlightSqlStatelessExample.java | 15 +++++++++------ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java index bb7444856668..0b755f7d241a 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java @@ -280,6 +280,9 @@ private static boolean removeDerbyDatabaseIfExists() { private static boolean populateDerbyDatabase() { try (final Connection connection = DriverManager.getConnection("jdbc:derby:target/derbyDB;create=true"); Statement statement = connection.createStatement()) { + + dropTable(statement, "intTable"); + dropTable(statement, "foreignTable"); statement.execute("CREATE TABLE foreignTable (" + "id INT not null primary key GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), " + "foreignName varchar(100), " + @@ -302,6 +305,18 @@ private static boolean populateDerbyDatabase() { return true; } + private static void dropTable(final Statement statement, final String tableName) throws SQLException { + try { + statement.execute("DROP TABLE " + tableName); + } catch (SQLException e) { + // sql error code for "object does not exist"; which is fine, we're trying to delete the table + // see https://db.apache.org/derby/docs/10.17/ref/rrefexcept71493.html + if (!"42Y55".equals(e.getSQLState())) { + throw e; + } + } + } + private static ArrowType getArrowTypeFromJdbcType(final int jdbcDataType, final int precision, final int scale) { try { return JdbcToArrowUtils.getArrowTypeFromJdbcType(new JdbcFieldInfo(jdbcDataType, precision, scale), diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java index 02f679b3efaf..8d1d901eb94e 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java @@ -77,7 +77,8 @@ public Runnable acceptPutPreparedStatementQuery(CommandPreparedStatementQuery co return () -> { final String query = new String(command.getPreparedStatementHandle().toStringUtf8()); - try (PreparedStatement preparedStatement = createPreparedStatement(query)) { + try (Connection connection = dataSource.getConnection(); + PreparedStatement preparedStatement = createPreparedStatement(connection, query)) { while (flightStream.next()) { final VectorSchemaRoot root = flightStream.getRoot(); final JdbcParameterBinder binder = JdbcParameterBinder.builder(preparedStatement, root).bindAll().build(); @@ -133,7 +134,8 @@ public void getStreamPreparedStatement(final CommandPreparedStatementQuery comma deserializePOJO(handle); final String query = doPutPreparedStatementResultPOJO.getQuery(); - try (PreparedStatement statement = createPreparedStatement(query); + try (Connection connection = dataSource.getConnection(); + PreparedStatement statement = createPreparedStatement(connection, query); ArrowFileReader reader = new ArrowFileReader(new SeekableReadChannel( new ByteArrayReadableSeekableByteChannel( doPutPreparedStatementResultPOJO.getParameters())), rootAllocator)) { @@ -152,7 +154,8 @@ public void getStreamPreparedStatement(final CommandPreparedStatementQuery comma } catch (StreamCorruptedException e) { // Case where there are no parameters final String query = new String(command.getPreparedStatementHandle().toStringUtf8()); - try (PreparedStatement preparedStatement = createPreparedStatement(query)) { + try (Connection connection = dataSource.getConnection(); + PreparedStatement preparedStatement = createPreparedStatement(connection, query)) { executeQuery(preparedStatement, listener); } } @@ -200,7 +203,8 @@ public FlightInfo getFlightInfoPreparedStatement(final CommandPreparedStatementQ } catch (StreamCorruptedException e) { query = new String(command.getPreparedStatementHandle().toStringUtf8()); } - try (PreparedStatement statement = createPreparedStatement(query)) { + try (Connection connection = dataSource.getConnection(); + PreparedStatement statement = createPreparedStatement(connection, query)) { ResultSetMetaData metaData = statement.getMetaData(); return getFlightInfoForSchema(command, descriptor, jdbcToArrowSchema(metaData, DEFAULT_CALENDAR)); @@ -226,8 +230,7 @@ private byte[] serializePOJO(DoPutPreparedStatementResultPOJO doPutPreparedState } } - private PreparedStatement createPreparedStatement(String query) throws SQLException { - final Connection connection = dataSource.getConnection(); + private PreparedStatement createPreparedStatement(Connection connection, String query) throws SQLException { return connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); } } From 20887c1845c8802e1b286e594c25d690b34608fe Mon Sep 17 00:00:00 2001 From: Steve Lord Date: Wed, 15 May 2024 10:40:24 -0700 Subject: [PATCH 13/16] GH 41262:[Java][FlightSQL] Implement stateless prepared statement Clean up Derby database at end of class test --- .../apache/arrow/flight/sql/example/FlightSqlExample.java | 4 +++- .../org/apache/arrow/flight/sql/test/TestFlightSql.java | 1 + .../arrow/flight/sql/test/TestFlightSqlStateless.java | 8 +++----- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java index 0b755f7d241a..cc56a0b69792 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java @@ -248,7 +248,7 @@ public FlightSqlExample(final Location location) { } - private static boolean removeDerbyDatabaseIfExists() { + public static boolean removeDerbyDatabaseIfExists() { boolean wasSuccess; final Path path = Paths.get("target" + File.separator + "derbyDB"); @@ -778,6 +778,8 @@ public void close() throws Exception { LOGGER.error(format("Failed to close resources: <%s>", t.getMessage()), t); } + // removeDerbyDatabaseIfExists(); + AutoCloseables.close(dataSource, rootAllocator); } diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSql.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSql.java index fdfcb38116bb..f400051ae53e 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSql.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSql.java @@ -151,6 +151,7 @@ protected static void setUpExpectedResultsMap() { @AfterAll public static void tearDown() throws Exception { close(sqlClient, server, allocator); + FlightSqlExample.removeDerbyDatabaseIfExists(); } private static List> getNonConformingResultsForGetSqlInfo(final List> results) { diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java index b99a17221fc6..42e748291970 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java @@ -54,6 +54,7 @@ public static void setUp() throws Exception { @AfterAll public static void tearDown() throws Exception { close(sqlClient, server, allocator); + FlightSqlStatelessExample.removeDerbyDatabaseIfExists(); } private static void setUpClientServer() throws Exception { @@ -68,6 +69,7 @@ private static void setUpClientServer() throws Exception { sqlClient = new FlightSqlClient(FlightClient.builder(allocator, clientLocation).build()); } + @Override @Test public void testSimplePreparedStatementResultsWithParameterBinding() throws Exception { try (PreparedStatement prepare = sqlClient.prepare("SELECT * FROM intTable WHERE id = ?")) { @@ -84,12 +86,8 @@ public void testSimplePreparedStatementResultsWithParameterBinding() throws Exce for (FlightEndpoint endpoint: flightInfo.getEndpoints()) { try (FlightStream stream = sqlClient.getStream(endpoint.getTicket())) { - // TODO: root is null and getSchema hangs when run as complete suite. - // This works when run as an individual test. - final VectorSchemaRoot root = stream.getRoot(); - final Schema schema = root.getSchema(); Assertions.assertAll( - () -> MatcherAssert.assertThat(schema, is(SCHEMA_INT_TABLE)), + () -> MatcherAssert.assertThat(stream.getSchema(), is(SCHEMA_INT_TABLE)), () -> MatcherAssert.assertThat(getResults(stream), is(EXPECTED_RESULTS_FOR_PARAMETER_BINDING)) ); } From 5a867eeeeb6a0d2896594ca095c6eb3dfe2e74ab Mon Sep 17 00:00:00 2001 From: Steve Lord Date: Wed, 15 May 2024 13:46:41 -0700 Subject: [PATCH 14/16] GH 41262:[Java][FlightSQL] Implement stateless prepared statement Continue to attempt to clean Derby database --- .../arrow/flight/sql/example/FlightSqlExample.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java index cc56a0b69792..9bcb46e3399a 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java @@ -252,6 +252,16 @@ public static boolean removeDerbyDatabaseIfExists() { boolean wasSuccess; final Path path = Paths.get("target" + File.separator + "derbyDB"); + try (final Connection connection = DriverManager.getConnection("jdbc:derby:target/derbyDB;create=true"); + Statement statement = connection.createStatement()) { + + dropTable(statement, "intTable"); + dropTable(statement, "foreignTable"); + } catch (final SQLException e) { + LOGGER.error(format("Failed attempt to drop tables in DerbyDB: <%s>", e.getMessage()), e); + return false; + } + try (final Stream walk = Files.walk(path)) { /* * Iterate over all paths to delete, mapping each path to the outcome of its own From a43c06bba23bfe5b7fd53b3f2ee0744b5d0dca39 Mon Sep 17 00:00:00 2001 From: Steve Lord Date: Wed, 15 May 2024 14:28:48 -0700 Subject: [PATCH 15/16] GH 41262:[Java][FlightSQL] Implement stateless prepared statement Fix Derby clean up --- .../flight/sql/example/FlightSqlExample.java | 59 ++++++++++--------- 1 file changed, 31 insertions(+), 28 deletions(-) diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java index 9bcb46e3399a..f24e448d9720 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java @@ -252,36 +252,39 @@ public static boolean removeDerbyDatabaseIfExists() { boolean wasSuccess; final Path path = Paths.get("target" + File.separator + "derbyDB"); - try (final Connection connection = DriverManager.getConnection("jdbc:derby:target/derbyDB;create=true"); - Statement statement = connection.createStatement()) { - - dropTable(statement, "intTable"); - dropTable(statement, "foreignTable"); - } catch (final SQLException e) { - LOGGER.error(format("Failed attempt to drop tables in DerbyDB: <%s>", e.getMessage()), e); - return false; - } + if (Files.exists(path)) { + try (final Connection connection = DriverManager.getConnection("jdbc:derby:target/derbyDB;create=true"); + Statement statement = connection.createStatement()) { + dropTable(statement, "intTable"); + dropTable(statement, "foreignTable"); + } catch (final SQLException e) { + LOGGER.error(format("Failed attempt to drop tables in DerbyDB: <%s>", e.getMessage()), e); + return false; + } - try (final Stream walk = Files.walk(path)) { - /* - * Iterate over all paths to delete, mapping each path to the outcome of its own - * deletion as a boolean representing whether or not each individual operation was - * successful; then reduce all booleans into a single answer, and store that into - * `wasSuccess`, which will later be returned by this method. - * If for whatever reason the resulting `Stream` is empty, throw an `IOException`; - * this not expected. - */ - wasSuccess = walk.sorted(Comparator.reverseOrder()).map(Path::toFile).map(File::delete) - .reduce(Boolean::logicalAnd).orElseThrow(IOException::new); - } catch (IOException e) { - /* - * The only acceptable scenario for an `IOException` to be thrown here is if - * an attempt to delete an non-existing file takes place -- which should be - * alright, since they would be deleted anyway. - */ - if (!(wasSuccess = e instanceof NoSuchFileException)) { - LOGGER.error(format("Failed attempt to clear DerbyDB: <%s>", e.getMessage()), e); + try (final Stream walk = Files.walk(path)) { + /* + * Iterate over all paths to delete, mapping each path to the outcome of its own + * deletion as a boolean representing whether or not each individual operation was + * successful; then reduce all booleans into a single answer, and store that into + * `wasSuccess`, which will later be returned by this method. + * If for whatever reason the resulting `Stream` is empty, throw an `IOException`; + * this not expected. + */ + wasSuccess = walk.sorted(Comparator.reverseOrder()).map(Path::toFile).map(File::delete) + .reduce(Boolean::logicalAnd).orElseThrow(IOException::new); + } catch (IOException e) { + /* + * The only acceptable scenario for an `IOException` to be thrown here is if + * an attempt to delete an non-existing file takes place -- which should be + * alright, since they would be deleted anyway. + */ + if (!(wasSuccess = e instanceof NoSuchFileException)) { + LOGGER.error(format("Failed attempt to clear DerbyDB: <%s>", e.getMessage()), e); + } } + } else { + return true; } return wasSuccess; From 641a519322b2b1240f42ed7a06604a2d0e97b7f0 Mon Sep 17 00:00:00 2001 From: Steve Lord Date: Wed, 15 May 2024 21:51:57 -0700 Subject: [PATCH 16/16] GH 41262:[Java][FlightSQL] Implement stateless prepared statement Create separate database per test class --- .../flight/sql/example/FlightSqlExample.java | 85 ++++++++----------- .../example/FlightSqlStatelessExample.java | 6 +- .../arrow/flight/sql/test/TestFlightSql.java | 5 +- .../sql/test/TestFlightSqlStateless.java | 5 +- 4 files changed, 46 insertions(+), 55 deletions(-) diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java index f24e448d9720..36362fd8681d 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlExample.java @@ -156,9 +156,10 @@ * supports all current features of Flight SQL. */ public class FlightSqlExample implements FlightSqlProducer, AutoCloseable { - private static final String DATABASE_URI = "jdbc:derby:target/derbyDB"; private static final Logger LOGGER = getLogger(FlightSqlExample.class); protected static final Calendar DEFAULT_CALENDAR = JdbcToArrowUtils.getUtcCalendar(); + public static final String DB_NAME = "derbyDB"; + private final String databaseUri; // ARROW-15315: Use ExecutorService to simulate an async scenario private final ExecutorService executorService = Executors.newFixedThreadPool(10); private final Location location; @@ -170,7 +171,7 @@ public class FlightSqlExample implements FlightSqlProducer, AutoCloseable { public static void main(String[] args) throws Exception { Location location = Location.forGrpcInsecure("localhost", 55555); - final FlightSqlExample example = new FlightSqlExample(location); + final FlightSqlExample example = new FlightSqlExample(location, DB_NAME); Location listenLocation = Location.forGrpcInsecure("0.0.0.0", 55555); try (final BufferAllocator allocator = new RootAllocator(); final FlightServer server = FlightServer.builder(allocator, listenLocation, example).build()) { @@ -179,13 +180,14 @@ public static void main(String[] args) throws Exception { } } - public FlightSqlExample(final Location location) { + public FlightSqlExample(final Location location, final String dbName) { // TODO Constructor should not be doing work. checkState( - removeDerbyDatabaseIfExists() && populateDerbyDatabase(), + removeDerbyDatabaseIfExists(dbName) && populateDerbyDatabase(dbName), "Failed to reset Derby database!"); + databaseUri = "jdbc:derby:target/" + dbName; final ConnectionFactory connectionFactory = - new DriverManagerConnectionFactory(DATABASE_URI, new Properties()); + new DriverManagerConnectionFactory(databaseUri, new Properties()); final PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null); final ObjectPool connectionPool = new GenericObjectPool<>(poolableConnectionFactory); @@ -248,50 +250,37 @@ public FlightSqlExample(final Location location) { } - public static boolean removeDerbyDatabaseIfExists() { + public static boolean removeDerbyDatabaseIfExists(final String dbName) { boolean wasSuccess; - final Path path = Paths.get("target" + File.separator + "derbyDB"); - - if (Files.exists(path)) { - try (final Connection connection = DriverManager.getConnection("jdbc:derby:target/derbyDB;create=true"); - Statement statement = connection.createStatement()) { - dropTable(statement, "intTable"); - dropTable(statement, "foreignTable"); - } catch (final SQLException e) { - LOGGER.error(format("Failed attempt to drop tables in DerbyDB: <%s>", e.getMessage()), e); - return false; + final Path path = Paths.get("target" + File.separator + dbName); + + try (final Stream walk = Files.walk(path)) { + /* + * Iterate over all paths to delete, mapping each path to the outcome of its own + * deletion as a boolean representing whether or not each individual operation was + * successful; then reduce all booleans into a single answer, and store that into + * `wasSuccess`, which will later be returned by this method. + * If for whatever reason the resulting `Stream` is empty, throw an `IOException`; + * this not expected. + */ + wasSuccess = walk.sorted(Comparator.reverseOrder()).map(Path::toFile).map(File::delete) + .reduce(Boolean::logicalAnd).orElseThrow(IOException::new); + } catch (IOException e) { + /* + * The only acceptable scenario for an `IOException` to be thrown here is if + * an attempt to delete an non-existing file takes place -- which should be + * alright, since they would be deleted anyway. + */ + if (!(wasSuccess = e instanceof NoSuchFileException)) { + LOGGER.error(format("Failed attempt to clear DerbyDB: <%s>", e.getMessage()), e); } - - try (final Stream walk = Files.walk(path)) { - /* - * Iterate over all paths to delete, mapping each path to the outcome of its own - * deletion as a boolean representing whether or not each individual operation was - * successful; then reduce all booleans into a single answer, and store that into - * `wasSuccess`, which will later be returned by this method. - * If for whatever reason the resulting `Stream` is empty, throw an `IOException`; - * this not expected. - */ - wasSuccess = walk.sorted(Comparator.reverseOrder()).map(Path::toFile).map(File::delete) - .reduce(Boolean::logicalAnd).orElseThrow(IOException::new); - } catch (IOException e) { - /* - * The only acceptable scenario for an `IOException` to be thrown here is if - * an attempt to delete an non-existing file takes place -- which should be - * alright, since they would be deleted anyway. - */ - if (!(wasSuccess = e instanceof NoSuchFileException)) { - LOGGER.error(format("Failed attempt to clear DerbyDB: <%s>", e.getMessage()), e); - } - } - } else { - return true; } return wasSuccess; } - private static boolean populateDerbyDatabase() { - try (final Connection connection = DriverManager.getConnection("jdbc:derby:target/derbyDB;create=true"); + private static boolean populateDerbyDatabase(final String dbName) { + try (final Connection connection = DriverManager.getConnection("jdbc:derby:target/" + dbName + ";create=true"); Statement statement = connection.createStatement()) { dropTable(statement, "intTable"); @@ -791,8 +780,6 @@ public void close() throws Exception { LOGGER.error(format("Failed to close resources: <%s>", t.getMessage()), t); } - // removeDerbyDatabaseIfExists(); - AutoCloseables.close(dataSource, rootAllocator); } @@ -1066,7 +1053,7 @@ public void getStreamTables(final CommandGetTables command, final CallContext co final String[] tableTypes = protocolSize == 0 ? null : protocolStringList.toArray(new String[protocolSize]); - try (final Connection connection = DriverManager.getConnection(DATABASE_URI); + try (final Connection connection = DriverManager.getConnection(databaseUri); final VectorSchemaRoot vectorSchemaRoot = getTablesRoot( connection.getMetaData(), rootAllocator, @@ -1117,7 +1104,7 @@ public void getStreamPrimaryKeys(final CommandGetPrimaryKeys command, final Call final String schema = command.hasDbSchema() ? command.getDbSchema() : null; final String table = command.getTable(); - try (Connection connection = DriverManager.getConnection(DATABASE_URI)) { + try (Connection connection = DriverManager.getConnection(databaseUri)) { final ResultSet primaryKeys = connection.getMetaData().getPrimaryKeys(catalog, schema, table); final VarCharVector catalogNameVector = new VarCharVector("catalog_name", rootAllocator); @@ -1171,7 +1158,7 @@ public void getStreamExportedKeys(final CommandGetExportedKeys command, final Ca String schema = command.hasDbSchema() ? command.getDbSchema() : null; String table = command.getTable(); - try (Connection connection = DriverManager.getConnection(DATABASE_URI); + try (Connection connection = DriverManager.getConnection(databaseUri); ResultSet keys = connection.getMetaData().getExportedKeys(catalog, schema, table); VectorSchemaRoot vectorSchemaRoot = createVectors(keys)) { listener.start(vectorSchemaRoot); @@ -1196,7 +1183,7 @@ public void getStreamImportedKeys(final CommandGetImportedKeys command, final Ca String schema = command.hasDbSchema() ? command.getDbSchema() : null; String table = command.getTable(); - try (Connection connection = DriverManager.getConnection(DATABASE_URI); + try (Connection connection = DriverManager.getConnection(databaseUri); ResultSet keys = connection.getMetaData().getImportedKeys(catalog, schema, table); VectorSchemaRoot vectorSchemaRoot = createVectors(keys)) { listener.start(vectorSchemaRoot); @@ -1224,7 +1211,7 @@ public void getStreamCrossReference(CommandGetCrossReference command, CallContex final String pkTable = command.getPkTable(); final String fkTable = command.getFkTable(); - try (Connection connection = DriverManager.getConnection(DATABASE_URI); + try (Connection connection = DriverManager.getConnection(databaseUri); ResultSet keys = connection.getMetaData() .getCrossReference(pkCatalog, pkSchema, pkTable, fkCatalog, fkSchema, fkTable); VectorSchemaRoot vectorSchemaRoot = createVectors(keys)) { diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java index 8d1d901eb94e..c79c09c0967d 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/example/FlightSqlStatelessExample.java @@ -66,9 +66,11 @@ */ public class FlightSqlStatelessExample extends FlightSqlExample { private static final Logger LOGGER = getLogger(FlightSqlStatelessExample.class); + public static final String DB_NAME = "derbyStatelessDB"; - public FlightSqlStatelessExample(final Location location) { - super(location); + + public FlightSqlStatelessExample(final Location location, final String dbName) { + super(location, dbName); } @Override diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSql.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSql.java index f400051ae53e..ffffdd62ac95 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSql.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSql.java @@ -105,7 +105,8 @@ private static void setUpClientServer() throws Exception { allocator = new RootAllocator(Integer.MAX_VALUE); final Location serverLocation = Location.forGrpcInsecure(LOCALHOST, 0); - server = FlightServer.builder(allocator, serverLocation, new FlightSqlExample(serverLocation)) + server = FlightServer.builder(allocator, serverLocation, + new FlightSqlExample(serverLocation, FlightSqlExample.DB_NAME)) .build() .start(); @@ -151,7 +152,7 @@ protected static void setUpExpectedResultsMap() { @AfterAll public static void tearDown() throws Exception { close(sqlClient, server, allocator); - FlightSqlExample.removeDerbyDatabaseIfExists(); + FlightSqlExample.removeDerbyDatabaseIfExists(FlightSqlExample.DB_NAME); } private static List> getNonConformingResultsForGetSqlInfo(final List> results) { diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java index 42e748291970..09c7b2ef87f4 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java @@ -54,14 +54,15 @@ public static void setUp() throws Exception { @AfterAll public static void tearDown() throws Exception { close(sqlClient, server, allocator); - FlightSqlStatelessExample.removeDerbyDatabaseIfExists(); + FlightSqlStatelessExample.removeDerbyDatabaseIfExists(FlightSqlStatelessExample.DB_NAME); } private static void setUpClientServer() throws Exception { allocator = new RootAllocator(Integer.MAX_VALUE); final Location serverLocation = Location.forGrpcInsecure(LOCALHOST, 0); - server = FlightServer.builder(allocator, serverLocation, new FlightSqlStatelessExample(serverLocation)) + server = FlightServer.builder(allocator, serverLocation, + new FlightSqlStatelessExample(serverLocation, FlightSqlStatelessExample.DB_NAME)) .build() .start();