mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(redshift): support Redshift Spectrum phase one (#4184)
* feat: add Redshift Spectrum metadata catalog * feat: parse Redshift Spectrum DDL * feat: read Redshift Spectrum CSV data from S3 * feat: classify and rewrite Redshift Spectrum queries * feat: materialize Spectrum rows into PostgreSQL * feat: intercept Redshift Spectrum queries * test: cover Redshift Spectrum wire integration * docs: document Redshift Spectrum phase one * fix: handle Spectrum extended queries * fix: preserve Spectrum query protocol state * fix: resolve Spectrum cursor paging and extended query race condition - Await prior backend queries before streaming local Spectrum Extended Query frames - Drop synthetic Spectrum Parse/Bind/Describe/Close frames from coordinator pending queue - Support server-side cursor pagination with PortalSuspended across multiple Execute cycles - Add cascade cleanup for unexhausted portal cursors when prepared statement is closed * fix(redshift): register SpectrumMaterializer for GraalVM runtime initialization * fix(redshift): forward non-Spectrum queries and register storage models for reflection * docs(redshift): clarify Spectrum temp table lifecycle across protocols * docs(redshift): note that Simple Query Spectrum creates a temp table per query --------- Signed-off-by: Vũ Thế Huy <31652864+vuthehuyht@users.noreply.github.com>
This commit is contained in:
1 parent
5f1f80b496
commit
a450cdc9b0
30 files changed
+2955
-6
No files matched your search
+196
@@ -0,0 +1,196 @@
|
||||
package io.github.hectorvent.floci.services.redshift;
|
||||
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.awaitility.Awaitility;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
class RedshiftSpectrumIntegrationTest {
|
||||
|
||||
@Inject
|
||||
RedshiftService redshiftService;
|
||||
|
||||
@Inject
|
||||
S3Service s3Service;
|
||||
|
||||
private String clusterId;
|
||||
private String bucket;
|
||||
|
||||
@BeforeAll
|
||||
static void requireDocker() {
|
||||
Assumptions.assumeTrue(isDockerAvailable(), "Docker daemon must be available for Redshift Spectrum integration tests");
|
||||
}
|
||||
|
||||
private static boolean isDockerAvailable() {
|
||||
try {
|
||||
Process process = new ProcessBuilder("docker", "version", "--format", "{{.Server.Version}}")
|
||||
.redirectErrorStream(true)
|
||||
.start();
|
||||
int exit = process.waitFor();
|
||||
return exit == 0;
|
||||
} catch (Exception ignored) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanUp() {
|
||||
if (clusterId != null) {
|
||||
redshiftService.deleteCluster(clusterId);
|
||||
}
|
||||
if (bucket != null) {
|
||||
s3Service.deleteObject(bucket, "events/part-1.csv");
|
||||
s3Service.deleteObject(bucket, "invalid/part-1.csv");
|
||||
s3Service.deleteBucket(bucket);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(60)
|
||||
void queriesCsvExternalTableThroughRedshiftWireProxy() throws SQLException {
|
||||
bucket = "spectrum-it-" + System.nanoTime();
|
||||
s3Service.createBucket(bucket, "us-east-1");
|
||||
s3Service.putObject(bucket, "events/part-1.csv",
|
||||
"id,name\n1,Alice\n2,Bob\n".getBytes(StandardCharsets.UTF_8), "text/csv", null);
|
||||
clusterId = "it-spectrum-" + System.nanoTime();
|
||||
Cluster cluster = redshiftService.createCluster(clusterId, "dc2.large", "admin", "Secret123");
|
||||
|
||||
try (Connection connection = waitForConnection(cluster, "admin", "Secret123");
|
||||
Statement statement = connection.createStatement()) {
|
||||
statement.execute("CREATE EXTERNAL SCHEMA analytics FROM DATA CATALOG DATABASE 'dev' IAM_ROLE 'role'");
|
||||
SQLException duplicateSchema = assertThrows(SQLException.class, () -> statement.execute(
|
||||
"CREATE EXTERNAL SCHEMA analytics FROM DATA CATALOG DATABASE 'dev' IAM_ROLE 'role'"));
|
||||
assertEquals("42P06", duplicateSchema.getSQLState());
|
||||
statement.execute("CREATE EXTERNAL TABLE analytics.events (id INTEGER, name VARCHAR) "
|
||||
+ "STORED AS TEXTFILE LOCATION 's3://" + bucket + "/events/' "
|
||||
+ "TBLPROPERTIES ('skip.header.line.count'='1')");
|
||||
try (ResultSet rows = statement.executeQuery("SELECT id, name FROM analytics.events")) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals(1, rows.getInt("id"));
|
||||
assertEquals("Alice", rows.getString("name"));
|
||||
assertTrue(rows.next());
|
||||
assertEquals(2, rows.getInt("id"));
|
||||
assertEquals("Bob", rows.getString("name"));
|
||||
assertTrue(!rows.next());
|
||||
}
|
||||
s3Service.putObject(bucket, "invalid/part-1.csv", "invalid,Bad\n".getBytes(StandardCharsets.UTF_8),
|
||||
"text/csv", null);
|
||||
statement.execute("CREATE EXTERNAL TABLE analytics.invalid_events (id INTEGER, name VARCHAR) "
|
||||
+ "STORED AS TEXTFILE LOCATION 's3://" + bucket + "/invalid/'");
|
||||
SQLException invalidRow = assertThrows(SQLException.class,
|
||||
() -> statement.executeQuery("SELECT * FROM analytics.invalid_events"));
|
||||
assertEquals("22000", invalidRow.getSQLState());
|
||||
try (ResultSet healthCheck = statement.executeQuery("SELECT 1")) {
|
||||
assertTrue(healthCheck.next());
|
||||
assertEquals(1, healthCheck.getInt(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(60)
|
||||
void queriesCsvExternalTableThroughExtendedQueryProtocol() throws SQLException {
|
||||
bucket = "spectrum-it-ext-" + System.nanoTime();
|
||||
s3Service.createBucket(bucket, "us-east-1");
|
||||
s3Service.putObject(bucket, "events/part-1.csv",
|
||||
"id,name\n1,Alice\n2,Bob\n".getBytes(StandardCharsets.UTF_8), "text/csv", null);
|
||||
clusterId = "it-spectrum-ext-" + System.nanoTime();
|
||||
Cluster cluster = redshiftService.createCluster(clusterId, "dc2.large", "admin", "Secret123");
|
||||
|
||||
String url = "jdbc:postgresql://127.0.0.1:" + cluster.getEndpoint().getPort()
|
||||
+ "/dev?socketTimeout=20&loginTimeout=20";
|
||||
try (Connection connection = Awaitility.await().atMost(Duration.ofSeconds(30)).pollDelay(Duration.ZERO)
|
||||
.pollInterval(Duration.ofMillis(500)).ignoreExceptions()
|
||||
.until(() -> DriverManager.getConnection(url, "admin", "Secret123"), Objects::nonNull);
|
||||
Statement setup = connection.createStatement()) {
|
||||
setup.execute("CREATE EXTERNAL SCHEMA analytics_ext FROM DATA CATALOG DATABASE 'dev' IAM_ROLE 'role'");
|
||||
setup.execute("CREATE EXTERNAL TABLE analytics_ext.events (id INTEGER, name VARCHAR) "
|
||||
+ "STORED AS TEXTFILE LOCATION 's3://" + bucket + "/events/' "
|
||||
+ "TBLPROPERTIES ('skip.header.line.count'='1')");
|
||||
// Phase 1 does not support bind-parameterized Spectrum predicates (SpectrumQueryClassifier
|
||||
// rejects them), so this exercises Extended Query with a literal predicate: pgjdbc still
|
||||
// uses Parse/Bind/Describe/Execute/Sync for PreparedStatement even without a '?'.
|
||||
try (java.sql.PreparedStatement prepared = connection.prepareStatement(
|
||||
"SELECT id, name FROM analytics_ext.events WHERE id = 1")) {
|
||||
// Forces pgjdbc to send Describe('S', ...) (Describe Statement, not just Describe
|
||||
// Portal): the response must be ParameterDescription followed by RowDescription/NoData.
|
||||
assertEquals(0, prepared.getParameterMetaData().getParameterCount());
|
||||
try (ResultSet rows = prepared.executeQuery()) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals(1, rows.getInt("id"));
|
||||
assertEquals("Alice", rows.getString("name"));
|
||||
assertTrue(!rows.next());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(60)
|
||||
void pagesSpectrumRowsAcrossMultipleExecutesWhenFetchSizeIsSet() throws SQLException {
|
||||
bucket = "spectrum-it-fetch-" + System.nanoTime();
|
||||
s3Service.createBucket(bucket, "us-east-1");
|
||||
s3Service.putObject(bucket, "events/part-1.csv",
|
||||
"id,name\n1,Alice\n2,Bob\n3,Carol\n4,Dave\n5,Eve\n".getBytes(StandardCharsets.UTF_8),
|
||||
"text/csv", null);
|
||||
clusterId = "it-spectrum-fetch-" + System.nanoTime();
|
||||
Cluster cluster = redshiftService.createCluster(clusterId, "dc2.large", "admin", "Secret123");
|
||||
|
||||
String url = "jdbc:postgresql://127.0.0.1:" + cluster.getEndpoint().getPort()
|
||||
+ "/dev?socketTimeout=20&loginTimeout=20";
|
||||
try (Connection connection = Awaitility.await().atMost(Duration.ofSeconds(30)).pollDelay(Duration.ZERO)
|
||||
.pollInterval(Duration.ofMillis(500)).ignoreExceptions()
|
||||
.until(() -> DriverManager.getConnection(url, "admin", "Secret123"), Objects::nonNull);
|
||||
Statement setup = connection.createStatement()) {
|
||||
setup.execute("CREATE EXTERNAL SCHEMA analytics_fetch FROM DATA CATALOG DATABASE 'dev' IAM_ROLE 'role'");
|
||||
setup.execute("CREATE EXTERNAL TABLE analytics_fetch.events (id INTEGER, name VARCHAR) "
|
||||
+ "STORED AS TEXTFILE LOCATION 's3://" + bucket + "/events/' "
|
||||
+ "TBLPROPERTIES ('skip.header.line.count'='1')");
|
||||
|
||||
// Fetch size only becomes a real server-side cursor (Execute with maxRows > 0, answered
|
||||
// with PortalSuspended) in pgjdbc when autoCommit is off.
|
||||
connection.setAutoCommit(false);
|
||||
try (java.sql.PreparedStatement prepared = connection.prepareStatement(
|
||||
"SELECT id, name FROM analytics_fetch.events")) {
|
||||
prepared.setFetchSize(2);
|
||||
List<Integer> ids = new ArrayList<>();
|
||||
try (ResultSet rows = prepared.executeQuery()) {
|
||||
while (rows.next()) {
|
||||
ids.add(rows.getInt("id"));
|
||||
}
|
||||
}
|
||||
assertEquals(List.of(1, 2, 3, 4, 5), ids);
|
||||
}
|
||||
connection.commit();
|
||||
}
|
||||
}
|
||||
|
||||
private static Connection waitForConnection(Cluster cluster, String username, String password) throws SQLException {
|
||||
String url = "jdbc:postgresql://127.0.0.1:" + cluster.getEndpoint().getPort() + "/dev";
|
||||
return Awaitility.await().atMost(Duration.ofSeconds(30)).pollDelay(Duration.ZERO)
|
||||
.pollInterval(Duration.ofMillis(500)).ignoreExceptions()
|
||||
.until(() -> DriverManager.getConnection(url, username, password), Objects::nonNull);
|
||||
}
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package io.github.hectorvent.floci.services.redshift.spectrum;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class SpectrumCatalogTest {
|
||||
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private SpectrumCatalog catalog;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
StorageFactory factory = mock(StorageFactory.class);
|
||||
when(factory.create(eq("redshift"), eq("redshift-spectrum-schemas.json"), any(TypeReference.class)))
|
||||
.thenReturn(AccountAwareStorageBackend.inMemory(ACCOUNT));
|
||||
when(factory.create(eq("redshift"), eq("redshift-spectrum-tables.json"), any(TypeReference.class)))
|
||||
.thenReturn(AccountAwareStorageBackend.inMemory(ACCOUNT));
|
||||
catalog = new SpectrumCatalog(factory);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createsAndLooksUpExternalSchema() {
|
||||
SpectrumExternalSchema schema = new SpectrumExternalSchema(
|
||||
ACCOUNT, "dev", "analytics", "s3://warehouse/root/", null);
|
||||
|
||||
catalog.createSchema(schema);
|
||||
|
||||
assertEquals(java.util.Optional.of(schema), catalog.schema(ACCOUNT, "dev", "analytics"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createsAndListsExternalTablesInStableNameOrder() {
|
||||
SpectrumExternalTable second = table("zebra");
|
||||
SpectrumExternalTable first = table("alpha");
|
||||
|
||||
catalog.createTable(second);
|
||||
catalog.createTable(first);
|
||||
|
||||
assertEquals(List.of(first, second), catalog.tablesForSchema(ACCOUNT, "dev", "analytics"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsDuplicateTableAndDuplicateColumnNames() {
|
||||
catalog.createTable(table("events"));
|
||||
|
||||
SpectrumSqlException duplicate = assertThrows(SpectrumSqlException.class,
|
||||
() -> catalog.createTable(table("events")));
|
||||
assertEquals("42P07", duplicate.sqlState());
|
||||
assertThrows(IllegalArgumentException.class, () -> new SpectrumExternalTable(
|
||||
ACCOUNT, "dev", "analytics", "duplicate",
|
||||
List.of(new SpectrumColumn("id", SpectrumColumn.Type.BIGINT),
|
||||
new SpectrumColumn("id", SpectrumColumn.Type.VARCHAR)),
|
||||
"s3://warehouse/events/", ',', '"', '\\', "\\N", 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void isolatesLookupsByAccountAndClearsState() {
|
||||
SpectrumExternalTable table = table("events");
|
||||
catalog.createTable(table);
|
||||
|
||||
assertTrue(catalog.table("111111111111", "dev", "analytics", "events").isEmpty());
|
||||
catalog.clear();
|
||||
assertTrue(catalog.tablesForSchema(ACCOUNT, "dev", "analytics").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void validatesLocationAndColumnType() {
|
||||
assertThrows(IllegalArgumentException.class, () -> new SpectrumExternalSchema(
|
||||
ACCOUNT, "dev", "analytics", "https://example.invalid/data", null));
|
||||
assertThrows(IllegalArgumentException.class, () -> new SpectrumColumn("id", null));
|
||||
}
|
||||
|
||||
private static SpectrumExternalTable table(String name) {
|
||||
return new SpectrumExternalTable(
|
||||
ACCOUNT, "dev", "analytics", name,
|
||||
List.of(new SpectrumColumn("id", SpectrumColumn.Type.BIGINT)),
|
||||
"s3://warehouse/events/", ',', '"', '\\', "\\N", 1);
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package io.github.hectorvent.floci.services.redshift.spectrum;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.Socket;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class SpectrumInterceptorTest {
|
||||
|
||||
private SpectrumCatalog catalog;
|
||||
private SpectrumMaterializer materializer;
|
||||
private SpectrumInterceptor interceptor;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
catalog = mock(SpectrumCatalog.class);
|
||||
materializer = mock(SpectrumMaterializer.class);
|
||||
interceptor = new SpectrumInterceptor(catalog, new SpectrumStatementParser(), new SpectrumQueryClassifier(),
|
||||
null, mock(SpectrumS3Reader.class), materializer);
|
||||
}
|
||||
|
||||
@Test
|
||||
void storesExternalSchemaAndTableDdl() {
|
||||
SpectrumInterceptor.Decision schema = interceptor.intercept(
|
||||
"CREATE EXTERNAL SCHEMA analytics FROM DATA CATALOG DATABASE 'dev' IAM_ROLE 'role'",
|
||||
"000000000000", "dev", null);
|
||||
SpectrumInterceptor.Decision table = interceptor.intercept(
|
||||
"CREATE EXTERNAL TABLE analytics.events (id INTEGER) STORED AS TEXTFILE LOCATION 's3://b/events/'",
|
||||
"000000000000", "dev", null);
|
||||
|
||||
assertInstanceOf(SpectrumInterceptor.Decision.Handled.class, schema);
|
||||
assertInstanceOf(SpectrumInterceptor.Decision.Handled.class, table);
|
||||
}
|
||||
|
||||
@Test
|
||||
void forwardsLocalQueryAndRewritesCatalogResolvedExternalQuery() {
|
||||
SpectrumExternalTable table = new SpectrumExternalTable("000000000000", "dev", "analytics", "events",
|
||||
List.of(new SpectrumColumn("id", SpectrumColumn.Type.INTEGER)), "s3://b/events/", ',', '"', '\\', "\\N", 0);
|
||||
SpectrumExternalSchema schema = new SpectrumExternalSchema("000000000000", "dev", "analytics",
|
||||
"s3://b/root/", null);
|
||||
SpectrumMaterializer.Materialization materialization = new SpectrumMaterializer.Materialization(
|
||||
"spectrum_tmp_x", table.columns());
|
||||
when(catalog.table("000000000000", "dev", "analytics", "events")).thenReturn(java.util.Optional.of(table));
|
||||
when(catalog.schema("000000000000", "dev", "analytics")).thenReturn(java.util.Optional.of(schema));
|
||||
when(materializer.nextIdentifier()).thenReturn("spectrum_tmp_x");
|
||||
when(materializer.materialize(any(), any(), any(), any(), eq("spectrum_tmp_x"))).thenReturn(materialization);
|
||||
|
||||
assertInstanceOf(SpectrumInterceptor.Decision.Forward.class,
|
||||
interceptor.intercept("SELECT * FROM local.events", "000000000000", "dev", null));
|
||||
SpectrumInterceptor.Decision decision = interceptor.intercept(
|
||||
"SELECT * FROM analytics.events", "000000000000", "dev", null);
|
||||
SpectrumInterceptor.Decision.Rewritten rewritten = assertInstanceOf(
|
||||
SpectrumInterceptor.Decision.Rewritten.class, decision);
|
||||
assertEquals("SELECT * FROM \"spectrum_tmp_x\"", rewritten.sql());
|
||||
}
|
||||
|
||||
@Test
|
||||
void delegatesCleanupToMaterializer() {
|
||||
Socket backend = mock(Socket.class);
|
||||
SpectrumMaterializer.Materialization materialization = new SpectrumMaterializer.Materialization(
|
||||
"spectrum_tmp_x", List.of());
|
||||
interceptor.cleanup(backend, materialization);
|
||||
verify(materializer).cleanup(backend, materialization);
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package io.github.hectorvent.floci.services.redshift.spectrum;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class SpectrumMaterializerTest {
|
||||
|
||||
@Test
|
||||
void materializesRowsWithGeneratedIdentifierAndCopyFraming() throws Exception {
|
||||
try (ServerSocket listener = new ServerSocket(0); Socket backend = new Socket("localhost", listener.getLocalPort())) {
|
||||
ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||
Future<byte[]> captured = executor.submit(() -> serve(listener));
|
||||
SpectrumS3Reader reader = mock(SpectrumS3Reader.class);
|
||||
when(reader.read(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()))
|
||||
.thenReturn(Stream.of(new SpectrumRow(Arrays.asList("1", null)), new SpectrumRow(List.of("two", "x"))));
|
||||
SpectrumExternalTable table = new SpectrumExternalTable("000000000000", "dev", "analytics", "events",
|
||||
List.of(new SpectrumColumn("id", SpectrumColumn.Type.INTEGER),
|
||||
new SpectrumColumn("value", SpectrumColumn.Type.VARCHAR)),
|
||||
"s3://warehouse/events/", ',', '"', '\\', "\\N", 0);
|
||||
|
||||
SpectrumMaterializer.Materialization materialization = new SpectrumMaterializer()
|
||||
.materialize(backend, table, null, reader);
|
||||
new SpectrumMaterializer().cleanup(backend, materialization);
|
||||
|
||||
byte[] copy = captured.get();
|
||||
assertTrue(materialization.identifier().startsWith("spectrum_tmp_"));
|
||||
assertFalse(materialization.identifier().contains("events"));
|
||||
assertTrue(new String(copy, StandardCharsets.UTF_8).contains("1\t\\N\ntwo\tx\n"));
|
||||
executor.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] serve(ServerSocket listener) throws IOException {
|
||||
try (Socket socket = listener.accept()) {
|
||||
InputStream input = socket.getInputStream();
|
||||
OutputStream output = socket.getOutputStream();
|
||||
ByteArrayOutputStream copyRows = new ByteArrayOutputStream();
|
||||
readQuery(input);
|
||||
send(output, 'C', "CREATE 0\0".getBytes(StandardCharsets.UTF_8));
|
||||
send(output, 'Z', new byte[]{'I'});
|
||||
readQuery(input);
|
||||
send(output, 'G', new byte[]{0, 0, 0});
|
||||
while (true) {
|
||||
Frame frame = readFrame(input);
|
||||
if (frame.type() == 'c') {
|
||||
break;
|
||||
}
|
||||
if (frame.type() == 'd') {
|
||||
copyRows.write(frame.body());
|
||||
}
|
||||
}
|
||||
send(output, 'C', "COPY 2\0".getBytes(StandardCharsets.UTF_8));
|
||||
send(output, 'Z', new byte[]{'I'});
|
||||
readQuery(input);
|
||||
send(output, 'C', "DROP TABLE\0".getBytes(StandardCharsets.UTF_8));
|
||||
send(output, 'Z', new byte[]{'I'});
|
||||
return copyRows.toByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
private static void readQuery(InputStream input) throws IOException {
|
||||
Frame frame = readFrame(input);
|
||||
if (frame.type() != 'Q') {
|
||||
throw new IOException("expected query");
|
||||
}
|
||||
}
|
||||
|
||||
private static Frame readFrame(InputStream input) throws IOException {
|
||||
int type = input.read();
|
||||
if (type < 0) {
|
||||
throw new IOException("unexpected EOF");
|
||||
}
|
||||
byte[] length = input.readNBytes(4);
|
||||
int size = ((length[0] & 0xff) << 24) | ((length[1] & 0xff) << 16)
|
||||
| ((length[2] & 0xff) << 8) | (length[3] & 0xff);
|
||||
return new Frame((char) type, input.readNBytes(size - 4));
|
||||
}
|
||||
|
||||
private static void send(OutputStream output, char type, byte[] body) throws IOException {
|
||||
int size = body.length + 4;
|
||||
output.write(type);
|
||||
output.write((size >>> 24) & 0xff);
|
||||
output.write((size >>> 16) & 0xff);
|
||||
output.write((size >>> 8) & 0xff);
|
||||
output.write(size & 0xff);
|
||||
output.write(body);
|
||||
output.flush();
|
||||
}
|
||||
|
||||
private record Frame(char type, byte[] body) {
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package io.github.hectorvent.floci.services.redshift.spectrum;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class SpectrumQueryClassifierTest {
|
||||
|
||||
private final SpectrumQueryClassifier classifier = new SpectrumQueryClassifier();
|
||||
|
||||
@Test
|
||||
void classifiesProjectionAndSimplePredicates() {
|
||||
SpectrumQuery query = classifier.classify(
|
||||
"SELECT id, name FROM analytics.events WHERE id >= 2 AND name <> 'x'", 0).orElseThrow();
|
||||
|
||||
assertEquals("analytics", query.schemaName());
|
||||
assertEquals("events", query.tableName());
|
||||
assertEquals("id, name", query.projectionSql());
|
||||
assertEquals("id >= 2 AND name <> 'x'", query.predicateSql());
|
||||
}
|
||||
|
||||
@Test
|
||||
void classifiesSelectStarAndReturnsEmptyForNonSelectSql() {
|
||||
SpectrumQuery query = classifier.classify("SELECT * FROM events", 0).orElseThrow();
|
||||
assertTrue(query.selectStar());
|
||||
assertTrue(classifier.classify("SHOW TABLES", 0).isEmpty());
|
||||
assertTrue(classifier.classify("SELECT 1", 0).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsParametersAndUnsupportedExternalShapes() {
|
||||
assertTrue(classifier.classify("SELECT * FROM analytics.events", 1).isEmpty());
|
||||
assertTrue(classifier.classify(
|
||||
"SELECT * FROM analytics.events JOIN analytics.users ON events.id = users.id", 0).isEmpty());
|
||||
assertTrue(classifier.classify(
|
||||
"SELECT count(*) FROM analytics.events", 0).isEmpty());
|
||||
assertTrue(classifier.classify(
|
||||
"SELECT * FROM analytics.events; SELECT 1", 0).isEmpty());
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package io.github.hectorvent.floci.services.redshift.spectrum;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class SpectrumQueryRewriterTest {
|
||||
|
||||
@Test
|
||||
void rewritesOnlyTheSourceTableAndQuotesGeneratedIdentifier() {
|
||||
SpectrumQuery query = new SpectrumQuery("analytics", "events", "id, name", "id >= 2 AND name <> 'x'", false);
|
||||
|
||||
assertEquals("SELECT id, name FROM \"spectrum_tmp_abc\" WHERE id >= 2 AND name <> 'x'",
|
||||
SpectrumQueryRewriter.rewrite(query, "spectrum_tmp_abc"));
|
||||
assertEquals("SELECT * FROM \"tmp\"\"unsafe\"", SpectrumQueryRewriter.rewrite(
|
||||
new SpectrumQuery("analytics", "events", "*", null, true), "tmp\"unsafe"));
|
||||
}
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
package io.github.hectorvent.floci.services.redshift.spectrum;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class SpectrumS3ReaderTest {
|
||||
|
||||
@Test
|
||||
void readsCsvRowsWithHeadersNullsAndTypes() {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
S3Object data = object("events/data.csv", ""
|
||||
+ "id,name,active,amount,date\n"
|
||||
+ "1,alice,true,12.50,2026-01-02\n"
|
||||
+ "2,\\N,false,3.00,2026-01-03\n");
|
||||
when(s3.listObjectsWithPrefixes("warehouse", "events/", "", 1000, null, null))
|
||||
.thenReturn(new S3Service.ListObjectsResult(List.of(data), List.of(), false, null));
|
||||
when(s3.getObject("warehouse", "events/data.csv")).thenReturn(data);
|
||||
SpectrumExternalTable table = new SpectrumExternalTable("000000000000", "dev", "analytics", "events",
|
||||
List.of(
|
||||
new SpectrumColumn("id", SpectrumColumn.Type.INTEGER),
|
||||
new SpectrumColumn("name", SpectrumColumn.Type.VARCHAR),
|
||||
new SpectrumColumn("active", SpectrumColumn.Type.BOOLEAN),
|
||||
new SpectrumColumn("amount", SpectrumColumn.Type.DECIMAL),
|
||||
new SpectrumColumn("date", SpectrumColumn.Type.DATE)),
|
||||
"s3://warehouse/events/", ',', '"', '\\', "\\N", 1);
|
||||
|
||||
List<SpectrumRow> rows = new SpectrumS3Reader(s3, null).read(schema(), table).toList();
|
||||
|
||||
assertEquals(List.of(
|
||||
new SpectrumRow(List.of("1", "alice", "true", "12.50", "2026-01-02")),
|
||||
new SpectrumRow(Arrays.asList("2", null, "false", "3.00", "2026-01-03"))), rows);
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsPrefixObjectsInSortedKeyOrder() {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
S3Object z = object("events/z.csv", "z\n");
|
||||
S3Object a = object("events/a.csv", "a\n");
|
||||
when(s3.listObjectsWithPrefixes("warehouse", "events/", "", 1000, null, null))
|
||||
.thenReturn(new S3Service.ListObjectsResult(List.of(z, a), List.of(), false, null));
|
||||
when(s3.getObject("warehouse", "events/z.csv")).thenReturn(z);
|
||||
when(s3.getObject("warehouse", "events/a.csv")).thenReturn(a);
|
||||
SpectrumExternalTable table = table(SpectrumColumn.Type.VARCHAR);
|
||||
|
||||
List<SpectrumRow> rows = new SpectrumS3Reader(s3, null).read(schema(), table).toList();
|
||||
|
||||
assertEquals(List.of(new SpectrumRow(List.of("a")), new SpectrumRow(List.of("z"))), rows);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsRowWidthAndTypeConversionErrors() {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
S3Object data = object("events/data.csv", "bad,extra\n");
|
||||
when(s3.listObjectsWithPrefixes("warehouse", "events/", "", 1000, null, null))
|
||||
.thenReturn(new S3Service.ListObjectsResult(List.of(data), List.of(), false, null));
|
||||
when(s3.getObject("warehouse", "events/data.csv")).thenReturn(data);
|
||||
SpectrumExternalTable table = new SpectrumExternalTable("000000000000", "dev", "analytics", "events",
|
||||
List.of(new SpectrumColumn("id", SpectrumColumn.Type.INTEGER)),
|
||||
"s3://warehouse/events/", ',', '"', '\\', "\\N", 0);
|
||||
|
||||
assertThrows(SpectrumReadException.class, () -> new SpectrumS3Reader(s3, null).read(schema(), table).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pagesThroughMoreThanOneThousandObjects() {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
S3Object first = object("events/000.csv", "1\n");
|
||||
S3Object second = object("events/001.csv", "2\n");
|
||||
when(s3.listObjectsWithPrefixes("warehouse", "events/", "", 1000, null, null))
|
||||
.thenReturn(new S3Service.ListObjectsResult(List.of(first), List.of(), true, "page-2"));
|
||||
when(s3.listObjectsWithPrefixes("warehouse", "events/", "", 1000, "page-2", null))
|
||||
.thenReturn(new S3Service.ListObjectsResult(List.of(second), List.of(), false, null));
|
||||
when(s3.getObject("warehouse", "events/000.csv")).thenReturn(first);
|
||||
when(s3.getObject("warehouse", "events/001.csv")).thenReturn(second);
|
||||
SpectrumExternalTable table = table(SpectrumColumn.Type.VARCHAR);
|
||||
|
||||
List<SpectrumRow> rows = new SpectrumS3Reader(s3, null).read(schema(), table).toList();
|
||||
|
||||
assertEquals(List.of(new SpectrumRow(List.of("1")), new SpectrumRow(List.of("2"))), rows);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapsDeniedGetObjectToAuthorizationSqlState() {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
S3Object data = object("events/data.csv", "value\n");
|
||||
when(s3.listObjectsWithPrefixes("warehouse", "events/", "", 1000, null, null))
|
||||
.thenReturn(new S3Service.ListObjectsResult(List.of(data), List.of(), false, null));
|
||||
doThrow(new AwsException("AccessDenied", "Access Denied", 403))
|
||||
.when(s3).authorizeAnonymousGetObject("warehouse", "events/data.csv");
|
||||
SpectrumExternalTable table = table(SpectrumColumn.Type.VARCHAR);
|
||||
|
||||
SpectrumReadException exception = assertThrows(SpectrumReadException.class,
|
||||
() -> new SpectrumS3Reader(s3, null).read(schema(), table).toList());
|
||||
|
||||
assertEquals("42501", exception.sqlState());
|
||||
}
|
||||
|
||||
private static SpectrumExternalSchema schema() {
|
||||
return new SpectrumExternalSchema("000000000000", "dev", "analytics", "s3://warehouse/root/", null);
|
||||
}
|
||||
|
||||
private static SpectrumExternalTable table(SpectrumColumn.Type type) {
|
||||
return new SpectrumExternalTable("000000000000", "dev", "analytics", "events",
|
||||
List.of(new SpectrumColumn("value", type)), "s3://warehouse/events/", ',', '"', '\\', "\\N", 0);
|
||||
}
|
||||
|
||||
private static S3Object object(String key, String content) {
|
||||
return new S3Object("warehouse", key, content.getBytes(StandardCharsets.UTF_8), "text/csv");
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package io.github.hectorvent.floci.services.redshift.spectrum;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class SpectrumSqlParserTest {
|
||||
|
||||
private final SpectrumStatementParser parser = new SpectrumStatementParser();
|
||||
|
||||
@Test
|
||||
void parsesExternalSchemaAndNormalizesUnquotedIdentifiers() {
|
||||
SpectrumStatement statement = parser.parse(
|
||||
"CREATE EXTERNAL SCHEMA Analytics FROM DATA CATALOG DATABASE 'warehouse' IAM_ROLE 'arn:aws:iam::000000000000:role/Reader'")
|
||||
.orElseThrow();
|
||||
|
||||
SpectrumStatement.CreateSchema schema = assertInstanceOf(SpectrumStatement.CreateSchema.class, statement);
|
||||
assertEquals("analytics", schema.schemaName());
|
||||
assertEquals("warehouse", schema.databaseName());
|
||||
assertEquals("arn:aws:iam::000000000000:role/Reader", schema.iamRoleArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parsesQuotedIdentifiersEscapedLiteralsAndCsvProperties() {
|
||||
SpectrumStatement statement = parser.parse(""
|
||||
+ "-- define the table\n"
|
||||
+ "CREATE EXTERNAL TABLE \"Sales\".\"Order\"\"Items\" ("
|
||||
+ "order_id BIGINT, description VARCHAR, active BOOLEAN, created DATE) "
|
||||
+ "STORED AS TEXTFILE LOCATION 's3://bucket/a''b/' "
|
||||
+ "TBLPROPERTIES ("
|
||||
+ "'skip.header.line.count'='1', 'field.delim'='|', "
|
||||
+ "'serialization.format'='|', 'quoteChar'='\"', 'escapeChar'='\\', "
|
||||
+ "'serialization.null.format'='NULL')").orElseThrow();
|
||||
|
||||
SpectrumStatement.CreateTable table = assertInstanceOf(SpectrumStatement.CreateTable.class, statement);
|
||||
assertEquals("Sales", table.schemaName());
|
||||
assertEquals("Order\"Items", table.tableName());
|
||||
assertEquals(List.of(
|
||||
new SpectrumColumn("order_id", SpectrumColumn.Type.BIGINT),
|
||||
new SpectrumColumn("description", SpectrumColumn.Type.VARCHAR),
|
||||
new SpectrumColumn("active", SpectrumColumn.Type.BOOLEAN),
|
||||
new SpectrumColumn("created", SpectrumColumn.Type.DATE)), table.columns());
|
||||
assertEquals("s3://bucket/a'b/", table.location());
|
||||
assertEquals('|', table.delimiter());
|
||||
assertEquals('"', table.quote());
|
||||
assertEquals('\\', table.escape());
|
||||
assertEquals("NULL", table.nullValue());
|
||||
assertEquals(1, table.headerLines());
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptsOptionalExternalDatabaseClauseAndTrailingSemicolon() {
|
||||
SpectrumStatement statement = parser.parse(
|
||||
"CREATE EXTERNAL SCHEMA s FROM DATA CATALOG DATABASE 'db' IAM_ROLE 'role' "
|
||||
+ "CREATE EXTERNAL DATABASE IF NOT EXISTS;").orElseThrow();
|
||||
|
||||
SpectrumStatement.CreateSchema schema = assertInstanceOf(SpectrumStatement.CreateSchema.class, statement);
|
||||
assertEquals("s", schema.schemaName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsEmptyForNonSpectrumSql() {
|
||||
assertTrue(parser.parse("SELECT 1").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsTrailingStatementsDuplicatePropertiesAndUnsupportedFormat() {
|
||||
assertThrows(SpectrumSqlException.class, () -> parser.parse(
|
||||
"CREATE EXTERNAL SCHEMA s FROM DATA CATALOG DATABASE 'db' IAM_ROLE 'role'; SELECT 1"));
|
||||
assertThrows(SpectrumSqlException.class, () -> parser.parse(
|
||||
"CREATE EXTERNAL TABLE s.t (id INTEGER) STORED AS PARQUET LOCATION 's3://b/p'"));
|
||||
assertThrows(SpectrumSqlException.class, () -> parser.parse(
|
||||
"CREATE EXTERNAL TABLE s.t (id INTEGER) STORED AS TEXTFILE LOCATION 's3://b/p' "
|
||||
+ "TBLPROPERTIES ('field.delim'=',', 'field.delim'='|')"));
|
||||
assertThrows(SpectrumSqlException.class, () -> parser.parse("CREATE EXTERNAL VIEW v AS SELECT 1"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user