Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
Expand Down Expand Up @@ -52,6 +54,7 @@ public final class ArrowFlightJdbcFlightStreamResultSet

private final ArrowFlightConnection connection;
private final FlightInfo flightInfo;
private List<CloseableEndpointStreamPair> endpoints = List.of();
private CloseableEndpointStreamPair currentEndpointData;
private FlightEndpointDataQueue flightEndpointDataQueue;
private volatile boolean cancelled;
Expand Down Expand Up @@ -149,8 +152,8 @@ protected AvaticaResultSet execute() throws SQLException {

private void populateData() throws SQLException {
loadNewQueue();
enqueueEndpointData(
flightEndpointDataQueue, connection.getClientHandler().getStreams(flightInfo));
endpoints = connection.getClientHandler().getStreams(flightInfo);
enqueueEndpointData(flightEndpointDataQueue, endpoints);
loadNewFlightStream();

// Ownership of the root will be passed onto the cursor.
Expand Down Expand Up @@ -180,6 +183,35 @@ public byte[] getAppMetadata() {
return flightInfo.getAppMetadata();
}

/**
* Returns a copy of the application metadata attached to the currently loaded row batch, or null
* if there is no such metadata. See {@link #getLatestMetadataByEndpoint()} for trailing metadata.
*/
public byte[] getCurrentBatchMetadata() {
if (currentEndpointData == null
|| currentEndpointData.getStream().getLatestMetadata() == null) {
return null;
}
return currentEndpointData.getLatestMetadata();
}

/**
* Returns a copy of the last non-null application metadata read from each endpoint, in {@link
* FlightInfo#getEndpoints()} order. An entry is null until the driver reads metadata from that
* endpoint. Each data or metadata-only message carrying metadata replaces the previous value.
*
* <p>The driver may read ahead on other endpoints. After {@link #next()} has reached the end of
* all streams, the entries include any trailers, even from endpoints with no rows. Retrieve them
* before closing the result set.
*/
public List<byte[]> getLatestMetadataByEndpoint() {
final List<byte[]> metadata = new ArrayList<>(endpoints.size());
for (CloseableEndpointStreamPair endpoint : endpoints) {
metadata.add(endpoint.getLatestMetadata());
}
return metadata;
}

@Override
public boolean next() throws SQLException {
if (currentVectorSchemaRoot == null) {
Expand All @@ -202,7 +234,7 @@ public boolean next() throws SQLException {
try {
if (currentEndpointData != null) {
currentEndpointData.getStream().getRoot().clear();
if (currentEndpointData.getStream().next()) {
if (currentEndpointData.next()) {
populateDataForCurrentFlightStream();
continue;
}
Expand Down Expand Up @@ -276,6 +308,7 @@ public synchronized void close() {
} catch (final Exception e) {
throw new RuntimeException(e);
} finally {
endpoints = List.of();
super.close();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import org.apache.arrow.flight.FlightStream;
import org.apache.arrow.flight.sql.FlightSqlClient;
import org.apache.arrow.memory.ArrowBuf;
import org.apache.arrow.util.AutoCloseables;
import org.apache.arrow.util.Preconditions;

Expand All @@ -26,6 +27,8 @@ public class CloseableEndpointStreamPair implements AutoCloseable {

private final FlightStream stream;
private final FlightSqlClient client;
// The queue worker can still be reading this endpoint while JDBC iterates another one.
private volatile byte[] latestMetadata;

public CloseableEndpointStreamPair(FlightStream stream, FlightSqlClient client) {
this.stream = Preconditions.checkNotNull(stream);
Expand All @@ -36,6 +39,26 @@ public FlightStream getStream() {
return stream;
}

/** Advances the stream and saves any metadata before the next message releases its buffer. */
public boolean next() {
if (!stream.next()) {
return false;
}
ArrowBuf metadata = stream.getLatestMetadata();
if (metadata != null) {
latestMetadata =
metadata.getBytesAsArray(
metadata.readerIndex(), Math.toIntExact(metadata.readableBytes()));
}
return true;
}

/** Returns a copy of the last non-null metadata seen by {@link #next()}, or null if none. */
public byte[] getLatestMetadata() {
final byte[] value = latestMetadata;
return value == null ? null : value.clone();
}

@Override
public void close() throws Exception {
AutoCloseables.close(stream, client);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,9 @@ public synchronized void enqueue(final CloseableEndpointStreamPair endpointReque
completionService.submit(
() -> {
// `FlightStream#next` will block until new data can be read or stream is over.
while (endpointRequest.getStream().next()) {
if (endpointRequest.getStream().getRoot().getRowCount() > 0) {
while (endpointRequest.next()) {
if (endpointRequest.getStream().hasRoot()
&& endpointRequest.getStream().getRoot().getRowCount() > 0) {
return endpointRequest;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,11 @@
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.arrow.driver.jdbc.utils.CoreMockedSqlProducers;
import org.apache.arrow.driver.jdbc.utils.FallbackFlightSqlProducer;
import org.apache.arrow.driver.jdbc.utils.MockFlightSqlProducer;
import org.apache.arrow.driver.jdbc.utils.PartitionedFlightSqlProducer;
import org.apache.arrow.flight.Action;
import org.apache.arrow.flight.FlightConstants;
Expand All @@ -62,6 +64,7 @@
import org.apache.arrow.flight.Location;
import org.apache.arrow.flight.Result;
import org.apache.arrow.flight.Ticket;
import org.apache.arrow.memory.ArrowBuf;
import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.memory.RootAllocator;
import org.apache.arrow.vector.IntVector;
Expand All @@ -75,14 +78,17 @@
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

public class ResultSetTest {
private static final Random RANDOM = new Random(10);

private static final MockFlightSqlProducer PRODUCER = CoreMockedSqlProducers.getLegacyProducer();

@RegisterExtension
public static final FlightServerTestExtension FLIGHT_SERVER_TEST_EXTENSION =
FlightServerTestExtension.createStandardTestExtension(
CoreMockedSqlProducers.getLegacyProducer());
FlightServerTestExtension.createStandardTestExtension(PRODUCER);

private static Connection connection;

Expand Down Expand Up @@ -888,6 +894,120 @@ public void testShouldRunSelectQueryWithEmptyVectorsEmbedded() throws Exception
}
}

private static ArrowBuf metadata(BufferAllocator allocator, int value) {
ArrowBuf buffer = allocator.buffer(1);
buffer.writeByte(value);
return buffer;
}

@Test
public void testQueryTimeoutAfterProgressMetadata() throws Exception {
final Schema schema =
new Schema(Collections.singletonList(Field.nullable("id", Types.MinorType.INT.getType())));
final String query = "select delayed first batch";
CountDownLatch release = new CountDownLatch(1);
PRODUCER.addSelectQuery(
query,
schema,
List.of(
listener -> {
try (BufferAllocator allocator = new RootAllocator();
VectorSchemaRoot data = VectorSchemaRoot.create(schema, allocator)) {
listener.start(data);
listener.putMetadata(metadata(allocator, 1));
release.await(30, TimeUnit.SECONDS);
if (!listener.isCancelled()) {
((IntVector) data.getVector(0)).setSafe(0, 10);
data.setRowCount(1);
listener.putNext();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
listener.completed();
}
}));
try (Statement statement = connection.createStatement()) {
statement.setQueryTimeout(1);
try {
SQLException error = assertThrows(SQLException.class, () -> statement.executeQuery(query));
assertThat(error.getCause().getCause(), is(instanceOf(SQLTimeoutException.class)));
} finally {
release.countDown();
}
}
}

@ParameterizedTest
@ValueSource(booleans = {true, false})
public void testBatchMetadata(boolean withRows) throws Exception {
final Schema schema =
new Schema(Collections.singletonList(Field.nullable("id", Types.MinorType.INT.getType())));
final String query = withRows ? "select batch metadata" : "select empty batch metadata";
PRODUCER.addSelectQuery(
query,
schema,
List.of(
listener -> {
try (BufferAllocator allocator = new RootAllocator();
VectorSchemaRoot data = VectorSchemaRoot.create(schema, allocator)) {
listener.start(data);
if (withRows) {
IntVector ids = (IntVector) data.getVector(0);
ids.setSafe(0, 10);
ids.setSafe(1, 20);
data.setRowCount(2);
listener.putNext(metadata(allocator, 42));
listener.putMetadata(metadata(allocator, 43));
listener.putMetadata(metadata(allocator, 44));
data.setRowCount(1);
listener.putNext();
}
listener.putMetadata(metadata(allocator, 99));
} finally {
listener.completed();
}
},
listener -> {
try (BufferAllocator allocator = new RootAllocator()) {
listener.putMetadata(metadata(allocator, 98));
} finally {
listener.completed();
}
},
FlightProducer.ServerStreamListener::completed));
try (Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(query)) {
ArrowFlightJdbcFlightStreamResultSet flight =
result.unwrap(ArrowFlightJdbcFlightStreamResultSet.class);
if (withRows) {
assertTrue(result.next());
assertEquals(10, result.getInt(1));
byte[] first = flight.getCurrentBatchMetadata();
assertArrayEquals(new byte[] {42}, first);
first[0] = 0;
assertTrue(result.next());
assertEquals(20, result.getInt(1));
assertArrayEquals(new byte[] {42}, flight.getCurrentBatchMetadata());
List<byte[]> snapshot = flight.getLatestMetadataByEndpoint();
assertTrue(result.next());
assertNull(flight.getCurrentBatchMetadata());
assertArrayEquals(new byte[] {42}, snapshot.get(0));
assertArrayEquals(new byte[] {44}, flight.getLatestMetadataByEndpoint().get(0));
}
assertFalse(result.next());
assertNull(flight.getCurrentBatchMetadata());
List<byte[]> trailers = flight.getLatestMetadataByEndpoint();
assertEquals(3, trailers.size());
assertArrayEquals(new byte[] {99}, trailers.get(0));
assertArrayEquals(new byte[] {98}, trailers.get(1));
assertNull(trailers.get(2));
trailers.get(1)[0] = 0;
assertFalse(result.next());
assertArrayEquals(new byte[] {98}, flight.getLatestMetadataByEndpoint().get(1));
}
}

@Test
public void testResultSetAppMetadata() throws Exception {
try (Statement statement = connection.createStatement();
Expand Down