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:
Vũ Thế Huy authored and GitHub committed 2026-09-23 23:34:03 -04:00
1 parent 5f1f80b496
commit a450cdc9b0
30 files changed
+2955 -6

No files matched your search

@@ -0,0 +1,225 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumInterceptor;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumMaterializer;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumReadException;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumSqlException;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Map;
/**
* Runs a Spectrum {@code Plan} for one Extended Query Execute.
*
* <p>Results are sent to the client immediately and this method then returns without waiting for
* Flush or Sync: PostgreSQL lets a frontend pipeline any number of Parse/Bind/Execute steps before
* a single trailing Sync, and Execute itself never produces {@code ReadyForQuery}. The client's
* eventual Sync is handled generically by {@link RedshiftInterceptingBridge#run()}, which forwards
* it to the real backend; the backend's own {@code ReadyForQuery} for that Sync is then relayed to
* the client by the ordinary backend-to-client pump. Waiting here for Sync (or even just Flush)
* before producing output would deadlock a client that reads Execute's result before deciding
* whether to send more commands or Sync.
*
* <p>A Spectrum SELECT cannot be paused and resumed on the real backend (it runs as a single Simple
* Query against the materialized temp table), so {@code Execute}'s {@code maxRows} is honored by
* buffering the full row set once per portal in a {@link PortalCursor} and doling it out across
* however many Execute calls the client makes, exactly like a real suspended portal: once the
* buffer is empty this sends {@code CommandComplete}, otherwise {@code PortalSuspended}.
*/
final class ExtendedSpectrumExchange {
private static final Logger LOG = Logger.getLogger(ExtendedSpectrumExchange.class);
private ExtendedSpectrumExchange() {
}
static void execute(Socket client, Socket backend, SpectrumInterceptor.Plan plan,
SpectrumInterceptor interceptor, String accountId, String database,
BackendResponseCoordinator coordinator, BackendResponseCoordinator.Ticket ticket,
String portalName, int maxRows, Map<String, PortalCursor> cursors) throws IOException {
boolean failed = true;
try {
PortalCursor cursor = cursors.get(portalName);
if (cursor == null) {
SpectrumInterceptor.Decision decision = interceptor.execute(plan, accountId, database, backend);
if (decision instanceof SpectrumInterceptor.Decision.Handled) {
forward(client, commandComplete("CREATE EXTERNAL"));
failed = false;
return;
}
if (decision instanceof SpectrumInterceptor.Decision.Rewritten rewritten) {
cursor = new PortalCursor(rewritten.materialization(),
bufferRows(backend, rewritten.sql()));
cursors.put(portalName, cursor);
} else {
throw new SpectrumSqlException("0A000", "Spectrum plan did not produce an executable statement");
}
}
deliverRows(client, cursor, maxRows);
failed = false;
if (cursor.exhausted()) {
cursors.remove(portalName);
cleanup(interceptor, backend, cursor.materialization());
}
} catch (RuntimeException e) {
PortalCursor abandoned = cursors.remove(portalName);
if (abandoned != null) {
cleanup(interceptor, backend, abandoned.materialization());
}
forward(client, error(e));
} finally {
coordinator.completeOwnedExecute(ticket, failed);
}
}
/** Drops a cursor's temp table, e.g. when its portal is closed before the client exhausts it. */
static void abandon(SpectrumInterceptor interceptor, Socket backend, PortalCursor cursor) {
cleanup(interceptor, backend, cursor.materialization());
}
private static void cleanup(SpectrumInterceptor interceptor, Socket backend,
SpectrumMaterializer.Materialization materialization) {
try {
interceptor.cleanup(backend, materialization);
} catch (RuntimeException cleanupFailure) {
LOG.warnv(cleanupFailure, "Unable to clean up Spectrum materialization {0}",
materialization.identifier());
}
}
private static Deque<PostgresWireDecoder.FrontendMessage> bufferRows(Socket backend, String sql)
throws IOException {
OutputStream backendOut = backend.getOutputStream();
backendOut.write(PostgresWireDecoder.encodeQuery(sql));
backendOut.flush();
PostgresWireDecoder decoder = new PostgresWireDecoder(backend.getInputStream());
Deque<PostgresWireDecoder.FrontendMessage> rows = new ArrayDeque<>();
while (true) {
PostgresWireDecoder.FrontendMessage message = decoder.nextMessage();
if (message == null) {
throw new IOException("Backend closed during Spectrum Execute");
}
switch (message.type()) {
case 'Z' -> {
return rows;
}
case 'T', 'C' -> {
// RowDescription was already sent from catalog metadata at Describe time; the
// backend's own CommandComplete tag is discarded in favor of one reflecting the
// buffered row count, since rows are delivered across possibly several Executes.
}
case 'E' -> throw new SpectrumSqlException("22000",
"PostgreSQL rejected the rewritten Spectrum query: " + describeError(message));
default -> rows.add(message);
}
}
}
private static String describeError(PostgresWireDecoder.FrontendMessage errorResponse) {
byte[] body = errorResponse.body();
if (body == null) {
return "unknown error";
}
int offset = 0;
while (offset < body.length && body[offset] != 0) {
if (body[offset] == 'M') {
int start = offset + 1;
int end = start;
while (end < body.length && body[end] != 0) {
end++;
}
return new String(body, start, end - start, StandardCharsets.UTF_8);
}
while (offset < body.length && body[offset] != 0) {
offset++;
}
offset++;
}
return "unknown error";
}
private static void deliverRows(Socket client, PortalCursor cursor, int maxRows) throws IOException {
int delivered = 0;
while ((maxRows <= 0 || delivered < maxRows) && !cursor.rows().isEmpty()) {
forward(client, cursor.rows().pollFirst());
delivered++;
}
cursor.delivered(delivered);
if (cursor.rows().isEmpty()) {
forward(client, commandComplete("SELECT " + cursor.totalDelivered()));
} else {
forward(client, portalSuspended());
}
}
private static PostgresWireDecoder.FrontendMessage commandComplete(String tag) {
return new PostgresWireDecoder.FrontendMessage('C', (tag + '\0').getBytes(StandardCharsets.UTF_8));
}
private static PostgresWireDecoder.FrontendMessage portalSuspended() {
return new PostgresWireDecoder.FrontendMessage('s', new byte[0]);
}
private static PostgresWireDecoder.FrontendMessage error(RuntimeException exception) {
return new PostgresWireDecoder.FrontendMessage('E',
S3CopySimulator.errorBody(sqlState(exception), exception.getMessage()));
}
private static String sqlState(RuntimeException exception) {
if (exception instanceof SpectrumSqlException spectrumSqlException) {
return spectrumSqlException.sqlState();
}
if (exception instanceof SpectrumReadException spectrumReadException) {
return spectrumReadException.sqlState();
}
return "22023";
}
private static void forward(Socket client, PostgresWireDecoder.FrontendMessage message) throws IOException {
OutputStream output = client.getOutputStream();
output.write(message.toPacketBytes());
output.flush();
}
/** The buffered, not-yet-delivered rows of one Spectrum SELECT bound to a portal, and the temp
* table they came from. Rows are removed as they are delivered; {@link #exhausted()} is true
* once every row has been sent to the client across one or more {@code Execute} calls. */
static final class PortalCursor {
private final SpectrumMaterializer.Materialization materialization;
private final Deque<PostgresWireDecoder.FrontendMessage> rows;
private long totalDelivered;
PortalCursor(SpectrumMaterializer.Materialization materialization,
Deque<PostgresWireDecoder.FrontendMessage> rows) {
this.materialization = materialization;
this.rows = rows;
}
SpectrumMaterializer.Materialization materialization() {
return materialization;
}
Deque<PostgresWireDecoder.FrontendMessage> rows() {
return rows;
}
void delivered(int count) {
totalDelivered += count;
}
long totalDelivered() {
return totalDelivered;
}
boolean exhausted() {
return rows.isEmpty();
}
}
}
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.services.rds.proxy.PostgresProtocolHandler;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyTlsCertificates;
import io.github.hectorvent.floci.services.rds.proxy.RdsSigV4Validator;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumInterceptor;
import org.jboss.logging.Logger;
import java.io.IOException;
@@ -38,6 +39,7 @@ public class RedshiftAuthProxy {
private final PasswordValidator passwordValidator;
private final S3Service s3Service;
private final IamService iamService;
private final SpectrumInterceptor spectrumInterceptor;
private final String clusterAccountId;
private volatile List<String> iamRoleArns;
private final int handshakeTimeoutMillis;
@@ -57,7 +59,7 @@ public class RedshiftAuthProxy {
this(clusterKey, backendHost, backendPort, masterUsername, masterPassword, dbName, sigV4,
tlsCertificates, passwordValidator, s3Service, iamService, null,
List.of(),
handshakeTimeoutMillis, backendConnectTimeoutMillis, maxConnections);
handshakeTimeoutMillis, backendConnectTimeoutMillis, maxConnections, null);
}
public RedshiftAuthProxy(String clusterKey, String backendHost, int backendPort,
@@ -69,6 +71,20 @@ public class RedshiftAuthProxy {
List<String> iamRoleArns,
int handshakeTimeoutMillis, int backendConnectTimeoutMillis,
int maxConnections) {
this(clusterKey, backendHost, backendPort, masterUsername, masterPassword, dbName, sigV4,
tlsCertificates, passwordValidator, s3Service, iamService, clusterAccountId, iamRoleArns,
handshakeTimeoutMillis, backendConnectTimeoutMillis, maxConnections, null);
}
public RedshiftAuthProxy(String clusterKey, String backendHost, int backendPort,
String masterUsername, String masterPassword, String dbName,
RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates,
PasswordValidator passwordValidator,
S3Service s3Service, IamService iamService,
String clusterAccountId,
List<String> iamRoleArns,
int handshakeTimeoutMillis, int backendConnectTimeoutMillis,
int maxConnections, SpectrumInterceptor spectrumInterceptor) {
this.clusterKey = clusterKey;
this.backendHost = backendHost;
this.backendPort = backendPort;
@@ -80,6 +96,7 @@ public class RedshiftAuthProxy {
this.passwordValidator = passwordValidator;
this.s3Service = s3Service;
this.iamService = iamService;
this.spectrumInterceptor = spectrumInterceptor;
this.clusterAccountId = clusterAccountId;
this.iamRoleArns = iamRoleArns == null ? List.of() : List.copyOf(iamRoleArns);
this.handshakeTimeoutMillis = handshakeTimeoutMillis;
@@ -205,7 +222,7 @@ public class RedshiftAuthProxy {
// Redshift-only DDL (DISTKEY/SORTKEY/ENCODE/...) is rewritten for the plain
// PostgreSQL backend on the way through; every other message is relayed verbatim.
new RedshiftInterceptingBridge(session.client(), session.backend(), s3Service, iamService,
clusterAccountId, iamRoleArns).run();
clusterAccountId, iamRoleArns, spectrumInterceptor).run();
}
} catch (Exception e) {
LOG.debugv("Redshift connection error for cluster {0}: {1}", clusterKey, e.getMessage());
@@ -1,15 +1,26 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumColumn;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumInterceptor;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumQueryRewriter;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumReadException;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumSqlException;
import io.github.hectorvent.floci.services.s3.S3Service;
import org.jboss.logging.Logger;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;
@@ -33,6 +44,8 @@ public class RedshiftInterceptingBridge {
private static final Logger LOG = Logger.getLogger(RedshiftInterceptingBridge.class);
private static final byte[] EMPTY_BODY = new byte[0];
private static final int PUMP_READ_TIMEOUT_MS = 200;
private static final int CLIENT_READ_TIMEOUT_MS = 10_000;
private static final long PUMP_PARK_WAIT_MS = 2_000L;
@@ -46,12 +59,17 @@ public class RedshiftInterceptingBridge {
private final IamService iamService;
private final String clusterAccountId;
private final List<String> iamRoleArns;
private final SpectrumInterceptor spectrumInterceptor;
private final ExtendedQuerySession session = new ExtendedQuerySession();
private final Map<String, SpectrumInterceptor.Plan> spectrumStatements = new HashMap<>();
private final Map<String, SpectrumInterceptor.Plan> spectrumPortals = new HashMap<>();
private final Map<String, ExtendedSpectrumExchange.PortalCursor> spectrumCursors = new HashMap<>();
private final BackendResponseCoordinator coordinator = new BackendResponseCoordinator(session);
private final ReentrantLock backendLock = new ReentrantLock(true);
private volatile boolean pumpBetweenMessages = true;
private volatile boolean pumpFinished = false;
private boolean extendedSpectrumError;
public RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService) {
this(client, backend, s3Service, iamService, null);
@@ -63,13 +81,20 @@ public class RedshiftInterceptingBridge {
}
public RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService,
String clusterAccountId, List<String> iamRoleArns) {
String clusterAccountId, List<String> iamRoleArns) {
this(client, backend, s3Service, iamService, clusterAccountId, iamRoleArns, null);
}
public RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService,
String clusterAccountId, List<String> iamRoleArns,
SpectrumInterceptor spectrumInterceptor) {
this.client = client;
this.backend = backend;
this.s3Service = s3Service;
this.iamService = iamService;
this.clusterAccountId = clusterAccountId;
this.iamRoleArns = iamRoleArns == null ? List.of() : List.copyOf(iamRoleArns);
this.spectrumInterceptor = spectrumInterceptor;
}
@FunctionalInterface
@@ -123,6 +148,9 @@ public class RedshiftInterceptingBridge {
}
continue;
}
if (extendedSpectrumError && msg.type() != 'S' && msg.type() != 'X') {
continue;
}
switch (msg.type()) {
case 'Q' -> handleSimpleQuery(msg, backendOut);
case 'P' -> handleParse(decoder, msg, backendOut);
@@ -131,6 +159,7 @@ public class RedshiftInterceptingBridge {
case 'E' -> handleExecute(decoder, msg, backendOut);
case 'C' -> handleClose(decoder, msg, backendOut);
case 'S' -> {
extendedSpectrumError = false;
coordinator.register(BackendResponseCoordinator.Operation.SYNC, null);
write(backendOut, msg.toPacketBytes());
}
@@ -151,6 +180,36 @@ public class RedshiftInterceptingBridge {
private void handleSimpleQuery(PostgresWireDecoder.FrontendMessage message, OutputStream backendOut)
throws IOException {
String sql = message.getSql();
if (spectrumInterceptor != null) {
SpectrumInterceptor.Decision[] decision = new SpectrumInterceptor.Decision[1];
boolean intercepted;
try {
intercepted = runWithBackendOwned(() -> {
decision[0] = spectrumInterceptor.intercept(sql, clusterAccountId, "dev", backend);
return true;
});
} catch (SpectrumSqlException | SpectrumReadException | IllegalArgumentException exception) {
writeSimpleSpectrumError(exception);
return;
}
if (intercepted && decision[0] instanceof SpectrumInterceptor.Decision.Handled) {
coordinator.register(BackendResponseCoordinator.Operation.SIMPLE_QUERY, null);
write(client.getOutputStream(), commandComplete("CREATE EXTERNAL\0"));
write(client.getOutputStream(), readyForQuery('I'));
coordinator.onBackendFrame('Z', new byte[]{'I'});
return;
}
if (intercepted && decision[0] instanceof SpectrumInterceptor.Decision.Rewritten rewritten) {
// The response streams back to the client through the async backend->client pump
// (see class docs), so the materialized temp table cannot be dropped synchronously
// here without racing that pump; it is cleaned up implicitly when the underlying
// PostgreSQL session ends (CREATE TEMP TABLE is session-scoped). The Extended Query
// path (ExtendedSpectrumExchange) owns the whole round trip and can clean up eagerly.
coordinator.register(BackendResponseCoordinator.Operation.SIMPLE_QUERY, null);
write(backendOut, PostgresWireDecoder.encodeQuery(rewritten.sql()));
return;
}
}
CopyStatementParser.S3Statement parsed = parseS3Statement(sql);
if (parsed != null) {
CopyStatementParser.S3Statement statement = parsed;
@@ -183,6 +242,24 @@ public class RedshiftInterceptingBridge {
private void handleParse(PostgresWireDecoder decoder, PostgresWireDecoder.FrontendMessage message,
OutputStream backendOut) throws IOException {
PostgresWireDecoder.ParseMessage parse = decoder.decodeParse(message);
// A Parse with an already-used statement name (the unnamed statement, "", above all) redefines
// it, per protocol; without this, a later non-Spectrum statement reusing that name would still
// resolve to the stale Spectrum plan in handleBind/handleDescribe/handleExecute.
spectrumStatements.remove(parse.statementName());
if (spectrumInterceptor != null && parse.parameterTypeOids().isEmpty()) {
try {
SpectrumInterceptor.Plan plan = spectrumInterceptor.plan(parse.sql(), clusterAccountId, "dev");
if (plan instanceof SpectrumInterceptor.Plan.Ddl || plan instanceof SpectrumInterceptor.Plan.Query) {
awaitPriorBackendResponses();
spectrumStatements.put(parse.statementName(), plan);
write(client.getOutputStream(), backendFrame('1', EMPTY_BODY));
return;
}
} catch (SpectrumSqlException | SpectrumReadException | IllegalArgumentException exception) {
writeParseSpectrumError(exception);
return;
}
}
CopyStatementParser.S3Statement statement = parse.parameterTypeOids().isEmpty()
? parseS3Statement(parse.sql()) : null;
ExtendedQuerySession.Mutation mutation = session.stageParse(parse.statementName(), statement);
@@ -208,6 +285,14 @@ public class RedshiftInterceptingBridge {
private void handleBind(PostgresWireDecoder decoder, PostgresWireDecoder.FrontendMessage message,
OutputStream backendOut) throws IOException {
PostgresWireDecoder.BindMessage bind = decoder.decodeBind(message);
SpectrumInterceptor.Plan spectrumPlan = spectrumStatements.get(bind.statementName());
if (spectrumPlan != null) {
awaitPriorBackendResponses();
spectrumPortals.put(bind.portalName(), spectrumPlan);
write(client.getOutputStream(), backendFrame('2', EMPTY_BODY));
return;
}
spectrumPortals.remove(bind.portalName());
ExtendedQuerySession.Mutation mutation = session.stageBind(bind.portalName(), bind.statementName());
coordinator.register(BackendResponseCoordinator.Operation.BIND, mutation);
write(backendOut, message.toPacketBytes());
@@ -216,6 +301,25 @@ public class RedshiftInterceptingBridge {
private void handleDescribe(PostgresWireDecoder decoder, PostgresWireDecoder.FrontendMessage message,
OutputStream backendOut) throws IOException {
PostgresWireDecoder.TargetMessage describe = decoder.decodeDescribe(message);
SpectrumInterceptor.Plan spectrumPlan = describe.targetType() == 'S'
? spectrumStatements.get(describe.name())
: spectrumPortals.get(describe.name());
if (spectrumPlan != null) {
try {
awaitPriorBackendResponses();
if (describe.targetType() == 'S') {
// Describe(Statement) must answer with ParameterDescription before RowDescription
// or NoData; every Spectrum-owned Parse has zero parameters (handleParse only
// takes this path when parse.parameterTypeOids() is empty), so this is always 0.
write(client.getOutputStream(), backendFrame('t', new byte[]{0, 0}));
}
byte[] response = spectrumDescribeResponse(spectrumPlan);
write(client.getOutputStream(), response);
} catch (SpectrumSqlException | SpectrumReadException | IllegalArgumentException exception) {
writeParseSpectrumError(exception);
}
return;
}
BackendResponseCoordinator.Operation operation = describe.targetType() == 'S'
? BackendResponseCoordinator.Operation.DESCRIBE_STATEMENT
: BackendResponseCoordinator.Operation.DESCRIBE_PORTAL;
@@ -223,9 +327,53 @@ public class RedshiftInterceptingBridge {
write(backendOut, message.toPacketBytes());
}
/** {@code RowDescription} for a Spectrum SELECT, or {@code NoData} for a DDL statement, computed
* entirely from catalog metadata so Describe never has to round-trip the real backend. */
private static byte[] spectrumDescribeResponse(SpectrumInterceptor.Plan plan) {
if (plan instanceof SpectrumInterceptor.Plan.Query query) {
return rowDescription(SpectrumQueryRewriter.outputColumns(query.query(), query.table()));
}
return backendFrame('n', EMPTY_BODY);
}
private static byte[] rowDescription(List<SpectrumColumn> columns) {
ByteArrayOutputStream body = new ByteArrayOutputStream();
body.write((columns.size() >>> 8) & 0xFF);
body.write(columns.size() & 0xFF);
for (SpectrumColumn column : columns) {
writeCString(body, column.name());
writeInt32(body, 0);
writeInt16(body, 0);
writeInt32(body, column.type().postgresTypeOid());
writeInt16(body, column.type().postgresTypeLength());
writeInt32(body, -1);
writeInt16(body, 0);
}
return backendFrame('T', body.toByteArray());
}
private static void writeInt32(ByteArrayOutputStream out, int value) {
out.write((value >>> 24) & 0xFF);
out.write((value >>> 16) & 0xFF);
out.write((value >>> 8) & 0xFF);
out.write(value & 0xFF);
}
private static void writeInt16(ByteArrayOutputStream out, int value) {
out.write((value >>> 8) & 0xFF);
out.write(value & 0xFF);
}
private void handleExecute(PostgresWireDecoder decoder, PostgresWireDecoder.FrontendMessage message,
OutputStream backendOut) throws IOException {
PostgresWireDecoder.ExecuteMessage execute = decoder.decodeExecute(message);
SpectrumInterceptor.Plan spectrumPlan = spectrumPortals.get(execute.portalName());
if (spectrumPlan != null) {
BackendResponseCoordinator.Ticket ticket = coordinator.register(
BackendResponseCoordinator.Operation.EXECUTE, null);
runExtendedSpectrumWithBackendOwned(spectrumPlan, execute.portalName(), execute.maxRows(), ticket);
return;
}
BackendResponseCoordinator.Ticket ticket = coordinator.register(
BackendResponseCoordinator.Operation.EXECUTE, null);
CopyStatementParser.S3Statement statement = session.portal(execute.portalName()).orElse(null);
@@ -236,14 +384,117 @@ public class RedshiftInterceptingBridge {
runExtendedWithBackendOwned(message, statement, ticket);
}
private void runExtendedSpectrumWithBackendOwned(SpectrumInterceptor.Plan plan, String portalName, int maxRows,
BackendResponseCoordinator.Ticket ticket) throws IOException {
BackendResponseCoordinator.GateResult gate;
try {
gate = coordinator.awaitExtendedExecuteTurn(ticket);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Interrupted while awaiting Spectrum Execute turn", e);
}
if (gate != BackendResponseCoordinator.GateResult.READY) {
return;
}
long deadlineNanos = System.nanoTime() + PUMP_PARK_WAIT_MS * 1_000_000L;
boolean locked = false;
while (!pumpFinished && System.nanoTime() < deadlineNanos) {
try {
long remainingMillis = Math.max(1L,
TimeUnit.NANOSECONDS.toMillis(deadlineNanos - System.nanoTime()));
locked = backendLock.tryLock(Math.min(PUMP_PARK_WAIT_MS, remainingMillis), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Interrupted while acquiring Spectrum Execute ownership", e);
}
if (!locked) {
continue;
}
if (pumpBetweenMessages) {
break;
}
backendLock.unlock();
locked = false;
}
if (!locked || !pumpBetweenMessages || pumpFinished) {
if (locked) {
backendLock.unlock();
}
throw new IOException("Could not take backend ownership for Spectrum Execute");
}
try {
backend.setSoTimeout(EXCHANGE_READ_TIMEOUT_MS);
ExtendedSpectrumExchange.execute(client, backend, plan, spectrumInterceptor, clusterAccountId, "dev",
coordinator, ticket, portalName, maxRows, spectrumCursors);
} finally {
try {
backend.setSoTimeout(PUMP_READ_TIMEOUT_MS);
} catch (IOException e) {
LOG.debugv(e, "could not restore backend read timeout (socket closing)");
}
backendLock.unlock();
}
}
private void handleClose(PostgresWireDecoder decoder, PostgresWireDecoder.FrontendMessage message,
OutputStream backendOut) throws IOException {
PostgresWireDecoder.TargetMessage close = decoder.decodeClose(message);
boolean spectrumOwned;
if (close.targetType() == 'S') {
SpectrumInterceptor.Plan closedPlan = spectrumStatements.remove(close.name());
spectrumOwned = closedPlan != null;
if (closedPlan != null) {
abandonStatementPortals(closedPlan);
}
} else {
spectrumOwned = spectrumPortals.remove(close.name()) != null;
ExtendedSpectrumExchange.PortalCursor cursor = spectrumCursors.remove(close.name());
if (cursor != null) {
// The portal is closed before the client exhausted it (fetch-size cursor abandoned
// mid-stream): the temp table has no other owner and would otherwise leak until the
// backend session ends, so drop it now.
runWithBackendOwned(() -> {
ExtendedSpectrumExchange.abandon(spectrumInterceptor, backend, cursor);
return true;
});
}
}
if (spectrumOwned) {
// Parse/Bind for a spectrum-owned statement or portal never reached the real backend
// (they are synthesized locally, see handleParse/handleBind), so the backend has never
// heard of this name either: forwarding Close would draw a spurious "does not exist" error.
awaitPriorBackendResponses();
write(client.getOutputStream(), backendFrame('3', EMPTY_BODY));
return;
}
ExtendedQuerySession.Mutation mutation = session.stageClose(close.targetType(), close.name());
coordinator.register(BackendResponseCoordinator.Operation.CLOSE, mutation);
write(backendOut, message.toPacketBytes());
}
/** Closing a prepared statement also closes every portal created from it. */
private void abandonStatementPortals(SpectrumInterceptor.Plan closedPlan) throws IOException {
List<ExtendedSpectrumExchange.PortalCursor> abandoned = new ArrayList<>();
Iterator<Map.Entry<String, SpectrumInterceptor.Plan>> portals = spectrumPortals.entrySet().iterator();
while (portals.hasNext()) {
Map.Entry<String, SpectrumInterceptor.Plan> portal = portals.next();
if (portal.getValue() == closedPlan) {
portals.remove();
ExtendedSpectrumExchange.PortalCursor cursor = spectrumCursors.remove(portal.getKey());
if (cursor != null) {
abandoned.add(cursor);
}
}
}
for (ExtendedSpectrumExchange.PortalCursor cursor : abandoned) {
runWithBackendOwned(() -> {
ExtendedSpectrumExchange.abandon(spectrumInterceptor, backend, cursor);
return true;
});
}
}
private CopyStatementParser.S3Statement parseS3Statement(String sql) {
try {
return CopyStatementParser.parse(sql);
@@ -311,6 +562,90 @@ public class RedshiftInterceptingBridge {
out.flush();
}
private static byte[] commandComplete(String tag) {
return backendFrame('C', tag.getBytes(StandardCharsets.UTF_8));
}
private static byte[] readyForQuery(char status) {
return backendFrame('Z', new byte[]{(byte) status});
}
private static byte[] errorResponse(String sqlState, String message) {
ByteArrayOutputStream body = new ByteArrayOutputStream();
body.write('S');
writeCString(body, "ERROR");
body.write('C');
writeCString(body, sqlState);
body.write('M');
writeCString(body, message == null ? "Spectrum statement failed" : message);
body.write(0);
return backendFrame('E', body.toByteArray());
}
private static byte[] backendFrame(char type, byte[] body) {
int length = body.length + 4;
byte[] frame = new byte[body.length + 5];
frame[0] = (byte) type;
frame[1] = (byte) (length >>> 24);
frame[2] = (byte) (length >>> 16);
frame[3] = (byte) (length >>> 8);
frame[4] = (byte) length;
System.arraycopy(body, 0, frame, 5, body.length);
return frame;
}
private static void writeCString(ByteArrayOutputStream out, String value) {
out.writeBytes(value.getBytes(StandardCharsets.UTF_8));
out.write(0);
}
private void writeSimpleSpectrumError(RuntimeException exception) throws IOException {
coordinator.register(BackendResponseCoordinator.Operation.SIMPLE_QUERY, null);
write(client.getOutputStream(), errorResponse(spectrumSqlState(exception), exception.getMessage()));
write(client.getOutputStream(), readyForQuery('I'));
coordinator.onBackendFrame('Z', new byte[]{'I'});
}
private void writeParseSpectrumError(RuntimeException exception) throws IOException {
session.clear();
extendedSpectrumError = true;
awaitPriorBackendResponses();
write(client.getOutputStream(), errorResponse(spectrumSqlState(exception), exception.getMessage()));
}
/**
* Waits until any earlier pipelined backend query (such as a {@code BEGIN} dispatched by
* {@code setAutoCommit(false)}) has finished streaming its response to the client. This
* prevents synthesized Spectrum responses (e.g. {@code ParseComplete}, {@code BindComplete},
* {@code RowDescription}) from racing and overtaking earlier backend responses on the wire.
*/
private void awaitPriorBackendResponses() throws IOException {
long deadlineNanos = System.nanoTime() + PUMP_PARK_WAIT_MS * 1_000_000L;
while (!pumpFinished) {
try {
if (coordinator.awaitIdle(PUMP_READ_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
return;
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Interrupted while waiting for prior backend responses", e);
}
if (System.nanoTime() >= deadlineNanos) {
throw new IOException("Backend did not go idle in time before local Spectrum response");
}
}
}
private static String spectrumSqlState(RuntimeException exception) {
if (exception instanceof SpectrumSqlException spectrumSqlException) {
return spectrumSqlException.sqlState();
}
if (exception instanceof SpectrumReadException spectrumReadException) {
return spectrumReadException.sqlState();
}
return "22023";
}
/**
* Take exclusive ownership of an idle backend at a wire-message boundary, run {@code exchange},
* then release it. Returns {@code false} if the backend could not be caught idle within
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyTlsCertificates;
import io.github.hectorvent.floci.services.rds.proxy.RdsSigV4Validator;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumInterceptor;
import io.quarkus.runtime.ShutdownEvent;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
@@ -30,6 +31,7 @@ public class RedshiftProxyManager {
private final RdsProxyTlsCertificates tlsCertificates;
private final S3Service s3Service;
private final IamService iamService;
private final SpectrumInterceptor spectrumInterceptor;
private final EmulatorConfig config;
private final ConcurrentHashMap<String, RedshiftAuthProxy> proxies = new ConcurrentHashMap<>();
/**
@@ -40,13 +42,20 @@ public class RedshiftProxyManager {
*/
private final ConcurrentHashMap<String, RedshiftAuthProxy> unclosableProxies = new ConcurrentHashMap<>();
@Inject
public RedshiftProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates,
S3Service s3Service, IamService iamService, EmulatorConfig config) {
this(sigV4Validator, tlsCertificates, s3Service, iamService, config, null);
}
@Inject
public RedshiftProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates,
S3Service s3Service, IamService iamService, EmulatorConfig config,
SpectrumInterceptor spectrumInterceptor) {
this.sigV4Validator = sigV4Validator;
this.tlsCertificates = tlsCertificates;
this.s3Service = s3Service;
this.iamService = iamService;
this.spectrumInterceptor = spectrumInterceptor;
this.config = config;
}
@@ -75,7 +84,7 @@ public class RedshiftProxyManager {
clusterAccountId,
iamRoleArns,
redshiftConfig.proxyHandshakeTimeoutMillis(), redshiftConfig.proxyBackendConnectTimeoutMillis(),
redshiftConfig.proxyMaxConnections());
redshiftConfig.proxyMaxConnections(), spectrumInterceptor);
try {
proxy.start(proxyPort);
} catch (IOException | RuntimeException e) {
@@ -0,0 +1,76 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
@ApplicationScoped
public class SpectrumCatalog implements Resettable {
private final AccountAwareStorageBackend<SpectrumExternalSchema> schemas;
private final AccountAwareStorageBackend<SpectrumExternalTable> tables;
public SpectrumCatalog(StorageFactory storageFactory) {
schemas = storageFactory.create("redshift", "redshift-spectrum-schemas.json",
new TypeReference<>() {});
tables = storageFactory.create("redshift", "redshift-spectrum-tables.json",
new TypeReference<>() {});
}
public synchronized void createSchema(SpectrumExternalSchema schema) {
String key = schemaKey(schema.accountId(), schema.databaseName(), schema.schemaName());
if (schemas.getForAccount(schema.accountId(), key).isPresent()) {
throw new SpectrumSqlException("42P06", "Spectrum external schema already exists: " + schema.schemaName());
}
schemas.putForAccount(schema.accountId(), key, schema);
schemas.flush();
}
public synchronized void createTable(SpectrumExternalTable table) {
String key = tableKey(table.accountId(), table.databaseName(), table.schemaName(), table.tableName());
if (tables.getForAccount(table.accountId(), key).isPresent()) {
throw new SpectrumSqlException("42P07", "Spectrum external table already exists: " + table.tableName());
}
tables.putForAccount(table.accountId(), key, table);
tables.flush();
}
public Optional<SpectrumExternalSchema> schema(String accountId, String databaseName, String schemaName) {
return schemas.getForAccount(accountId, schemaKey(accountId, databaseName, schemaName));
}
public Optional<SpectrumExternalTable> table(String accountId, String databaseName,
String schemaName, String tableName) {
return tables.getForAccount(accountId, tableKey(accountId, databaseName, schemaName, tableName));
}
public List<SpectrumExternalTable> tablesForSchema(String accountId, String databaseName, String schemaName) {
String prefix = accountId + ":" + databaseName + ":" + schemaName + ":";
return tables.scanForAccount(accountId, key -> key.startsWith(prefix))
.stream()
.sorted(Comparator.comparing(SpectrumExternalTable::tableName))
.toList();
}
@Override
public synchronized void clear() {
schemas.clear();
tables.clear();
schemas.flush();
tables.flush();
}
private static String schemaKey(String accountId, String databaseName, String schemaName) {
return accountId + ":" + databaseName + ":" + schemaName;
}
private static String tableKey(String accountId, String databaseName, String schemaName, String tableName) {
return accountId + ":" + databaseName + ":" + schemaName + ":" + tableName;
}
}
@@ -0,0 +1,92 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.Locale;
@RegisterForReflection(targets = SpectrumColumn.Type.class)
public record SpectrumColumn(String name, Type type) {
public SpectrumColumn {
if (name == null || name.isBlank()) {
throw new IllegalArgumentException("Spectrum column name is required");
}
if (type == null) {
throw new IllegalArgumentException("Spectrum column type is required");
}
if (!name.equals(name.trim())) {
throw new IllegalArgumentException("Spectrum column name must not contain surrounding whitespace");
}
}
@RegisterForReflection
public enum Type {
VARCHAR,
CHAR,
INTEGER,
BIGINT,
DECIMAL,
BOOLEAN,
DATE,
TIMESTAMP;
public static Type fromSql(String value) {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException("Spectrum column type is required");
}
String normalized = value.trim().toUpperCase(Locale.ROOT);
return switch (normalized) {
case "VARCHAR" -> VARCHAR;
case "CHAR" -> CHAR;
case "INTEGER", "INT" -> INTEGER;
case "BIGINT" -> BIGINT;
case "DECIMAL", "NUMERIC" -> DECIMAL;
case "BOOLEAN", "BOOL" -> BOOLEAN;
case "DATE" -> DATE;
case "TIMESTAMP" -> TIMESTAMP;
default -> throw new IllegalArgumentException("Unsupported Spectrum column type: " + value);
};
}
public String postgresType() {
return switch (this) {
case VARCHAR -> "VARCHAR";
case CHAR -> "CHAR";
case INTEGER -> "INTEGER";
case BIGINT -> "BIGINT";
case DECIMAL -> "DECIMAL";
case BOOLEAN -> "BOOLEAN";
case DATE -> "DATE";
case TIMESTAMP -> "TIMESTAMP";
};
}
/**
* The well-known PostgreSQL {@code pg_type} OID for this column's Postgres type, needed to
* synthesize a wire-accurate {@code RowDescription} for an Extended Query Describe response
* without a backend round trip.
*/
public int postgresTypeOid() {
return switch (this) {
case VARCHAR -> 1043;
case CHAR -> 1042;
case INTEGER -> 23;
case BIGINT -> 20;
case DECIMAL -> 1700;
case BOOLEAN -> 16;
case DATE -> 1082;
case TIMESTAMP -> 1114;
};
}
/** The fixed on-wire type length for this Postgres type, or {@code -1} for a variable-length type. */
public short postgresTypeLength() {
return switch (this) {
case VARCHAR, CHAR, DECIMAL -> -1;
case INTEGER, DATE -> 4;
case BIGINT, TIMESTAMP -> 8;
case BOOLEAN -> 1;
};
}
}
}
@@ -0,0 +1,39 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public record SpectrumExternalSchema(
String accountId,
String databaseName,
String schemaName,
String location,
String iamRoleArn) {
public SpectrumExternalSchema {
requireText(accountId, "accountId");
requireText(databaseName, "databaseName");
requireText(schemaName, "schemaName");
validateS3Location(location);
if (iamRoleArn != null && iamRoleArn.isBlank()) {
throw new IllegalArgumentException("iamRoleArn must not be blank");
}
}
private static void requireText(String value, String field) {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException(field + " is required");
}
}
static void validateS3Location(String value) {
if (value == null || !value.startsWith("s3://") || value.length() <= "s3://".length()) {
throw new IllegalArgumentException("Spectrum location must be an s3:// URI");
}
String path = value.substring("s3://".length());
int slash = path.indexOf('/');
if (slash <= 0 || slash == path.length() - 1) {
throw new IllegalArgumentException("Spectrum location must include a bucket and key or prefix");
}
}
}
@@ -0,0 +1,55 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
@RegisterForReflection
public record SpectrumExternalTable(
String accountId,
String databaseName,
String schemaName,
String tableName,
List<SpectrumColumn> columns,
String location,
char delimiter,
char quote,
char escape,
String nullValue,
int headerLines) {
public SpectrumExternalTable {
requireText(accountId, "accountId");
requireText(databaseName, "databaseName");
requireText(schemaName, "schemaName");
requireText(tableName, "tableName");
SpectrumExternalSchema.validateS3Location(location);
if (columns == null || columns.isEmpty()) {
throw new IllegalArgumentException("Spectrum external table requires columns");
}
columns = List.copyOf(columns);
if (delimiter == '\0' || quote == '\0' || escape == '\0') {
throw new IllegalArgumentException("Spectrum CSV delimiters must be valid characters");
}
if (nullValue == null) {
throw new IllegalArgumentException("Spectrum nullValue is required");
}
if (headerLines < 0) {
throw new IllegalArgumentException("Spectrum headerLines must not be negative");
}
for (int i = 0; i < columns.size(); i++) {
String left = columns.get(i).name();
for (int j = i + 1; j < columns.size(); j++) {
if (left.equalsIgnoreCase(columns.get(j).name())) {
throw new IllegalArgumentException("Duplicate Spectrum column: " + left);
}
}
}
}
private static void requireText(String value, String field) {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException(field + " is required");
}
}
}
@@ -0,0 +1,121 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import jakarta.enterprise.context.ApplicationScoped;
import java.net.Socket;
import java.util.Optional;
@ApplicationScoped
public final class SpectrumInterceptor {
private final SpectrumCatalog catalog;
private final SpectrumStatementParser statementParser;
private final SpectrumQueryClassifier queryClassifier;
private final SpectrumQueryRewriter queryRewriter;
private final SpectrumS3Reader reader;
private final SpectrumMaterializer materializer;
public SpectrumInterceptor(SpectrumCatalog catalog, SpectrumStatementParser statementParser,
SpectrumQueryClassifier queryClassifier, SpectrumQueryRewriter queryRewriter,
SpectrumS3Reader reader, SpectrumMaterializer materializer) {
this.catalog = catalog;
this.statementParser = statementParser;
this.queryClassifier = queryClassifier;
this.queryRewriter = queryRewriter;
this.reader = reader;
this.materializer = materializer;
}
public Decision intercept(String sql, String accountId, String databaseName, Socket backend) {
Plan plan = plan(sql, accountId, databaseName);
return execute(plan, accountId, databaseName, backend);
}
public Plan plan(String sql, String accountId, String databaseName) {
Optional<SpectrumStatement> statement = statementParser.parse(sql);
if (statement.isPresent()) {
return new Plan.Ddl(statement.get());
}
Optional<SpectrumQuery> query = queryClassifier.classify(sql, 0);
if (query.isEmpty() || query.get().schemaName() == null) {
return new Plan.Forward();
}
SpectrumQuery externalQuery = query.get();
Optional<SpectrumExternalTable> table = catalog.table(
accountId, databaseName, externalQuery.schemaName(), externalQuery.tableName());
if (table.isEmpty()) {
return new Plan.Forward();
}
SpectrumExternalSchema schema = catalog.schema(accountId, databaseName, externalQuery.schemaName())
.orElseThrow(() -> new SpectrumSqlException("0A000", "External schema is not defined"));
return new Plan.Query(externalQuery, table.get(), schema, materializer.nextIdentifier());
}
public Decision execute(Plan plan, String accountId, String databaseName, Socket backend) {
switch (plan) {
case Plan.Ddl(SpectrumStatement parsed) -> {
switch (parsed) {
case SpectrumStatement.CreateSchema schema -> catalog.createSchema(new SpectrumExternalSchema(
accountId, schema.databaseName(), schema.schemaName(),
"s3://spectrum/" + schema.schemaName() + "/", schema.iamRoleArn()));
case SpectrumStatement.CreateTable table -> catalog.createTable(new SpectrumExternalTable(
accountId, databaseName, table.schemaName(), table.tableName(), table.columns(),
table.location(), table.delimiter(), table.quote(), table.escape(), table.nullValue(),
table.headerLines()));
}
return new Decision.Handled();
}
case Plan.Query(SpectrumQuery query, SpectrumExternalTable table, SpectrumExternalSchema schema, String identifier) -> {
SpectrumMaterializer.Materialization materialized = materializer.materialize(backend, table, schema, reader, identifier);
return new Decision.Rewritten(queryRewriter.rewrite(query, materialized.identifier()), materialized);
}
case Plan.Forward ignored -> {
return new Decision.Forward();
}
}
}
/**
* Drops the temp table a {@link Decision.Rewritten} materialized, once the client has finished
* reading its rows (or failed while doing so).
* <p>
* This eager cleanup is used by execution paths that manage the query round-trip explicitly, such
* as the Extended Query path in {@code ExtendedSpectrumExchange}. Under the Simple Query protocol,
* the temp table is session-scoped (via PostgreSQL {@code CREATE TEMP TABLE}) and cleaned up when
* the connection terminates, avoiding race conditions with the streaming backend-to-client pump.
* Each query materializes its own table, so a long-lived or pooled connection holds one copy per
* query until it closes.
*/
public void cleanup(Socket backend, SpectrumMaterializer.Materialization materialization) {
materializer.cleanup(backend, materialization);
}
public sealed interface Plan permits Plan.Ddl, Plan.Forward, Plan.Query {
record Ddl(SpectrumStatement statement) implements Plan {
}
record Forward() implements Plan {
}
record Query(SpectrumQuery query, SpectrumExternalTable table, SpectrumExternalSchema schema,
String identifier) implements Plan {
}
}
public sealed interface Decision permits Decision.Handled, Decision.Forward, Decision.Rewritten {
record Handled() implements Decision {
}
record Forward() implements Decision {
}
/**
* A Spectrum query rewritten into an executable SQL statement querying a temporary table.
* The materialized table is dropped eagerly via {@link SpectrumInterceptor#cleanup} on the
* Extended Query protocol, or released at session termination on the Simple Query protocol.
*/
record Rewritten(String sql, SpectrumMaterializer.Materialization materialization) implements Decision {
}
}
}
@@ -0,0 +1,221 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import jakarta.enterprise.context.ApplicationScoped;
import io.github.hectorvent.floci.services.redshift.proxy.PostgresWireDecoder;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.HexFormat;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@ApplicationScoped
public final class SpectrumMaterializer {
private static final SecureRandom RANDOM = new SecureRandom();
private static final String SQLSTATE_DATA = "22000";
public Materialization materialize(Socket backend, SpectrumExternalTable table,
SpectrumExternalSchema schema, SpectrumS3Reader reader) {
return materialize(backend, table, schema, reader, nextIdentifier());
}
public Materialization materialize(Socket backend, SpectrumExternalTable table,
SpectrumExternalSchema schema, SpectrumS3Reader reader, String identifier) {
Materialization materialization = new Materialization(identifier, table.columns());
OutputStream output = null;
boolean tableCreated = false;
boolean copyInProgress = false;
try {
output = backend.getOutputStream();
sendQuery(output, createTableSql(identifier, table));
awaitReady(backend);
tableCreated = true;
sendQuery(output, copySql(identifier, table));
awaitCopyIn(backend);
copyInProgress = true;
try (Stream<SpectrumRow> rows = reader.read(schema, table)) {
Iterator<SpectrumRow> iterator = rows.iterator();
while (iterator.hasNext()) {
writeCopyData(output, encodeRow(iterator.next()));
}
}
writeCopyDone(output);
copyInProgress = false;
awaitReady(backend);
return materialization;
} catch (SpectrumReadException exception) {
recoverFromFailure(backend, materialization, output, tableCreated, copyInProgress, exception);
throw exception;
} catch (IOException exception) {
SpectrumReadException readException = new SpectrumReadException(
SQLSTATE_DATA, "Unable to materialize Spectrum rows", exception);
recoverFromFailure(backend, materialization, output, tableCreated, copyInProgress, readException);
throw readException;
}
}
public String nextIdentifier() {
return "spectrum_tmp_" + HexFormat.of().formatHex(randomBytes(12));
}
public void cleanup(Socket backend, Materialization materialization) {
try {
OutputStream output = backend.getOutputStream();
sendQuery(output, "DROP TABLE IF EXISTS \"" + quoteIdentifier(materialization.identifier()) + "\"");
awaitReady(backend);
} catch (IOException exception) {
throw new SpectrumReadException(SQLSTATE_DATA, "Unable to clean up Spectrum materialization", exception);
}
}
private static String createTableSql(String identifier, SpectrumExternalTable table) {
StringBuilder sql = new StringBuilder("CREATE TEMP TABLE \"")
.append(quoteIdentifier(identifier)).append("\" (");
for (int i = 0; i < table.columns().size(); i++) {
if (i > 0) {
sql.append(", ");
}
SpectrumColumn column = table.columns().get(i);
sql.append('"').append(quoteIdentifier(column.name())).append("\" ").append(column.type().postgresType());
}
return sql.append(')').toString();
}
private static String copySql(String identifier, SpectrumExternalTable table) {
return "COPY \"" + quoteIdentifier(identifier) + "\" ("
+ table.columns().stream().map(column -> "\"" + quoteIdentifier(column.name()) + "\"")
.collect(Collectors.joining(", "))
+ ") FROM STDIN";
}
private static byte[] encodeRow(SpectrumRow row) {
StringBuilder line = new StringBuilder();
for (int i = 0; i < row.values().size(); i++) {
if (i > 0) {
line.append('\t');
}
String value = row.values().get(i);
if (value == null) {
line.append("\\N");
} else {
line.append(value.replace("\\", "\\\\").replace("\t", "\\t")
.replace("\n", "\\n").replace("\r", "\\r"));
}
}
line.append('\n');
return line.toString().getBytes(StandardCharsets.UTF_8);
}
private static void sendQuery(OutputStream output, String sql) throws IOException {
output.write(PostgresWireDecoder.encodeQuery(sql));
output.flush();
}
private static void writeCopyData(OutputStream output, byte[] data) throws IOException {
output.write('d');
writeInt32(output, data.length + 4);
output.write(data);
}
private static void writeCopyDone(OutputStream output) throws IOException {
output.write('c');
writeInt32(output, 4);
output.flush();
}
private static void writeCopyFail(OutputStream output, String reason) throws IOException {
byte[] body = (reason == null ? "Spectrum row conversion failed" : reason).getBytes(StandardCharsets.UTF_8);
output.write('f');
writeInt32(output, body.length + 5);
output.write(body);
output.write(0);
output.flush();
}
private static void writeInt32(OutputStream output, int value) throws IOException {
output.write((value >>> 24) & 0xFF);
output.write((value >>> 16) & 0xFF);
output.write((value >>> 8) & 0xFF);
output.write(value & 0xFF);
}
private static void awaitCopyIn(Socket backend) throws IOException {
PostgresWireDecoder decoder = new PostgresWireDecoder(backend.getInputStream());
PostgresWireDecoder.FrontendMessage message;
SpectrumReadException backendFailure = null;
while ((message = decoder.nextMessage()) != null) {
if (message.type() == 'G') {
return;
}
if (message.type() == 'E') {
backendFailure = new SpectrumReadException(SQLSTATE_DATA, "PostgreSQL rejected Spectrum COPY");
}
if (message.type() == 'Z' && backendFailure != null) {
throw backendFailure;
}
}
throw new IOException("PostgreSQL closed before CopyInResponse");
}
private static void awaitReady(Socket backend) throws IOException {
PostgresWireDecoder decoder = new PostgresWireDecoder(backend.getInputStream());
PostgresWireDecoder.FrontendMessage message;
SpectrumReadException backendFailure = null;
while ((message = decoder.nextMessage()) != null) {
if (message.type() == 'Z') {
if (backendFailure != null) {
throw backendFailure;
}
return;
}
if (message.type() == 'E') {
backendFailure = new SpectrumReadException(SQLSTATE_DATA, "PostgreSQL rejected Spectrum statement");
}
}
throw new IOException("PostgreSQL closed before ReadyForQuery");
}
private void recoverFromFailure(Socket backend, Materialization materialization, OutputStream output,
boolean tableCreated, boolean copyInProgress,
SpectrumReadException original) {
if (copyInProgress && output != null) {
try {
writeCopyFail(output, original.getMessage());
awaitReady(backend);
} catch (IOException | SpectrumReadException cleanupFailure) {
original.addSuppressed(cleanupFailure);
}
}
if (tableCreated) {
try {
cleanup(backend, materialization);
} catch (RuntimeException cleanupFailure) {
original.addSuppressed(cleanupFailure);
}
}
}
private static String quoteIdentifier(String value) {
return value.replace("\"", "\"\"");
}
private static byte[] randomBytes(int length) {
byte[] bytes = new byte[length];
RANDOM.nextBytes(bytes);
return bytes;
}
public record Materialization(String identifier, List<SpectrumColumn> columns) {
public Materialization {
columns = List.copyOf(columns);
}
}
}
@@ -0,0 +1,9 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
public record SpectrumQuery(
String schemaName,
String tableName,
String projectionSql,
String predicateSql,
boolean selectStar) {
}
@@ -0,0 +1,120 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.Locale;
import java.util.Optional;
@ApplicationScoped
public final class SpectrumQueryClassifier {
public Optional<SpectrumQuery> classify(String sql, int parameterCount) {
String normalized = sql == null ? "" : sql.trim();
if (!startsWithKeyword(normalized, "SELECT")) {
return Optional.empty();
}
if (parameterCount > 0 || containsOutsideQuotes(normalized, '?')) {
return Optional.empty();
}
String statement = stripTrailingSemicolon(normalized);
if (statement.indexOf(';') >= 0 || hasParenthesesOutsideQuotes(statement)) {
return Optional.empty();
}
String lower = statement.toLowerCase(Locale.ROOT);
for (String keyword : new String[]{" join ", " group ", " order ", " having ", " union ", " intersect ",
" except ", " limit ", " offset ", " distinct "}) {
if (lower.contains(keyword)) {
return Optional.empty();
}
}
int from = keywordIndex(statement, "from", 6);
if (from < 0) {
return Optional.empty();
}
String projection = statement.substring(6, from).trim();
if (projection.isEmpty() || projection.contains(",") && projection.contains("(")) {
return Optional.empty();
}
String source = statement.substring(from + 4).trim();
int where = keywordIndex(source, "where", 0);
String tablePart = where < 0 ? source : source.substring(0, where).trim();
String predicate = where < 0 ? null : source.substring(where + 5).trim();
if (!isIdentifierPath(tablePart) || (predicate != null && !simplePredicate(predicate))) {
return Optional.empty();
}
String[] identifiers = tablePart.split("\\.", -1);
String schema = identifiers.length == 2 ? identifier(identifiers[0]) : null;
String table = identifier(identifiers[identifiers.length - 1]);
boolean star = "*".equals(projection);
if (!star && !isProjection(projection)) {
return Optional.empty();
}
return Optional.of(new SpectrumQuery(schema, table, projection, predicate, star));
}
private static boolean simplePredicate(String predicate) {
String lower = predicate.toLowerCase(Locale.ROOT);
return !lower.contains(" or ") && !lower.contains(" in ") && !lower.contains(" like ")
&& !lower.contains(" is ") && predicate.matches("[\\w\\\".]+\\s*(=|<>|!=|<=|>=|<|>)\\s*('[^']*(?:''[^']*)*'|-?\\d+(?:\\.\\d+)?)"
+ "(?:\\s+AND\\s+[\\w\\\".]+\\s*(?:=|<>|!=|<=|>=|<|>)\\s*(?:'[^']*(?:''[^']*)*'|-?\\d+(?:\\.\\d+)?))*");
}
private static boolean isProjection(String projection) {
for (String part : projection.split(",")) {
if (!isIdentifierPath(part.trim())) {
return false;
}
}
return true;
}
private static boolean isIdentifierPath(String value) {
return value.matches("(?:[A-Za-z_][A-Za-z0-9_$]*|\"(?:\"\"|[^\"])+\")(?:\\.(?:[A-Za-z_][A-Za-z0-9_$]*|\"(?:\"\"|[^\"])+\")){0,1}");
}
private static String identifier(String value) {
String trimmed = value.trim();
if (trimmed.startsWith("\"") && trimmed.endsWith("\"")) {
return trimmed.substring(1, trimmed.length() - 1).replace("\"\"", "\"");
}
return trimmed.toLowerCase(Locale.ROOT);
}
private static int keywordIndex(String sql, String keyword, int start) {
String lower = sql.toLowerCase(Locale.ROOT);
for (int i = start; i <= lower.length() - keyword.length(); i++) {
if (lower.regionMatches(i, keyword, 0, keyword.length())
&& (i == 0 || Character.isWhitespace(lower.charAt(i - 1)))
&& (i + keyword.length() == lower.length() || Character.isWhitespace(lower.charAt(i + keyword.length())))) {
return i;
}
}
return -1;
}
private static boolean startsWithKeyword(String sql, String keyword) {
return sql.regionMatches(true, 0, keyword, 0, keyword.length())
&& (sql.length() == keyword.length() || Character.isWhitespace(sql.charAt(keyword.length())));
}
private static String stripTrailingSemicolon(String sql) {
return sql.endsWith(";") ? sql.substring(0, sql.length() - 1).trim() : sql;
}
private static boolean containsOutsideQuotes(String sql, char target) {
boolean quoted = false;
for (int i = 0; i < sql.length(); i++) {
char current = sql.charAt(i);
if (current == '\'') {
quoted = !quoted;
} else if (!quoted && current == target) {
return true;
}
}
return false;
}
private static boolean hasParenthesesOutsideQuotes(String sql) {
return containsOutsideQuotes(sql, '(') || containsOutsideQuotes(sql, ')');
}
}
@@ -0,0 +1,58 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
@ApplicationScoped
public final class SpectrumQueryRewriter {
public SpectrumQueryRewriter() {
}
public static String rewrite(SpectrumQuery query, String materializedIdentifier) {
if (materializedIdentifier == null || materializedIdentifier.isBlank()) {
throw new IllegalArgumentException("materializedIdentifier is required");
}
String projection = query.selectStar() ? "*" : query.projectionSql();
StringBuilder sql = new StringBuilder("SELECT ").append(projection)
.append(" FROM \"").append(materializedIdentifier.replace("\"", "\"\""))
.append('"');
if (query.predicateSql() != null && !query.predicateSql().isBlank()) {
sql.append(" WHERE ").append(query.predicateSql());
}
return sql.toString();
}
/**
* The columns {@code query} projects from {@code table}, in output order. {@link SpectrumQueryClassifier}
* only ever accepts {@code *} or a comma-separated list of plain (optionally schema-qualified)
* identifiers as a projection, so this is a complete, exact mapping, not a heuristic: it is what
* an Extended Query Describe response is built from without a backend round trip.
*/
public static List<SpectrumColumn> outputColumns(SpectrumQuery query, SpectrumExternalTable table) {
if (query.selectStar()) {
return table.columns();
}
List<SpectrumColumn> columns = new ArrayList<>();
for (String part : query.projectionSql().split(",")) {
String name = normalizeIdentifier(part.trim());
columns.add(table.columns().stream()
.filter(column -> column.name().equalsIgnoreCase(name))
.findFirst()
.orElseThrow(() -> new SpectrumSqlException("42703",
"column \"" + name + "\" does not exist on external table")));
}
return columns;
}
private static String normalizeIdentifier(String value) {
String local = value.substring(value.lastIndexOf('.') + 1);
if (local.length() >= 2 && local.startsWith("\"") && local.endsWith("\"")) {
return local.substring(1, local.length() - 1).replace("\"\"", "\"");
}
return local.toLowerCase(Locale.ROOT);
}
}
@@ -0,0 +1,20 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
public class SpectrumReadException extends RuntimeException {
private final String sqlState;
public SpectrumReadException(String sqlState, String message) {
super(message);
this.sqlState = sqlState;
}
public SpectrumReadException(String sqlState, String message, Throwable cause) {
super(message, cause);
this.sqlState = sqlState;
}
public String sqlState() {
return sqlState;
}
}
@@ -0,0 +1,12 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public record SpectrumRow(List<String> values) {
public SpectrumRow {
values = Collections.unmodifiableList(new ArrayList<>(values));
}
}
@@ -0,0 +1,275 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import jakarta.enterprise.context.ApplicationScoped;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
@ApplicationScoped
public final class SpectrumS3Reader {
private static final String SQLSTATE_AUTHORIZATION = "42501";
private static final String SQLSTATE_DATA = "22000";
private static final String SQLSTATE_INTERNAL = "XX000";
private final S3Service s3Service;
// Stored in the schema now so role-aware Spectrum authorization can be added without changing metadata.
@SuppressWarnings("unused")
private final IamService iamService;
public SpectrumS3Reader(S3Service s3Service, IamService iamService) {
this.s3Service = s3Service;
this.iamService = iamService;
}
public Stream<SpectrumRow> read(SpectrumExternalSchema schema, SpectrumExternalTable table) {
Location location = Location.parse(table.location());
try {
s3Service.authorizeAnonymousListBucket(location.bucket());
List<S3Object> objects = new ArrayList<>();
String continuationToken = null;
do {
S3Service.ListObjectsResult result = s3Service.listObjectsWithPrefixes(
location.bucket(), location.key(), "", 1000, continuationToken, null);
objects.addAll(result.objects());
continuationToken = result.isTruncated() ? result.nextContinuationToken() : null;
} while (continuationToken != null);
List<String> keys = objects.stream()
.map(S3Object::getKey)
.sorted(Comparator.naturalOrder())
.toList();
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
new RowIterator(location.bucket(), keys.iterator(), table), 0), false);
} catch (AwsException exception) {
throw mapAwsException(location, exception);
}
}
private SpectrumReadException mapAwsException(Location location, AwsException exception) {
String state = switch (exception.getErrorCode()) {
case "AccessDenied", "Unauthorized", "Forbidden" -> SQLSTATE_AUTHORIZATION;
default -> SQLSTATE_INTERNAL;
};
return new SpectrumReadException(state,
"Unable to read Spectrum location " + location.uri(), exception);
}
private final class RowIterator implements Iterator<SpectrumRow> {
private final String bucket;
private final Iterator<String> keys;
private final SpectrumExternalTable table;
private BufferedReader reader;
private SpectrumRow next;
private boolean finished;
private String currentKey;
private RowIterator(String bucket, Iterator<String> keys, SpectrumExternalTable table) {
this.bucket = bucket;
this.keys = keys;
this.table = table;
}
@Override
public boolean hasNext() {
if (next == null && !finished) {
advance();
}
return next != null;
}
@Override
public SpectrumRow next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
SpectrumRow result = next;
next = null;
return result;
}
private void advance() {
try {
while (true) {
if (reader == null) {
if (!keys.hasNext()) {
finished = true;
return;
}
currentKey = keys.next();
s3Service.authorizeAnonymousGetObject(bucket, currentKey);
S3Object object = s3Service.getObject(bucket, currentKey);
reader = new BufferedReader(new InputStreamReader(
new ByteArrayInputStream(object.getData()), StandardCharsets.UTF_8));
skipHeaders();
}
String record = readRecord(reader, table.quote(), table.escape());
if (record == null) {
reader.close();
reader = null;
continue;
}
if (record.isEmpty()) {
continue;
}
next = convert(record, table);
return;
}
} catch (AwsException exception) {
throw mapAwsException(new Location(bucket, currentKey), exception);
} catch (IOException exception) {
throw new SpectrumReadException(SQLSTATE_INTERNAL, "Unable to close Spectrum object", exception);
}
}
private void skipHeaders() throws IOException {
for (int i = 0; i < table.headerLines(); i++) {
if (readRecord(reader, table.quote(), table.escape()) == null) {
return;
}
}
}
}
private static SpectrumRow convert(String record, SpectrumExternalTable table) {
List<String> fields = parseFields(record, table.delimiter(), table.quote(), table.escape());
if (fields.size() != table.columns().size()) {
throw new SpectrumReadException(SQLSTATE_DATA,
"Spectrum row has " + fields.size() + " fields, expected " + table.columns().size());
}
List<String> converted = new ArrayList<>(fields.size());
for (int i = 0; i < fields.size(); i++) {
String value = fields.get(i);
converted.add(value.equals(table.nullValue()) ? null : convertValue(value, table.columns().get(i).type()));
}
return new SpectrumRow(converted);
}
private static String convertValue(String value, SpectrumColumn.Type type) {
try {
return switch (type) {
case VARCHAR, CHAR -> value;
case INTEGER -> Integer.toString(Integer.parseInt(value));
case BIGINT -> Long.toString(Long.parseLong(value));
case DECIMAL -> new BigDecimal(value).toString();
case BOOLEAN -> parseBoolean(value);
case DATE -> LocalDate.parse(value).toString();
case TIMESTAMP -> parseTimestamp(value);
};
} catch (NumberFormatException | DateTimeParseException exception) {
throw new SpectrumReadException(SQLSTATE_DATA, "Invalid " + type + " value", exception);
}
}
private static String parseBoolean(String value) {
if ("true".equalsIgnoreCase(value)) {
return "true";
}
if ("false".equalsIgnoreCase(value)) {
return "false";
}
throw new SpectrumReadException(SQLSTATE_DATA, "Invalid BOOLEAN value");
}
private static String parseTimestamp(String value) {
try {
return LocalDateTime.parse(value).toString();
} catch (DateTimeParseException ignored) {
return OffsetDateTime.parse(value).toLocalDateTime().toString();
}
}
private static List<String> parseFields(String record, char delimiter, char quote, char escape) {
List<String> fields = new ArrayList<>();
StringBuilder field = new StringBuilder();
boolean quoted = false;
for (int i = 0; i < record.length(); i++) {
char current = record.charAt(i);
if (current == escape && quoted && i + 1 < record.length()) {
field.append(record.charAt(++i));
} else if (current == quote) {
if (quoted && i + 1 < record.length() && record.charAt(i + 1) == quote) {
field.append(quote);
i++;
} else {
quoted = !quoted;
}
} else if (current == delimiter && !quoted) {
fields.add(field.toString());
field.setLength(0);
} else {
field.append(current);
}
}
if (quoted) {
throw new SpectrumReadException(SQLSTATE_DATA, "Unterminated quoted CSV field");
}
fields.add(field.toString());
return fields;
}
private static String readRecord(BufferedReader reader, char quote, char escape) throws IOException {
StringBuilder record = new StringBuilder();
boolean quoted = false;
int value;
while ((value = reader.read()) != -1) {
char current = (char) value;
if (current == escape && !quoted) {
record.append(current);
int next = reader.read();
if (next == -1) {
break;
}
record.append((char) next);
} else if (current == quote) {
quoted = !quoted;
record.append(current);
} else if (current == '\n' && !quoted) {
break;
} else if (current != '\r') {
record.append(current);
}
}
if (value == -1 && record.isEmpty()) {
return null;
}
return record.toString();
}
private record Location(String bucket, String key) {
private static Location parse(String uri) {
if (uri == null || !uri.startsWith("s3://")) {
throw new SpectrumReadException(SQLSTATE_INTERNAL, "Spectrum location must use s3://");
}
String path = uri.substring(5);
int slash = path.indexOf('/');
if (slash <= 0) {
throw new SpectrumReadException(SQLSTATE_INTERNAL, "Spectrum location must include a bucket and key");
}
return new Location(path.substring(0, slash), path.substring(slash + 1));
}
private String uri() {
return "s3://" + bucket + "/" + key;
}
}
}
@@ -0,0 +1,15 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
public class SpectrumSqlException extends RuntimeException {
private final String sqlState;
public SpectrumSqlException(String sqlState, String message) {
super(message);
this.sqlState = sqlState;
}
public String sqlState() {
return sqlState;
}
}
@@ -0,0 +1,25 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import java.util.List;
public sealed interface SpectrumStatement permits SpectrumStatement.CreateSchema, SpectrumStatement.CreateTable {
record CreateSchema(String schemaName, String databaseName, String iamRoleArn) implements SpectrumStatement {
}
record CreateTable(
String schemaName,
String tableName,
List<SpectrumColumn> columns,
String location,
char delimiter,
char quote,
char escape,
String nullValue,
int headerLines) implements SpectrumStatement {
public CreateTable {
columns = List.copyOf(columns);
}
}
}
@@ -0,0 +1,330 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
@ApplicationScoped
public final class SpectrumStatementParser {
private static final String UNSUPPORTED = "0A000";
private static final String INVALID_VALUE = "22023";
public Optional<SpectrumStatement> parse(String sql) {
List<Token> tokens = new Tokenizer(sql).tokenize();
Cursor cursor = new Cursor(tokens);
if (cursor.peekKeyword("CREATE") && cursor.peekKeyword(1, "EXTERNAL") && cursor.peekKeyword(2, "SCHEMA")) {
return Optional.of(parseSchema(cursor));
}
if (cursor.peekKeyword("CREATE") && cursor.peekKeyword(1, "EXTERNAL") && cursor.peekKeyword(2, "TABLE")) {
return Optional.of(parseTable(cursor));
}
if (cursor.peekKeyword("CREATE") && cursor.peekKeyword(1, "EXTERNAL")) {
throw unsupported("unsupported CREATE EXTERNAL statement");
}
return Optional.empty();
}
private SpectrumStatement.CreateSchema parseSchema(Cursor cursor) {
cursor.expectKeyword("CREATE");
cursor.expectKeyword("EXTERNAL");
cursor.expectKeyword("SCHEMA");
String schema = cursor.identifier();
cursor.expectKeyword("FROM");
cursor.expectKeyword("DATA");
cursor.expectKeyword("CATALOG");
cursor.expectKeyword("DATABASE");
String database = cursor.stringLiteral();
cursor.expectKeyword("IAM_ROLE");
String role = cursor.stringLiteral();
if (cursor.peekKeyword("CREATE")) {
cursor.expectKeyword("CREATE");
cursor.expectKeyword("EXTERNAL");
cursor.expectKeyword("DATABASE");
cursor.expectKeyword("IF");
cursor.expectKeyword("NOT");
cursor.expectKeyword("EXISTS");
}
cursor.finish();
return new SpectrumStatement.CreateSchema(schema, database, role);
}
private SpectrumStatement.CreateTable parseTable(Cursor cursor) {
cursor.expectKeyword("CREATE");
cursor.expectKeyword("EXTERNAL");
cursor.expectKeyword("TABLE");
String schema = cursor.identifier();
cursor.expectSymbol('.');
String table = cursor.identifier();
cursor.expectSymbol('(');
List<SpectrumColumn> columns = new ArrayList<>();
while (!cursor.peekSymbol(')')) {
String name = cursor.identifier();
String type = cursor.identifier();
try {
columns.add(new SpectrumColumn(name, SpectrumColumn.Type.fromSql(type)));
} catch (IllegalArgumentException exception) {
throw new SpectrumSqlException(INVALID_VALUE, exception.getMessage());
}
if (!cursor.consumeSymbol(',')) {
break;
}
}
cursor.expectSymbol(')');
cursor.expectKeyword("STORED");
cursor.expectKeyword("AS");
if (!cursor.consumeKeyword("TEXTFILE")) {
throw unsupported("only STORED AS TEXTFILE is supported");
}
cursor.expectKeyword("LOCATION");
String location = cursor.stringLiteral();
String nullValue = "\\N";
char delimiter = ',';
char quote = '"';
char escape = '\\';
int headerLines = 0;
if (cursor.consumeKeyword("TBLPROPERTIES")) {
cursor.expectSymbol('(');
Map<String, String> properties = new HashMap<>();
while (!cursor.peekSymbol(')')) {
String name = cursor.stringLiteral();
cursor.expectSymbol('=');
String value = cursor.stringLiteral();
if (properties.put(name, value) != null) {
throw unsupported("duplicate Spectrum table property: " + name);
}
if (!SetOfProperties.SUPPORTED.contains(name)) {
throw unsupported("unsupported Spectrum table property: " + name);
}
if (!cursor.consumeSymbol(',')) {
break;
}
}
cursor.expectSymbol(')');
try {
if (properties.containsKey("skip.header.line.count")) {
headerLines = Integer.parseInt(properties.get("skip.header.line.count"));
if (headerLines < 0) {
throw new IllegalArgumentException("skip.header.line.count must not be negative");
}
}
delimiter = oneCharacter(properties, "field.delim", delimiter);
char serialization = oneCharacter(properties, "serialization.format", delimiter);
if (properties.containsKey("field.delim") && properties.containsKey("serialization.format")
&& serialization != delimiter) {
throw new IllegalArgumentException("field.delim and serialization.format must match");
}
delimiter = serialization;
quote = oneCharacter(properties, "quoteChar", quote);
escape = oneCharacter(properties, "escapeChar", escape);
nullValue = properties.getOrDefault("serialization.null.format", nullValue);
} catch (IllegalArgumentException exception) {
throw new SpectrumSqlException(INVALID_VALUE, exception.getMessage());
}
}
cursor.finish();
try {
SpectrumExternalSchema.validateS3Location(location);
} catch (IllegalArgumentException exception) {
throw new SpectrumSqlException(INVALID_VALUE, exception.getMessage());
}
return new SpectrumStatement.CreateTable(schema, table, columns, location, delimiter, quote, escape, nullValue,
headerLines);
}
private static char oneCharacter(Map<String, String> properties, String name, char defaultValue) {
String value = properties.get(name);
if (value == null) {
return defaultValue;
}
if (value.length() != 1) {
throw new IllegalArgumentException(name + " must contain exactly one character");
}
return value.charAt(0);
}
private static SpectrumSqlException unsupported(String message) {
return new SpectrumSqlException(UNSUPPORTED, message);
}
private static final class SetOfProperties {
private static final Set<String> SUPPORTED = Set.of(
"skip.header.line.count", "field.delim", "serialization.format", "quoteChar", "escapeChar",
"serialization.null.format");
private SetOfProperties() {
}
}
private record Token(Kind kind, String text, boolean quoted) {
private enum Kind { IDENTIFIER, STRING, SYMBOL, END }
}
private static final class Cursor {
private final List<Token> tokens;
private int position;
private Cursor(List<Token> tokens) {
this.tokens = tokens;
}
private boolean peekKeyword(String value) {
return peekKeyword(0, value);
}
private boolean peekKeyword(int offset, String value) {
Token token = tokens.get(Math.min(position + offset, tokens.size() - 1));
return token.kind() == Token.Kind.IDENTIFIER && !token.quoted()
&& token.text().equalsIgnoreCase(value);
}
private boolean consumeKeyword(String value) {
if (!peekKeyword(value)) {
return false;
}
position++;
return true;
}
private void expectKeyword(String value) {
if (!consumeKeyword(value)) {
throw unsupported("expected keyword " + value);
}
}
private String identifier() {
Token token = current();
if (token.kind() != Token.Kind.IDENTIFIER) {
throw unsupported("expected identifier");
}
position++;
return token.text();
}
private String stringLiteral() {
Token token = current();
if (token.kind() != Token.Kind.STRING) {
throw unsupported("expected string literal");
}
position++;
return token.text();
}
private void expectSymbol(char symbol) {
if (!consumeSymbol(symbol)) {
throw unsupported("expected symbol " + symbol);
}
}
private boolean consumeSymbol(char symbol) {
Token token = current();
if (token.kind() == Token.Kind.SYMBOL && token.text().charAt(0) == symbol) {
position++;
return true;
}
return false;
}
private boolean peekSymbol(char symbol) {
Token token = current();
return token.kind() == Token.Kind.SYMBOL && token.text().charAt(0) == symbol;
}
private void finish() {
if (consumeSymbol(';')) {
if (current().kind() != Token.Kind.END) {
throw unsupported("trailing SQL is not supported");
}
return;
}
if (current().kind() != Token.Kind.END) {
throw unsupported("trailing SQL is not supported");
}
}
private Token current() {
return tokens.get(position);
}
}
private static final class Tokenizer {
private final String sql;
private int position;
private Tokenizer(String sql) {
this.sql = sql == null ? "" : sql;
}
private List<Token> tokenize() {
List<Token> tokens = new ArrayList<>();
while (position < sql.length()) {
char current = sql.charAt(position);
if (Character.isWhitespace(current)) {
position++;
} else if (current == '-' && position + 1 < sql.length() && sql.charAt(position + 1) == '-') {
skipComment();
} else if (current == '\'') {
tokens.add(new Token(Token.Kind.STRING, readQuoted('\''), true));
} else if (current == '"') {
tokens.add(new Token(Token.Kind.IDENTIFIER, readQuoted('"'), true));
} else if (isSymbol(current)) {
tokens.add(new Token(Token.Kind.SYMBOL, String.valueOf(current), false));
position++;
} else {
tokens.add(new Token(Token.Kind.IDENTIFIER, readIdentifier(), false));
}
}
tokens.add(new Token(Token.Kind.END, "", false));
return tokens;
}
private void skipComment() {
position += 2;
while (position < sql.length() && sql.charAt(position) != '\n') {
position++;
}
}
private String readQuoted(char delimiter) {
position++;
StringBuilder value = new StringBuilder();
while (position < sql.length()) {
char current = sql.charAt(position++);
if (current == delimiter) {
if (position < sql.length() && sql.charAt(position) == delimiter) {
value.append(delimiter);
position++;
} else {
return value.toString();
}
} else {
value.append(current);
}
}
throw unsupported("unterminated quoted value");
}
private String readIdentifier() {
int start = position;
while (position < sql.length()) {
char current = sql.charAt(position);
if (Character.isWhitespace(current) || isSymbol(current) || current == '\'') {
break;
}
position++;
}
String value = sql.substring(start, position);
return value.toLowerCase(Locale.ROOT);
}
private static boolean isSymbol(char value) {
return value == '(' || value == ')' || value == ',' || value == '.' || value == ';' || value == '=';
}
}
}