feat(redshift): add relational queries for Redshift Spectrum (#5095)

* feat: add relational queries for Redshift Spectrum

* fix(redshift): harden Spectrum relational query preparation

Catch RuntimeException during preparation so the client gets an ErrorResponse
instead of a dropped connection, skip preparation while the backend discards
until Sync, defer schema binding until the transaction commits, make the
catalog functions SECURITY DEFINER, and track COMMIT and ROLLBACK from the
command tag.

* fix(redshift): address review findings on transaction handling in Spectrum relational queries

- Undo Glue tables created inside a rolled back transaction (Data API batch and wire proxy)
- Keep bindings and Glue tables on ROLLBACK TO SAVEPOINT; only a closed transaction discards them
- Report the real transaction status for locally handled simple queries instead of idle
- Use a switch expression in BackendResponseCoordinator
- Map host.docker.internal into the floci-duck container on Linux

* fix(redshift): undo Glue tables across sessions and on rollback to savepoint

- Scope staged Glue tables by the backend socket so the proxy rollback finds tables created by another session
- Track SAVEPOINT, ROLLBACK TO and RELEASE so a Data API batch undoes only the tables created after the savepoint

* fix(redshift): defer Glue undo on rollback to savepoint until the backend confirms and bundle bootstrap catalog in native image

* fix(redshift): reject CREATE EXTERNAL TABLE inside a transaction like AWS

AWS does not allow CREATE EXTERNAL TABLE inside a transaction block, and a
Data API batch runs as one transaction. Return SQLSTATE 25001 instead of
staging Glue tables and undoing them on rollback, which removes the savepoint
tracking and cross-session undo code. Reuse ExternalTableMaterializer.quote.

* fix(redshift): reject CREATE EXTERNAL TABLE in a transaction for legacy schemas too
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-06 15:30:53 -04:00
1 parent a7e2447a34
commit 950b6fe774
30 files changed
+1773 -68

No files matched your search

@@ -122,6 +122,7 @@ public class FlociDuckManager {
.withDynamicPort(DUCK_PORT)
.withDockerNetwork(config.services().dockerNetwork())
.withEmbeddedDns()
.withHostDockerInternalOnLinux()
.withLogRotation()
.build();
@@ -603,6 +603,7 @@ public class RedshiftService {
}
containerManager.stop(clusters.accountId(), identifier);
proxyManager.forgetSpectrumRuntime(relayKey(clusters.accountId(), identifier));
clusters.delete(identifier);
clusters.flush();
// Invalidate any GetClusterCredentials passwords so a cluster later recreated with this
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
@@ -106,6 +107,9 @@ final class BackendResponseCoordinator {
void onBackendFrame(char type, byte[] body) {
lock.lock();
try {
if (type == 'C') {
updateStatusFromCommandTag(new String(body, StandardCharsets.UTF_8));
}
if (type == 'Z') {
updateReadyStatus(body);
}
@@ -215,6 +219,28 @@ final class BackendResponseCoordinator {
}
}
/**
* Tracks transaction boundaries as the tag arrives, so a statement pipelined after COMMIT sees them. The
* ROLLBACK tag is also sent for ROLLBACK TO SAVEPOINT, which leaves the transaction open, so only the
* ReadyForQuery status can say that a rollback ended it.
*/
private void updateStatusFromCommandTag(String tag) {
boolean transactionEnded = switch (tag) {
case "BEGIN\0" -> {
lastReadyStatus = 'T';
yield false;
}
case "COMMIT\0", "END\0" -> {
lastReadyStatus = 'I';
yield true;
}
default -> false;
};
if (transactionEnded) {
session.transactionEnded();
}
}
private void updateReadyStatus(byte[] body) {
if (body != null && body.length == 1) {
lastReadyStatus = (char) body[0];
@@ -5,8 +5,8 @@ import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;
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 io.github.hectorvent.floci.services.s3.S3Service;
import org.jboss.logging.Logger;
import java.io.IOException;
@@ -222,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, spectrumInterceptor).run();
clusterAccountId, iamRoleArns, spectrumInterceptor, clusterKey, dbName).run();
}
} catch (Exception e) {
LOG.debugv("Redshift connection error for cluster {0}: {1}", clusterKey, e.getMessage());
@@ -1,10 +1,12 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.redshift.spectrum.PostgresExtendedBackendSession;
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.SpectrumSession;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumSqlException;
import io.github.hectorvent.floci.services.s3.S3Service;
import org.jboss.logging.Logger;
@@ -60,6 +62,10 @@ public class RedshiftInterceptingBridge {
private final String clusterAccountId;
private final List<String> iamRoleArns;
private final SpectrumInterceptor spectrumInterceptor;
private final String clusterKey;
private final String databaseName;
private final PostgresExtendedBackendSession relationalBackend;
private final Map<String, PostgresWireDecoder.ParseMessage> relationalStatements = new HashMap<>();
private final ExtendedQuerySession session = new ExtendedQuerySession();
private final Map<String, SpectrumInterceptor.Plan> spectrumStatements = new HashMap<>();
private final Map<String, SpectrumInterceptor.Plan> spectrumPortals = new HashMap<>();
@@ -70,6 +76,7 @@ public class RedshiftInterceptingBridge {
private volatile boolean pumpBetweenMessages = true;
private volatile boolean pumpFinished = false;
private boolean extendedSpectrumError;
private boolean rolledBackInCycle;
public RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService) {
this(client, backend, s3Service, iamService, null);
@@ -82,12 +89,13 @@ public class RedshiftInterceptingBridge {
public RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService,
String clusterAccountId, List<String> iamRoleArns) {
this(client, backend, s3Service, iamService, clusterAccountId, iamRoleArns, null);
// Without a Spectrum interceptor the cluster key and database name are never read.
this(client, backend, s3Service, iamService, clusterAccountId, iamRoleArns, null, null, null);
}
public RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService,
String clusterAccountId, List<String> iamRoleArns,
SpectrumInterceptor spectrumInterceptor) {
SpectrumInterceptor spectrumInterceptor, String clusterKey, String databaseName) {
this.client = client;
this.backend = backend;
this.s3Service = s3Service;
@@ -95,6 +103,14 @@ public class RedshiftInterceptingBridge {
this.clusterAccountId = clusterAccountId;
this.iamRoleArns = iamRoleArns == null ? List.of() : List.copyOf(iamRoleArns);
this.spectrumInterceptor = spectrumInterceptor;
this.clusterKey = clusterKey;
this.databaseName = databaseName;
this.relationalBackend = new PostgresExtendedBackendSession(backend);
}
private SpectrumSession spectrumSession() {
return new SpectrumSession(clusterAccountId, clusterKey, databaseName, iamRoleArns,
coordinator.lastReadyStatus() != 'I');
}
@FunctionalInterface
@@ -171,6 +187,9 @@ public class RedshiftInterceptingBridge {
} catch (Exception e) {
LOG.warnv(e, "Unexpected error in RedshiftInterceptingBridge");
} finally {
if (spectrumInterceptor != null && spectrumInterceptor.preparation() != null) {
spectrumInterceptor.preparation().finishCycle(relationalBackend);
}
coordinator.close();
closeQuietly(client, "client");
closeQuietly(backend, "backend");
@@ -185,18 +204,22 @@ public class RedshiftInterceptingBridge {
boolean intercepted;
try {
intercepted = runWithBackendOwned(() -> {
decision[0] = spectrumInterceptor.intercept(sql, clusterAccountId, "dev", backend);
decision[0] = spectrumInterceptor.intercept(sql, spectrumSession(), backend);
return true;
});
} catch (SpectrumSqlException | SpectrumReadException | IllegalArgumentException exception) {
} catch (RuntimeException exception) {
writeSimpleSpectrumError(exception);
return;
}
if (!intercepted && spectrumInterceptor.preparation() != null
&& spectrumInterceptor.preparation().referencesExternal(sql, spectrumSession())) {
writeSimpleSpectrumError(new SpectrumReadException("58030", "Unable to prepare external query"));
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'});
reportLocalReady();
return;
}
if (intercepted && decision[0] instanceof SpectrumInterceptor.Decision.Rewritten rewritten) {
@@ -246,16 +269,39 @@ public class RedshiftInterceptingBridge {
// 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());
relationalStatements.remove(parse.statementName());
// After a backend error the backend discards everything up to Sync, so a preparation round trip
// would only wait out the socket timeout; forward the Parse and let the backend discard it.
if (spectrumInterceptor != null && spectrumInterceptor.preparation() != null
&& !coordinator.isDiscardingUntilSync()
&& spectrumInterceptor.preparation().referencesExternal(parse.sql(), spectrumSession())) {
try {
write(backendOut, new byte[]{'H', 0, 0, 0, 4});
boolean prepared = runWithBackendOwned(() -> {
spectrumInterceptor.preparation().prepare(parse.sql(), spectrumSession(), relationalBackend);
return true;
});
if (!prepared) {
throw new SpectrumReadException("58030", "Unable to prepare external query");
}
relationalStatements.put(parse.statementName(), parse);
} catch (RuntimeException exception) {
spectrumInterceptor.preparation().finishCycle(relationalBackend);
writeParseSpectrumError(exception);
return;
}
}
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) {
SpectrumInterceptor.Plan plan = spectrumInterceptor.plan(parse.sql(), spectrumSession());
if (plan instanceof SpectrumInterceptor.Plan.Ddl || plan instanceof SpectrumInterceptor.Plan.Query
|| plan instanceof SpectrumInterceptor.Plan.ExternalDdl) {
awaitPriorBackendResponses();
spectrumStatements.put(parse.statementName(), plan);
write(client.getOutputStream(), backendFrame('1', EMPTY_BODY));
return;
}
} catch (SpectrumSqlException | SpectrumReadException | IllegalArgumentException exception) {
} catch (RuntimeException exception) {
writeParseSpectrumError(exception);
return;
}
@@ -285,6 +331,24 @@ public class RedshiftInterceptingBridge {
private void handleBind(PostgresWireDecoder decoder, PostgresWireDecoder.FrontendMessage message,
OutputStream backendOut) throws IOException {
PostgresWireDecoder.BindMessage bind = decoder.decodeBind(message);
PostgresWireDecoder.ParseMessage relational = relationalStatements.get(bind.statementName());
if (relational != null && !coordinator.isDiscardingUntilSync()) {
try {
// Parse/Describe responses may be buffered until Flush or Sync; drain them before taking ownership.
write(backendOut, new byte[]{'H', 0, 0, 0, 4});
boolean prepared = runWithBackendOwned(() -> {
spectrumInterceptor.preparation().prepare(relational.sql(), spectrumSession(), relationalBackend);
return true;
});
if (!prepared) {
throw new SpectrumReadException("58030", "Unable to prepare external query");
}
} catch (RuntimeException exception) {
spectrumInterceptor.preparation().finishCycle(relationalBackend);
writeParseSpectrumError(exception);
return;
}
}
SpectrumInterceptor.Plan spectrumPlan = spectrumStatements.get(bind.statementName());
if (spectrumPlan != null) {
awaitPriorBackendResponses();
@@ -315,7 +379,7 @@ public class RedshiftInterceptingBridge {
}
byte[] response = spectrumDescribeResponse(spectrumPlan);
write(client.getOutputStream(), response);
} catch (SpectrumSqlException | SpectrumReadException | IllegalArgumentException exception) {
} catch (RuntimeException exception) {
writeParseSpectrumError(exception);
}
return;
@@ -425,7 +489,9 @@ public class RedshiftInterceptingBridge {
}
try {
backend.setSoTimeout(EXCHANGE_READ_TIMEOUT_MS);
ExtendedSpectrumExchange.execute(client, backend, plan, spectrumInterceptor, clusterAccountId, "dev",
SpectrumInterceptor.Plan executionPlan = plan instanceof SpectrumInterceptor.Plan.ExternalDdl ddl
? new SpectrumInterceptor.Plan.ExternalDdl(ddl.sql(), spectrumSession()) : plan;
ExtendedSpectrumExchange.execute(client, backend, executionPlan, spectrumInterceptor, clusterAccountId, databaseName,
coordinator, ticket, portalName, maxRows, spectrumCursors);
} finally {
try {
@@ -442,6 +508,7 @@ public class RedshiftInterceptingBridge {
PostgresWireDecoder.TargetMessage close = decoder.decodeClose(message);
boolean spectrumOwned;
if (close.targetType() == 'S') {
relationalStatements.remove(close.name());
SpectrumInterceptor.Plan closedPlan = spectrumStatements.remove(close.name());
spectrumOwned = closedPlan != null;
if (closedPlan != null) {
@@ -602,8 +669,14 @@ public class RedshiftInterceptingBridge {
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'});
reportLocalReady();
}
/** A query answered locally never reaches the backend, so its transaction state must be reported unchanged. */
private void reportLocalReady() throws IOException {
char status = coordinator.lastReadyStatus();
write(client.getOutputStream(), readyForQuery(status));
coordinator.onBackendFrame('Z', new byte[]{(byte) status});
}
private void writeParseSpectrumError(RuntimeException exception) throws IOException {
@@ -643,7 +716,11 @@ public class RedshiftInterceptingBridge {
if (exception instanceof SpectrumReadException spectrumReadException) {
return spectrumReadException.sqlState();
}
return "22023";
if (exception instanceof IllegalArgumentException) {
return "22023";
}
LOG.warnv(exception, "External query preparation failed unexpectedly");
return "58030";
}
/**
@@ -710,7 +787,38 @@ public class RedshiftInterceptingBridge {
}
private void pumpBackendToClient() {
WireFrameTracker tracker = new WireFrameTracker(coordinator::onBackendFrame);
WireFrameTracker tracker = new WireFrameTracker((type, body) -> {
// Publish or drop pending preparation state before the coordinator reports the backend idle,
// so the next preparation already sees a schema bound by a committed CREATE EXTERNAL SCHEMA.
if (spectrumInterceptor != null && spectrumInterceptor.preparation() != null) {
if (type == 'E') {
spectrumInterceptor.preparation().finishCycle(relationalBackend);
}
if (type == 'C' && "ROLLBACK\0".equals(new String(body, StandardCharsets.UTF_8))) {
// Loads are dropped on every rollback; bindings and Glue tables only once ReadyForQuery
// reports the transaction closed, because ROLLBACK TO SAVEPOINT keeps it open.
rolledBackInCycle = true;
spectrumInterceptor.preparation().discardPendingLoads(relationalBackend);
}
if (type == 'Z' && body.length > 0 && body[0] == 'I') {
if (rolledBackInCycle) {
spectrumInterceptor.preparation().finishCycle(relationalBackend);
} else {
spectrumInterceptor.preparation().finishCycle(relationalBackend, true);
}
}
if (type == 'Z') {
rolledBackInCycle = false;
}
}
if (type == 'E') {
relationalBackend.onBackendError();
}
coordinator.onBackendFrame(type, body);
if (type == 'Z') {
relationalBackend.onSync();
}
});
try {
InputStream backendIn = backend.getInputStream();
OutputStream clientOut = client.getOutputStream();
@@ -770,6 +878,7 @@ public class RedshiftInterceptingBridge {
private long declaredBodyLength = 0;
private char pendingType = 0;
private byte readyStatus;
private byte[] commandTag = EMPTY_BODY;
WireFrameTracker(FrameCompletion onFrame) {
this.onFrame = onFrame;
@@ -786,6 +895,9 @@ public class RedshiftInterceptingBridge {
if (pendingType == 'Z' && declaredBodyLength == 1) {
readyStatus = (byte) current;
}
if (pendingType == 'C' && commandTag.length > 0) {
commandTag[(int) (declaredBodyLength - bodyRemaining)] = (byte) current;
}
bodyRemaining--;
if (bodyRemaining == 0) {
publishCompletion();
@@ -799,6 +911,7 @@ public class RedshiftInterceptingBridge {
pendingType = (char) (header[0] & 0xFF);
bodyRemaining = Math.max(0, msgLen - 4);
declaredBodyLength = bodyRemaining;
commandTag = pendingType == 'C' && bodyRemaining <= 128 ? new byte[(int) bodyRemaining] : EMPTY_BODY;
headerBytesSeen = 0;
if (bodyRemaining == 0) {
publishCompletion();
@@ -809,7 +922,7 @@ public class RedshiftInterceptingBridge {
private void publishCompletion() {
byte[] body = pendingType == 'Z' && declaredBodyLength == 1
? new byte[]{readyStatus} : new byte[0];
? new byte[]{readyStatus} : pendingType == 'C' ? commandTag : EMPTY_BODY;
onFrame.accept(pendingType, body);
}
}
@@ -5,8 +5,8 @@ import io.github.hectorvent.floci.services.iam.IamService;
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.github.hectorvent.floci.services.s3.S3Service;
import io.quarkus.runtime.ShutdownEvent;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
@@ -76,6 +76,7 @@ public class RedshiftProxyManager {
// Make sure the self-signed proxy certificate covers the host clients will connect to,
// so sslmode=prefer/require handshakes succeed.
tlsCertificates.ensureHost(advertisedHost);
invalidateSpectrumRuntime(relayKey);
EmulatorConfig.RedshiftServiceConfig redshiftConfig = config.services().redshift();
String clusterAccountId = relayKey.substring(0, relayKey.indexOf(':'));
RedshiftAuthProxy proxy = new RedshiftAuthProxy(
@@ -138,6 +139,20 @@ public class RedshiftProxyManager {
proxies.remove(relayKey);
LOG.infov("Stopped Redshift proxy for cluster {0}", relayKey);
}
invalidateSpectrumRuntime(relayKey);
}
public void forgetSpectrumRuntime(String relayKey) {
if (spectrumInterceptor != null && spectrumInterceptor.preparation() != null) {
String accountId = relayKey.substring(0, relayKey.indexOf(':'));
spectrumInterceptor.preparation().forgetRuntime(accountId, relayKey);
}
}
private void invalidateSpectrumRuntime(String relayKey) {
if (spectrumInterceptor != null && spectrumInterceptor.preparation() != null) {
spectrumInterceptor.preparation().invalidateRuntime(relayKey);
}
}
public synchronized void stopAll() {
@@ -3,6 +3,10 @@ package io.github.hectorvent.floci.services.redshift.spectrum;
import java.io.InputStream;
public interface BackendSql {
default boolean permitsCachePublication() {
return true;
}
void execute(String sql);
long copyIn(String copySql, InputStream data);
}
@@ -68,6 +68,32 @@ public class ExternalTableMaterializer {
private final ConcurrentHashMap<String, String> schemaSignatures = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, ReentrantLock> locks = new ConcurrentHashMap<>();
private final Set<String> sweptAccounts = ConcurrentHashMap.newKeySet();
private final Map<BackendSql, Map<String, PendingLoad>> pendingLoads = new ConcurrentHashMap<>();
private final Map<String, PendingLoad> latestLoads = new ConcurrentHashMap<>();
private record PendingLoad(String fingerprint, String definitions) { }
public void finishCycle(BackendSql backend) {
pendingLoads.remove(backend);
}
public void finishCycle(BackendSql backend, boolean committed) {
Map<String, PendingLoad> completed = pendingLoads.remove(backend);
if (committed && completed != null) {
completed.forEach((key, loaded) -> {
ReentrantLock lock = locks.computeIfAbsent(key, ignored -> new ReentrantLock());
lock.lock();
try {
if (latestLoads.get(key) == loaded) {
fingerprints.put(key, loaded.fingerprint());
schemaSignatures.put(key, loaded.definitions());
}
} finally {
lock.unlock();
}
});
}
}
public ExternalTableMaterializer(FlociDuckClient duckClient, GlueService glueService, S3Service s3Service,
IamService iamService, EmulatorConfig config) {
@@ -107,6 +133,12 @@ public class ExternalTableMaterializer {
// An Iceberg snapshot can change through its metadata or manifests while the Glue table and the
// listed objects stay the same, so no fingerprint can vouch for it: it is read on every query.
boolean cacheable = !session.inTransaction() && !GlueTableResolver.isIcebergTable(table);
Map<String, PendingLoad> localLoads = backend.permitsCachePublication() ? Map.of()
: pendingLoads.computeIfAbsent(backend, ignored -> new ConcurrentHashMap<>());
PendingLoad local = localLoads.get(cacheKey);
if (!GlueTableResolver.isIcebergTable(table) && local != null && fingerprint.equals(local.fingerprint())) {
return Outcome.CURRENT;
}
if (cacheable && fingerprint.equals(fingerprints.get(cacheKey))) {
return Outcome.CURRENT;
}
@@ -116,9 +148,18 @@ public class ExternalTableMaterializer {
if (cacheable && fingerprint.equals(fingerprints.get(cacheKey))) {
return Outcome.CURRENT;
}
String previousSignature = schemaSignatures.get(cacheKey);
String previousSignature = local == null ? schemaSignatures.get(cacheKey) : local.definitions();
latestLoads.remove(cacheKey);
String definitions = load(backend, session, binding, table, sources, previousSignature);
if (session.inTransaction()) {
if (!backend.permitsCachePublication()) {
fingerprints.remove(cacheKey);
PendingLoad loaded = new PendingLoad(fingerprint, definitions);
localLoads.put(cacheKey, loaded);
latestLoads.put(cacheKey, loaded);
if (!definitions.equals(schemaSignatures.get(cacheKey))) {
schemaSignatures.remove(cacheKey);
}
} else if (session.inTransaction()) {
// Transactional DDL may roll back, so the rows cannot be trusted afterwards. The schema
// signature stays when this load kept the committed columns, so a view that depends on the
// table can still be refilled in place; a replaced table may roll back to the old columns.
@@ -182,6 +223,7 @@ public class ExternalTableMaterializer {
private void forgetMatching(Predicate<String> matches) {
fingerprints.keySet().removeIf(matches);
schemaSignatures.keySet().removeIf(matches);
latestLoads.keySet().removeIf(matches);
// Keep locks: removing a held lock lets another thread create a second lock for the same table.
}
@@ -0,0 +1,203 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
/** Runs preparation without ending the client's transaction or destroying its portals. */
public final class PostgresExtendedBackendSession implements BackendSql {
private final Socket backend;
private String name;
private volatile boolean failedUntilSync;
public PostgresExtendedBackendSession(Socket backend) {
this.backend = backend;
}
@Override
public boolean permitsCachePublication() {
return false;
}
/** The client's own pipelined statement failed; the backend discards everything until Sync. */
public void onBackendError() {
failedUntilSync = true;
}
public void onSync() {
failedUntilSync = false;
}
@Override
public void execute(String sql) {
try {
start(atomicCommand(sql));
closeAndFlush();
awaitClosed();
} catch (IOException exception) {
throw failure(exception);
}
}
public static String atomicCommand(String sql) {
if (!sql.startsWith("CREATE ") && !sql.startsWith("DROP ")) {
return sql;
}
String delimiter = "$floci_" + UUID.randomUUID().toString().replace("-", "") + "$";
return "DO " + delimiter + " BEGIN " + sql + "; END " + delimiter;
}
@Override
public long copyIn(String sql, InputStream data) {
try {
start(sql);
frame('H', new byte[0]);
backend.getOutputStream().flush();
readUntil('G');
byte[] chunk = new byte[8192];
try {
int count;
while ((count = data.read(chunk)) >= 0) {
if (count > 0) {
frame('d', chunk, count);
}
}
} catch (IOException exception) {
frame('f', "Unable to read external data\0".getBytes(StandardCharsets.UTF_8));
backend.getOutputStream().flush();
try {
readUntil('C');
} catch (SpectrumReadException expected) {
// COPY failure leaves recovery to the client's Sync.
exception.addSuppressed(expected);
}
throw exception;
}
frame('c', new byte[0]);
closeAndFlush();
String tag = awaitClosed();
return Long.parseLong(tag.substring(tag.lastIndexOf(' ') + 1).trim());
} catch (IOException exception) {
throw failure(exception);
}
}
private void start(String sql) throws IOException {
if (failedUntilSync) {
throw new SpectrumReadException("25P02", "Preparation is waiting for Sync after a backend error");
}
name = "floci_prepare_" + UUID.randomUUID().toString().replace("-", "");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
DataOutputStream body = new DataOutputStream(bytes);
cstring(body, name);
cstring(body, sql);
body.writeShort(0);
frame('P', bytes.toByteArray());
bytes.reset();
cstring(body, name);
cstring(body, name);
body.writeShort(0);
body.writeShort(0);
body.writeShort(0);
frame('B', bytes.toByteArray());
bytes.reset();
cstring(body, name);
body.writeInt(0);
frame('E', bytes.toByteArray());
}
private void closeAndFlush() throws IOException {
frame('C', ("P" + name + "\0").getBytes(StandardCharsets.UTF_8));
frame('C', ("S" + name + "\0").getBytes(StandardCharsets.UTF_8));
frame('H', new byte[0]);
backend.getOutputStream().flush();
}
private String awaitClosed() throws IOException {
String tag = "";
for (int closed = 0; closed < 2;) {
Response response = read();
if (response.type() == '3') {
closed++;
} else if (response.type() == 'C') {
tag = new String(response.body(), StandardCharsets.UTF_8).replace("\0", "");
}
}
return tag;
}
private void readUntil(char type) throws IOException {
Response response;
do {
// ParseComplete, BindComplete and asynchronous messages precede the response.
response = read();
if (response.type() == 'Z') {
throw new IOException("Backend ended preparation before sending " + type);
}
} while (response.type() != type);
}
private Response read() throws IOException {
DataInputStream input = new DataInputStream(backend.getInputStream());
char type = (char) input.readUnsignedByte();
int length = input.readInt();
if (length < 4 || length > 64 * 1024 * 1024) {
throw new IOException("Invalid preparation response length");
}
byte[] body = input.readNBytes(length - 4);
if (body.length != length - 4) {
throw new IOException("Backend closed during preparation");
}
if (type == 'E') {
failedUntilSync = true;
String state = "58030";
String message = "External query preparation failed";
for (int offset = 0; offset < body.length && body[offset] != 0;) {
char field = (char) body[offset++];
int start = offset;
while (offset < body.length && body[offset] != 0) {
offset++;
}
String value = new String(body, start, offset - start, StandardCharsets.UTF_8);
if (field == 'C') {
state = value;
} else if (field == 'M') {
message = value;
}
offset++;
}
throw new SpectrumReadException(state, message);
}
return new Response(type, body);
}
private void frame(char type, byte[] body) throws IOException {
frame(type, body, body.length);
}
/** Writes the frame in one call; a split write would put a header packet on the wire of its own. */
private void frame(char type, byte[] body, int length) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream(length + 5);
DataOutputStream output = new DataOutputStream(bytes);
output.writeByte(type);
output.writeInt(length + 4);
output.write(body, 0, length);
backend.getOutputStream().write(bytes.toByteArray());
}
private static void cstring(DataOutputStream output, String text) throws IOException {
output.write(text.getBytes(StandardCharsets.UTF_8));
output.writeByte(0);
}
private static SpectrumReadException failure(IOException exception) {
return new SpectrumReadException("58030", "Unable to prepare external query", exception);
}
private record Response(char type, byte[] body) { }
}
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.net.Socket;
import java.util.Optional;
@@ -14,16 +15,48 @@ public final class SpectrumInterceptor {
private final SpectrumQueryRewriter queryRewriter;
private final SpectrumS3Reader reader;
private final SpectrumMaterializer materializer;
private final SpectrumQueryPreparation preparation;
public SpectrumInterceptor(SpectrumCatalog catalog, SpectrumStatementParser statementParser,
SpectrumQueryClassifier queryClassifier, SpectrumQueryRewriter queryRewriter,
SpectrumS3Reader reader, SpectrumMaterializer materializer) {
this(catalog, statementParser, queryClassifier, queryRewriter, reader, materializer, null);
}
@Inject
public SpectrumInterceptor(SpectrumCatalog catalog, SpectrumStatementParser statementParser,
SpectrumQueryClassifier queryClassifier, SpectrumQueryRewriter queryRewriter,
SpectrumS3Reader reader, SpectrumMaterializer materializer,
SpectrumQueryPreparation preparation) {
this.catalog = catalog;
this.statementParser = statementParser;
this.queryClassifier = queryClassifier;
this.queryRewriter = queryRewriter;
this.reader = reader;
this.materializer = materializer;
this.preparation = preparation;
}
public SpectrumQueryPreparation preparation() {
return preparation;
}
public Plan plan(String sql, SpectrumSession session) {
if (preparation != null && preparation.handlesDdl(sql, session)) {
return new Plan.ExternalDdl(sql, session);
}
if (preparation != null && preparation.referencesExternal(sql, session)) {
return new Plan.Forward();
}
return plan(sql, session.accountId(), session.databaseName());
}
public Decision intercept(String sql, SpectrumSession session, Socket backend) {
Plan plan = plan(sql, session);
if (plan instanceof Plan.Forward && preparation != null) {
preparation.prepare(sql, session, new PostgresBackendSession(backend));
}
return execute(plan, session.accountId(), session.databaseName(), backend);
}
public Decision intercept(String sql, String accountId, String databaseName, Socket backend) {
@@ -54,6 +87,12 @@ public final class SpectrumInterceptor {
public Decision execute(Plan plan, String accountId, String databaseName, Socket backend) {
switch (plan) {
case Plan.ExternalDdl(String sql, SpectrumSession session) -> {
if (preparation.prepare(sql, session, new PostgresBackendSession(backend))) {
return new Decision.Handled();
}
return execute(plan(sql, accountId, databaseName), accountId, databaseName, backend);
}
case Plan.Ddl(SpectrumStatement parsed) -> {
switch (parsed) {
case SpectrumStatement.CreateSchema schema -> catalog.createSchema(new SpectrumExternalSchema(
@@ -91,7 +130,9 @@ public final class SpectrumInterceptor {
materializer.cleanup(backend, materialization);
}
public sealed interface Plan permits Plan.Ddl, Plan.Forward, Plan.Query {
public sealed interface Plan permits Plan.Ddl, Plan.Forward, Plan.Query, Plan.ExternalDdl {
record ExternalDdl(String sql, SpectrumSession session) implements Plan {
}
record Ddl(SpectrumStatement statement) implements Plan {
}
@@ -0,0 +1,195 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.glue.GlueService;
import io.github.hectorvent.floci.services.glue.model.Database;
import jakarta.enterprise.context.ApplicationScoped;
import org.jboss.logging.Logger;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
@ApplicationScoped
public class SpectrumQueryPreparation {
private static final Logger LOG = Logger.getLogger(SpectrumQueryPreparation.class);
private final ExternalCatalogRegistry registry;
private final ExternalTableMaterializer materializer;
private final ExternalStatementParser parser;
private final GlueService glue;
private final ExternalMetadataWriter metadata;
private final Map<BackendSql, List<ExternalSchemaBinding>> pendingBindings = new ConcurrentHashMap<>();
public SpectrumQueryPreparation(ExternalCatalogRegistry registry, ExternalTableMaterializer materializer,
ExternalStatementParser parser, GlueService glue, ExternalMetadataWriter metadata) {
this.registry = registry;
this.materializer = materializer;
this.parser = parser;
this.glue = glue;
this.metadata = metadata;
}
public boolean prepare(String sql, SpectrumSession session, BackendSql backend) {
try {
return RequestScopes.callAs(session.accountId(), () -> prepareInScope(sql, session, backend));
} catch (AwsException exception) {
String state = switch (exception.getErrorCode()) {
case "AlreadyExistsException" -> "42P07";
case "EntityNotFoundException" -> "42P01";
case "AccessDenied", "AccessDeniedException" -> "42501";
case "InvalidInputException" -> "42601";
default -> "58030";
};
throw new SpectrumSqlException(state, exception.getMessage());
}
}
public boolean referencesExternal(String sql, SpectrumSession session) {
Set<String> schemas = bindings(session).keySet();
return !ExternalReferenceScanner.scan(sql, schemas).isEmpty()
|| ExternalReferenceScanner.writeTarget(sql, schemas).isPresent();
}
public boolean handlesDdl(String sql, SpectrumSession session) {
Optional<ExternalStatement> statement = parser.parse(sql);
return statement.orElse(null) instanceof ExternalStatement.CreateSchema
|| statement.orElse(null) instanceof ExternalStatement.CreateTable table
&& (session.inTransaction() || bindings(session).containsKey(table.schemaName()));
}
private boolean prepareInScope(String sql, SpectrumSession session, BackendSql backend) {
Optional<ExternalStatement> statement = parser.parse(sql);
if (statement.orElse(null) instanceof ExternalStatement.CreateSchema schema) {
return createSchema(schema, session, backend);
}
Map<String, ExternalSchemaBinding> bindings = bindings(session);
if (statement.orElse(null) instanceof ExternalStatement.CreateTable && session.inTransaction()) {
// Legacy-catalog tables are saved immediately too, so a rollback would leave them behind.
throw new SpectrumSqlException("25001", "CREATE EXTERNAL TABLE cannot run inside a transaction block");
}
if (statement.orElse(null) instanceof ExternalStatement.CreateTable table && bindings.containsKey(table.schemaName())) {
ExternalSchemaBinding binding = bindings.get(table.schemaName());
glue.createTable(binding.glueDatabase(), GlueTableBuilder.toGlueTable(table));
metadata.refresh(backend, session.accountId(), binding);
return true;
}
Optional<ExternalReferenceScanner.Reference> write = ExternalReferenceScanner.writeTarget(sql, bindings.keySet());
if (write.isPresent()) {
throw new SpectrumSqlException("0A000", "Writes to external relation \""
+ write.get().schema() + "." + write.get().table() + "\" are not supported");
}
Set<String> refreshed = new HashSet<>();
for (ExternalReferenceScanner.Reference reference : ExternalReferenceScanner.scan(sql, bindings.keySet())) {
ExternalSchemaBinding binding = bindings.get(reference.schema());
ExternalTableMaterializer.Outcome outcome = materializer.ensureCurrent(backend, session, binding, reference.table());
if (outcome == ExternalTableMaterializer.Outcome.NOT_EXTERNAL) {
throw new SpectrumSqlException("42P01", "external relation \"" + reference.schema()
+ "." + reference.table() + "\" does not exist");
}
if (outcome == ExternalTableMaterializer.Outcome.LOADED && refreshed.add(binding.schemaName())) {
metadata.refresh(backend, session.accountId(), binding);
}
}
return false;
}
private boolean createSchema(ExternalStatement.CreateSchema schema, SpectrumSession session, BackendSql backend) {
if (session.inTransaction()) {
throw new SpectrumSqlException("0A000", "CREATE EXTERNAL SCHEMA inside a transaction is not supported");
}
Optional<ExternalSchemaBinding> existing = registry.find(session.accountId(), session.clusterKey(),
session.databaseName(), schema.schemaName());
if (existing.isPresent()) {
if (schema.ifNotExists()) {
return true;
}
throw new SpectrumSqlException("42P06", "schema \"" + schema.schemaName() + "\" already exists");
}
try {
glue.getDatabase(schema.glueDatabase());
} catch (AwsException exception) {
if (!"EntityNotFoundException".equals(exception.getErrorCode())) {
throw exception;
}
if (!schema.createDatabaseIfNotExists()) {
// Preserve the legacy catalog path for schemas without a Glue database.
return false;
}
Database database = new Database();
database.setName(schema.glueDatabase());
glue.createDatabase(database);
}
ExternalSchemaBinding binding = new ExternalSchemaBinding(session.accountId(), session.clusterKey(),
session.databaseName(), schema.schemaName(), schema.glueDatabase(), schema.iamRoleArn());
backend.execute("CREATE SCHEMA " + ExternalTableMaterializer.quote(schema.schemaName()));
try {
metadata.refresh(backend, session.accountId(), binding);
bindWhenCommitted(backend, binding);
} catch (RuntimeException exception) {
try {
backend.execute("DROP SCHEMA " + ExternalTableMaterializer.quote(schema.schemaName()) + " CASCADE");
} catch (RuntimeException cleanupFailure) {
LOG.warnv(cleanupFailure, "Could not clean up failed external schema {0}", schema.schemaName());
}
throw exception;
}
return true;
}
private Map<String, ExternalSchemaBinding> bindings(SpectrumSession session) {
Map<String, ExternalSchemaBinding> bindings = new LinkedHashMap<>();
for (ExternalSchemaBinding binding : registry.list(session.accountId(), session.clusterKey(), session.databaseName())) {
bindings.put(binding.schemaName(), binding);
}
return bindings;
}
public void forgetRuntime(String accountId, String clusterKey) {
registry.removeCluster(accountId, clusterKey);
materializer.forgetCluster(clusterKey);
}
public void invalidateRuntime(String clusterKey) {
materializer.forgetCluster(clusterKey);
}
/**
* A backend that shares the client's transaction can still roll the schema back, so the binding is held
* until {@link #finishCycle(BackendSql, boolean)} sees the commit. Any other backend has committed already.
*/
private void bindWhenCommitted(BackendSql backend, ExternalSchemaBinding binding) {
if (backend.permitsCachePublication()) {
registry.bind(binding);
return;
}
pendingBindings.computeIfAbsent(backend, ignored -> new CopyOnWriteArrayList<>()).add(binding);
}
/** The transaction rolled back: drop everything staged for it. */
public void finishCycle(BackendSql backend) {
pendingBindings.remove(backend);
materializer.finishCycle(backend);
}
public void finishCycle(BackendSql backend, boolean committed) {
List<ExternalSchemaBinding> completed = pendingBindings.remove(backend);
if (committed && completed != null) {
completed.forEach(registry::bind);
}
materializer.finishCycle(backend, committed);
}
/**
* A rollback to a savepoint leaves the transaction open, so only the loads are dropped: they may have been
* made after the savepoint, and their fingerprints would no longer match the backend tables.
*/
public void discardPendingLoads(BackendSql backend) {
materializer.finishCycle(backend);
}
}
@@ -0,0 +1,44 @@
package io.github.hectorvent.floci.services.redshiftdata;
import io.github.hectorvent.floci.services.redshift.spectrum.BackendSql;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumReadException;
import org.postgresql.PGConnection;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
final class RedshiftDataBackendSql implements BackendSql {
private final Connection connection;
RedshiftDataBackendSql(Connection connection) {
this.connection = connection;
}
@Override
public void execute(String sql) {
try (Statement statement = connection.createStatement()) {
statement.execute(sql);
} catch (SQLException exception) {
throw failure(exception);
}
}
@Override
public long copyIn(String copySql, InputStream data) {
try {
return connection.unwrap(PGConnection.class).getCopyAPI().copyIn(copySql, data);
} catch (SQLException exception) {
throw failure(exception);
} catch (IOException exception) {
throw new SpectrumReadException("58030", "Unable to stream external table data", exception);
}
}
private static SpectrumReadException failure(SQLException exception) {
String state = exception.getSQLState() == null ? "58030" : exception.getSQLState();
return new SpectrumReadException(state, exception.getMessage(), exception);
}
}
@@ -8,6 +8,8 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.redshift.RedshiftCredentialBroker;
import io.github.hectorvent.floci.services.redshift.RedshiftService;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumSession;
import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessRuntime;
import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessService;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;
@@ -65,17 +67,21 @@ class RedshiftDataResourceResolver {
}
RedshiftServerlessService.WorkgroupTarget workgroup =
serverlessService.getWorkgroupTarget(request.get("WorkgroupName").asText(), region);
String accountId = AwsArnUtils.parse(workgroup.arn()).accountId();
SpectrumSession spectrum = new SpectrumSession(accountId,
accountId + ":" + RedshiftServerlessRuntime.backendId(region, workgroup.workgroupName()), database,
workgroup.iamRoleArns(), false);
if (!database.equals(workgroup.database())) {
throw validation("Database " + database + " does not exist in workgroup " + workgroup.workgroupName()
+ "; the only database is " + workgroup.database() + ".");
}
if (!hasText(request, "SecretArn")) {
return new DatabaseTarget(workgroup.arn(), workgroup.host(), workgroup.port(), database,
workgroup.masterUsername(), workgroup.masterPassword());
workgroup.masterUsername(), workgroup.masterPassword(), spectrum);
}
Credentials creds = secretCredentials(request.get("SecretArn").asText(), region);
return new DatabaseTarget(workgroup.arn(), workgroup.host(), workgroup.port(), database,
creds.username(), creds.password());
creds.username(), creds.password(), spectrum);
}
private Credentials secretCredentials(String secretArn, String region) {
@@ -146,7 +152,10 @@ class RedshiftDataResourceResolver {
if (host == null || host.isBlank() || port <= 0) {
throw validation("Cluster runtime is not available for Data API execution.");
}
return new DatabaseTarget(arn, host, port, database, user, password);
String accountId = AwsArnUtils.parse(arn).accountId();
SpectrumSession spectrum = new SpectrumSession(accountId, accountId + ":" + cluster.getClusterIdentifier(),
database, cluster.getIamRoleArns(), false);
return new DatabaseTarget(arn, host, port, database, user, password, spectrum);
}
private Credentials parseCredentials(String secretString) {
@@ -196,7 +205,11 @@ class RedshiftDataResourceResolver {
return value == null || value.isNull() ? null : value.asText();
}
record DatabaseTarget(String arn, String host, int port, String database, String user, String password) {
record DatabaseTarget(String arn, String host, int port, String database, String user, String password,
SpectrumSession spectrum) {
DatabaseTarget(String arn, String host, int port, String database, String user, String password) {
this(arn, host, port, database, user, password, null);
}
}
private record Credentials(String username, String password) {
@@ -7,6 +7,11 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.common.SqlParameterParser.ParsedSql;
import io.github.hectorvent.floci.services.redshift.spectrum.BackendSql;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumQueryPreparation;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumReadException;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumSession;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumSqlException;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -33,16 +38,25 @@ public class RedshiftDataService implements Resettable {
private final RedshiftDataConnectionFactory connectionFactory;
private final RedshiftDataStatementStore store;
private final ObjectMapper objectMapper;
private final SpectrumQueryPreparation preparation;
@Inject
public RedshiftDataService(RedshiftDataResourceResolver resolver,
RedshiftDataConnectionFactory connectionFactory,
RedshiftDataStatementStore store,
ObjectMapper objectMapper) {
this(resolver, connectionFactory, store, objectMapper, null);
}
@Inject
public RedshiftDataService(RedshiftDataResourceResolver resolver,
RedshiftDataConnectionFactory connectionFactory,
RedshiftDataStatementStore store, ObjectMapper objectMapper,
SpectrumQueryPreparation preparation) {
this.resolver = resolver;
this.connectionFactory = connectionFactory;
this.store = store;
this.objectMapper = objectMapper;
this.preparation = preparation;
}
@Override
@@ -77,7 +91,7 @@ public class RedshiftDataService implements Resettable {
RedshiftDataResourceResolver.DatabaseTarget target,
String sql, Map<String, String> parameters) {
try (Connection connection = connectionFactory.open(target)) {
runOnConnection(stored, connection, sql, parameters);
runOnConnection(stored, connection, sql, parameters, target.spectrum());
} catch (SQLException e) {
stored.status = RedshiftDataStatementStore.Status.FAILED;
stored.error = e.getMessage();
@@ -104,8 +118,25 @@ public class RedshiftDataService implements Resettable {
}
private void runOnConnection(RedshiftDataStatementStore.StoredStatement stored,
Connection connection, String sql, Map<String, String> parameters)
Connection connection, String sql, Map<String, String> parameters, SpectrumSession context)
throws SQLException {
if (preparation != null && context != null) {
SpectrumSession session = new SpectrumSession(context.accountId(), context.clusterKey(), context.databaseName(),
context.iamRoleArns(), !connection.getAutoCommit());
try {
if (preparation.prepare(sql, session, new RedshiftDataBackendSql(connection))) {
stored.status = RedshiftDataStatementStore.Status.FINISHED;
return;
}
} catch (SpectrumSqlException exception) {
throw new SQLException(exception.getMessage(), exception.sqlState(), exception);
} catch (SpectrumReadException exception) {
throw new SQLException(exception.getMessage(), exception.sqlState(), exception);
} catch (RuntimeException exception) {
// Anything else from Glue or the read path must fail the statement, not leave it running.
throw new SQLException("External query preparation failed: " + exception.getMessage(), "58030", exception);
}
}
ParsedSql parsed = RedshiftDataSqlParameters.parse(sql);
long t0 = System.nanoTime();
try (PreparedStatement statement = connection.prepareStatement(parsed.sql())) {
@@ -309,44 +340,57 @@ public class RedshiftDataService implements Resettable {
long totalDuration = 0;
try (Connection connection = connectionFactory.open(target)) {
connection.setAutoCommit(false);
boolean failed = false;
for (int n = 0; n < sqls.size(); n++) {
RedshiftDataStatementStore.StoredStatement sub = new RedshiftDataStatementStore.StoredStatement();
sub.id = parent.id + ":" + (n + 1);
sub.sql = sqls.get(n);
sub.sqls = List.of(sqls.get(n));
sub.clusterIdentifier = parent.clusterIdentifier;
sub.workgroupName = parent.workgroupName;
sub.database = parent.database;
sub.dbUser = parent.dbUser;
sub.resultFormat = parent.resultFormat;
Instant now = Instant.now();
sub.createdAt = now;
sub.updatedAt = now;
try {
runOnConnection(sub, connection, sqls.get(n), Map.of());
} catch (SQLException e) {
sub.status = RedshiftDataStatementStore.Status.FAILED;
sub.error = e.getMessage();
BackendSql batchBackend = new RedshiftDataBackendSql(connection);
boolean committed = false;
try {
connection.setAutoCommit(false);
boolean failed = false;
for (int n = 0; n < sqls.size(); n++) {
RedshiftDataStatementStore.StoredStatement sub = new RedshiftDataStatementStore.StoredStatement();
sub.id = parent.id + ":" + (n + 1);
sub.sql = sqls.get(n);
sub.sqls = List.of(sqls.get(n));
sub.clusterIdentifier = parent.clusterIdentifier;
sub.workgroupName = parent.workgroupName;
sub.database = parent.database;
sub.dbUser = parent.dbUser;
sub.resultFormat = parent.resultFormat;
Instant now = Instant.now();
sub.createdAt = now;
sub.updatedAt = now;
try {
runOnConnection(sub, connection, sqls.get(n), Map.of(), target.spectrum());
} catch (SQLException e) {
sub.status = RedshiftDataStatementStore.Status.FAILED;
sub.error = e.getMessage();
sub.updatedAt = Instant.now();
parent.subStatements.add(sub);
store.put(sub);
totalDuration += sub.durationNanos;
parent.status = RedshiftDataStatementStore.Status.FAILED;
parent.error = e.getMessage();
connection.rollback();
failed = true;
break;
}
sub.updatedAt = Instant.now();
parent.subStatements.add(sub);
store.put(sub);
totalDuration += sub.durationNanos;
parent.status = RedshiftDataStatementStore.Status.FAILED;
parent.error = e.getMessage();
connection.rollback();
failed = true;
break;
}
sub.updatedAt = Instant.now();
parent.subStatements.add(sub);
store.put(sub);
totalDuration += sub.durationNanos;
}
if (!failed) {
connection.commit();
parent.status = RedshiftDataStatementStore.Status.FINISHED;
if (!failed) {
connection.commit();
committed = true;
parent.status = RedshiftDataStatementStore.Status.FINISHED;
}
} finally {
if (preparation != null) {
if (committed) {
preparation.finishCycle(batchBackend, true);
} else {
preparation.finishCycle(batchBackend);
}
}
}
} catch (SQLException e) {
parent.status = RedshiftDataStatementStore.Status.FAILED;
@@ -89,6 +89,7 @@ public class RedshiftServerlessRuntime {
String backendId = backendId(region, workgroupName);
proxyManager.stopProxy(relayKey(accountId, backendId));
containerManager.stop(accountId, backendId);
proxyManager.forgetSpectrumRuntime(relayKey(accountId, backendId));
credentialBroker.revokeCluster(accountId, backendId);
}
@@ -562,12 +562,20 @@ public class RedshiftServerlessService implements Resettable {
}
return new WorkgroupTarget(workgroup.getWorkgroupArn(), workgroup.getWorkgroupName(),
workgroup.getRuntimeHost(), workgroup.getRuntimePort(), namespace.getDbName(),
workgroup.getMasterUsername(), namespace.getAdminUserPassword(), adminUserOf(namespace));
workgroup.getMasterUsername(), namespace.getAdminUserPassword(), adminUserOf(namespace), namespace.getIamRoles());
}
/** Connection details of a workgroup's backend; {@code adminUsername} is the name clients log in with. */
public record WorkgroupTarget(String arn, String workgroupName, String host, int port, String database,
String masterUsername, String masterPassword, String adminUsername) {
String masterUsername, String masterPassword, String adminUsername, List<String> iamRoleArns) {
public WorkgroupTarget(String arn, String workgroupName, String host, int port, String database,
String masterUsername, String masterPassword, String adminUsername) {
this(arn, workgroupName, host, port, database, masterUsername, masterPassword, adminUsername, List.of());
}
public WorkgroupTarget {
iamRoleArns = iamRoleArns == null ? List.of() : List.copyOf(iamRoleArns);
}
}
private Workgroup resolveWorkgroup(String nameOrArn, String region) {