feat(redshift): evaluate scalar Lambda UDFs over PostgreSQL wire and Data API (#9336)

Scalar Lambda UDFs created with CREATE EXTERNAL FUNCTION now evaluate in SQL over the PostgreSQL wire protocol, Simple and Extended Query, and through the Data API. LambdaUdfEvaluator collects each statement's calls in rolled-back passes through generated stubs, invokes the functions in batches through LambdaUdfInvoker, and serves the results from a per-statement cache. In autocommit the collect passes and the statement share one transaction, so now() and the other transaction-time arguments stay the same, and volatile arguments such as random() or statement_timestamp() are refused.

PostgresWire.dataRowValues is now the one DataRow decoder for the Spectrum backend session and the S3 COPY simulator.

Closes #7815
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-24 14:59:14 -04:00
1 parent d42f29579c
commit a3a6cef531
19 files changed
+2063 -96

No files matched your search

@@ -6,7 +6,9 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
@@ -180,6 +182,39 @@ public final class PostgresWire {
return bytes;
}
// ── Rows ──────────────────────────────────────────────────────────────────
/**
* The text-format values of a DataRow body in column order, with {@code null} for SQL NULL.
*
* @throws IllegalArgumentException when a value runs past the end of the body
*/
public static List<String> dataRowValues(byte[] body) {
if (body == null || body.length < 2) {
return List.of();
}
int count = ((body[0] & 0xFF) << 8) | (body[1] & 0xFF);
List<String> values = new ArrayList<>(count);
int offset = 2;
for (int i = 0; i < count; i++) {
if (offset + 4 > body.length) {
throw new IllegalArgumentException("DataRow ends before column " + (i + 1) + " of " + count);
}
int length = int32(body, offset);
offset += 4;
if (length < 0) {
values.add(null);
continue;
}
if (offset + length > body.length) {
throw new IllegalArgumentException("DataRow ends inside column " + (i + 1) + " of " + count);
}
values.add(new String(body, offset, length, StandardCharsets.UTF_8));
offset += length;
}
return values;
}
// ── Startup ───────────────────────────────────────────────────────────────
/** The {@code name=value} pairs of a StartupMessage body, in the order the client sent them. */
@@ -141,7 +141,7 @@ final class CopyBackendSession {
while (true) {
PostgresWireDecoder.FrontendMessage response = read();
if (response.type() == 'D') {
rows.add(S3CopySimulator.parseDataRow(response.body()));
rows.add(PostgresWire.dataRowValues(response.body()));
} else if (response.type() == 'C' || response.type() == 'I') {
close(name);
return rows;
@@ -1,6 +1,7 @@
package io.floci.aws.services.redshift.proxy;
import io.floci.aws.core.common.PostgresWire;
import io.floci.aws.services.redshift.spectrum.BackendSql;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
@@ -151,6 +152,36 @@ public class PostgresWireDecoder {
return new BindMessage(cursor.readCString(), cursor.readCString());
}
/**
* Extracts the raw parameter format codes and parameter value bytes from a Bind ({@code 'B'}) message so binary
* bind parameters can be replayed without lossy text decoding. Returns {@code null} if the section is malformed.
*/
public BackendSql.RawParameters extractBindParameters(FrontendMessage message, List<Integer> parameterTypeOids)
throws IOException {
BodyCursor cursor = cursorFor(message, 'B');
cursor.readCString();
cursor.readCString();
int start = cursor.offset;
try {
int formatCount = cursor.readInt16();
cursor.skip(formatCount * 2);
int parameterCount = cursor.readInt16();
if (formatCount > 1 && formatCount != parameterCount) {
return null;
}
for (int i = 0; i < parameterCount; i++) {
int length = cursor.readInt32();
if (length > 0) {
cursor.skip(length);
}
}
byte[] section = Arrays.copyOfRange(message.body(), start, cursor.offset);
return new BackendSql.RawParameters(parameterTypeOids, parameterCount, section);
} catch (IOException expected) {
return null;
}
}
/**
* Values of a Bind's parameters without known type OIDs. Binary values and NULL remain unknown.
* Only a statement that prunes needs them, so they are read apart from
@@ -7,6 +7,8 @@ import io.floci.aws.services.redshift.RedshiftAuditSql;
import io.floci.aws.services.redshift.RedshiftAuditSql.UserChange;
import io.floci.aws.services.redshift.RedshiftAuditSql.UserChanges;
import io.floci.aws.services.redshift.proxy.S3CopySimulator.S3TransferException;
import io.floci.aws.services.redshift.spectrum.BackendSql;
import io.floci.aws.services.redshift.spectrum.PostgresBackendSession;
import io.floci.aws.services.redshift.spectrum.PostgresExtendedBackendSession;
import io.floci.aws.services.redshift.spectrum.SpectrumColumn;
import io.floci.aws.services.redshift.spectrum.SpectrumInterceptor;
@@ -80,6 +82,7 @@ public class RedshiftInterceptingBridge {
private final UserChanges auditUserChanges = new UserChanges();
private final PostgresExtendedBackendSession relationalBackend;
private final Map<String, RelationalStatement> relationalStatements = new HashMap<>();
private final Map<String, BoundPortal> relationalPortals = 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<>();
@@ -101,6 +104,7 @@ public class RedshiftInterceptingBridge {
private boolean extendedSpectrumError;
private boolean rolledBackInCycle;
private boolean auditCycleFailed;
private boolean udfStateDirty;
public RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService) {
this(client, backend, s3Service, iamService, null);
@@ -292,6 +296,27 @@ public class RedshiftInterceptingBridge {
String sql = message.getSql();
publishActivity(sql);
if (spectrumInterceptor != null) {
boolean usesUdf = spectrumInterceptor.preparation() != null
&& spectrumInterceptor.preparation().referencesExternalFunction(sql, spectrumSession());
if (udfStateDirty && !usesUdf && spectrumInterceptor.preparation() != null
&& coordinator.lastReadyStatus() != 'E') {
try {
boolean cleared = runWithBackendOwned(() -> {
spectrumInterceptor.preparation().resetUdfState(new PostgresBackendSession(backend));
return true;
});
if (cleared) {
udfStateDirty = false;
}
} catch (RuntimeException exception) {
LOG.debugv(exception, "Could not reset external function state before Simple Query");
}
}
if (usesUdf && coordinator.lastReadyStatus() == 'I' && parseS3Statement(sql) == null
&& runExternalFunctionStatementInOneTransaction(sql)) {
udfStateDirty = true;
return;
}
SpectrumInterceptor.Decision[] decision = new SpectrumInterceptor.Decision[1];
boolean intercepted;
try {
@@ -303,6 +328,9 @@ public class RedshiftInterceptingBridge {
writeSimpleSpectrumError(exception);
return;
}
if (intercepted && usesUdf) {
udfStateDirty = true;
}
if (!intercepted && spectrumInterceptor.preparation() != null
&& spectrumInterceptor.preparation().referencesExternal(sql, spectrumSession())) {
writeSimpleSpectrumError(new SpectrumReadException("58030", "Unable to prepare external query"));
@@ -447,20 +475,35 @@ public class RedshiftInterceptingBridge {
private void handleBind(PostgresWireDecoder decoder, PostgresWireDecoder.FrontendMessage message,
OutputStream backendOut) throws IOException {
PostgresWireDecoder.BindMessage bind = decoder.decodeBind(message);
relationalPortals.remove(bind.portalName());
RelationalStatement 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});
BoundPortal[] bound = new BoundPortal[1];
boolean prepared = runWithBackendOwned(() -> {
List<String> parameterValues = decoder.decodeBindParameters(message, relational.parameterTypeOids);
spectrumInterceptor.preparation().prepare(relational.parse.sql(), spectrumSession(), relationalBackend,
parameterValues);
SpectrumSession currentSession = spectrumSession();
if (spectrumInterceptor.preparation().referencesExternalFunction(
relational.parse.sql(), currentSession)) {
BackendSql.RawParameters rawParameters = decoder.extractBindParameters(
message, relational.parameterTypeOids);
spectrumInterceptor.preparation().prepareTables(
relational.parse.sql(), currentSession, relationalBackend, parameterValues);
bound[0] = new BoundPortal(relational, parameterValues, rawParameters);
} else {
spectrumInterceptor.preparation().prepare(
relational.parse.sql(), currentSession, relationalBackend, parameterValues);
}
return true;
});
if (!prepared) {
throw new SpectrumReadException("58030", "Unable to prepare external query");
}
if (bound[0] != null) {
relationalPortals.put(bind.portalName(), bound[0]);
}
} catch (RuntimeException exception) {
spectrumInterceptor.preparation().finishCycle(relationalBackend);
writeParseSpectrumError(exception);
@@ -571,6 +614,42 @@ public class RedshiftInterceptingBridge {
runExtendedSpectrumWithBackendOwned(spectrumPlan, execute.portalName(), execute.maxRows(), ticket);
return;
}
BoundPortal boundPortal = relationalPortals.get(execute.portalName());
if (boundPortal != null && !boundPortal.prepared && !coordinator.isDiscardingUntilSync()) {
try {
write(backendOut, new byte[]{'H', 0, 0, 0, 4});
boolean prepared = runWithBackendOwned(() -> {
spectrumInterceptor.preparation().prepareExternalFunctions(
boundPortal.statement.parse.sql(), spectrumSession(), relationalBackend,
boundPortal.parameterValues, boundPortal.rawParameters);
return true;
});
if (!prepared) {
throw new SpectrumReadException("58030", "Unable to prepare external function call");
}
boundPortal.prepared = true;
udfStateDirty = true;
} catch (RuntimeException exception) {
spectrumInterceptor.preparation().finishCycle(relationalBackend);
writeParseSpectrumError(exception);
return;
}
} else if (boundPortal == null && udfStateDirty && spectrumInterceptor != null
&& spectrumInterceptor.preparation() != null && !coordinator.isDiscardingUntilSync()
&& coordinator.lastReadyStatus() != 'E') {
try {
write(backendOut, new byte[]{'H', 0, 0, 0, 4});
boolean cleared = runWithBackendOwned(() -> {
spectrumInterceptor.preparation().resetUdfState(relationalBackend);
return true;
});
if (cleared) {
udfStateDirty = false;
}
} catch (RuntimeException exception) {
LOG.debugv(exception, "Could not reset external function state before Execute");
}
}
BackendResponseCoordinator.Ticket ticket = coordinator.register(
BackendResponseCoordinator.Operation.EXECUTE, null,
auditSql == null ? null : auditResponses(auditSql));
@@ -642,13 +721,17 @@ public class RedshiftInterceptingBridge {
PostgresWireDecoder.TargetMessage close = decoder.decodeClose(message);
boolean spectrumOwned;
if (close.targetType() == 'S') {
relationalStatements.remove(close.name());
RelationalStatement closedRelational = relationalStatements.remove(close.name());
if (closedRelational != null) {
relationalPortals.values().removeIf(portal -> portal.statement == closedRelational);
}
SpectrumInterceptor.Plan closedPlan = spectrumStatements.remove(close.name());
spectrumOwned = closedPlan != null;
if (closedPlan != null) {
abandonStatementPortals(closedPlan);
}
} else {
relationalPortals.remove(close.name());
spectrumOwned = spectrumPortals.remove(close.name()) != null;
ExtendedSpectrumExchange.PortalCursor cursor = spectrumCursors.remove(close.name());
if (cursor != null) {
@@ -866,6 +949,109 @@ public class RedshiftInterceptingBridge {
out.write(0);
}
/**
* Runs an autocommit Simple Query statement that calls an external function inside one transaction together
* with its collect passes, so {@code now()} and the other transaction-time values the calls are keyed on stay
* the same from the first pass to the statement itself. The bridge owns the backend for the whole exchange,
* relays the statement's response, and reports the transaction closed once it has committed or rolled back.
*
* @return {@code false} when the statement is not a plain forwarded one or the backend could not be owned, so
* the caller handles it the usual way
*/
private boolean runExternalFunctionStatementInOneTransaction(String sql) throws IOException {
return runWithBackendOwned(() -> {
PostgresBackendSession backendSql = new PostgresBackendSession(backend);
SpectrumSession autocommit = spectrumSession();
try {
if (!(spectrumInterceptor.plan(sql, autocommit, backendSql) instanceof SpectrumInterceptor.Plan.Forward)) {
return false;
}
spectrumInterceptor.preparation().prepareTables(sql, autocommit, backendSql, List.of());
backendSql.execute("BEGIN");
} catch (RuntimeException exception) {
writeSimpleSpectrumError(exception);
return true;
}
try {
spectrumInterceptor.preparation().prepareExternalFunctions(sql, new SpectrumSession(clusterAccountId,
clusterKey, databaseName, iamRoleArns, true), backendSql, List.of(), null);
} catch (RuntimeException exception) {
endOwnedTransaction(backendSql, true);
writeSimpleSpectrumError(exception);
return true;
}
String statement = sql;
try {
statement = rewriteSql(sql);
} catch (RuntimeException e) {
LOG.warnv("RedshiftSqlInterceptor failed, forwarding original query: {0}", e.getMessage());
}
write(backend.getOutputStream(), PostgresWireDecoder.encodeQuery(statement));
boolean failed = relayUntilReady(auditResponses(sql));
RuntimeException commitFailure = endOwnedTransaction(backendSql, failed);
if (commitFailure != null) {
write(client.getOutputStream(),
errorResponse(spectrumSqlState(commitFailure), commitFailure.getMessage()));
}
byte[] idle = new byte[]{'I'};
write(client.getOutputStream(), readyForQuery('I'));
coordinator.onBackendFrame('Z', idle);
completeUserChanges(idle);
return true;
});
}
/**
* Relays the backend's response to one Simple Query to the client, holding back its ReadyForQuery because the
* transaction the bridge opened around it is still to be ended.
*
* @return whether the statement failed
*/
private boolean relayUntilReady(BiConsumer<Character, byte[]> audit) throws IOException {
PostgresWireDecoder decoder = new PostgresWireDecoder(backend.getInputStream());
OutputStream out = client.getOutputStream();
boolean failed = false;
PostgresWireDecoder.FrontendMessage message = decoder.nextMessage();
while (message != null) {
if (message.type() == 'Z') {
out.flush();
return failed;
}
if (message.type() == 'E') {
failed = true;
}
audit.accept(message.type(), message.body());
out.write(message.toPacketBytes());
message = decoder.nextMessage();
}
throw new IOException("PostgreSQL closed before ReadyForQuery");
}
/**
* Commits, or rolls back after a failure, the transaction the bridge opened around a statement, and publishes
* or drops the external table state it staged.
*
* @return the failure of a COMMIT, which the client has not been told about yet; null otherwise
*/
private RuntimeException endOwnedTransaction(PostgresBackendSession backendSql, boolean failed) {
RuntimeException commitFailure = null;
try {
backendSql.execute(failed ? "ROLLBACK" : "COMMIT");
} catch (RuntimeException exception) {
if (failed) {
LOG.warnv(exception, "Could not roll back the transaction around an external function statement");
} else {
commitFailure = exception;
}
}
if (failed || commitFailure != null) {
spectrumInterceptor.preparation().finishCycle(relationalBackend);
} else {
spectrumInterceptor.preparation().finishCycle(relationalBackend, true);
}
return commitFailure;
}
private void writeSimpleSpectrumError(RuntimeException exception) throws IOException {
coordinator.register(BackendResponseCoordinator.Operation.SIMPLE_QUERY, null);
write(client.getOutputStream(), errorResponse(spectrumSqlState(exception), exception.getMessage()));
@@ -881,6 +1067,7 @@ public class RedshiftInterceptingBridge {
private void writeParseSpectrumError(RuntimeException exception) throws IOException {
session.clear();
relationalPortals.clear();
extendedSpectrumError = true;
awaitPriorBackendResponses();
write(client.getOutputStream(), errorResponse(spectrumSqlState(exception), exception.getMessage()));
@@ -1136,6 +1323,20 @@ public class RedshiftInterceptingBridge {
}
}
private static final class BoundPortal {
private final RelationalStatement statement;
private final List<String> parameterValues;
private final BackendSql.RawParameters rawParameters;
private boolean prepared;
private BoundPortal(RelationalStatement statement, List<String> parameterValues,
BackendSql.RawParameters rawParameters) {
this.statement = statement;
this.parameterValues = parameterValues;
this.rawParameters = rawParameters;
}
}
/** Tracks frames while retaining bounded command tags, parameter types and ReadyForQuery status. */
static final class WireFrameTracker {
private static final int MAX_PARAMETER_DESCRIPTION_BYTES = 2 + 4 * 0xFFFF;
@@ -784,24 +784,6 @@ public final class S3CopySimulator {
return CopyRecordTransformer.ColumnKind.OTHER;
}
static List<String> parseDataRow(byte[] body) {
int count = ((body[0] & 0xFF) << 8) | (body[1] & 0xFF);
List<String> values = new ArrayList<>(count);
int offset = 2;
for (int i = 0; i < count; i++) {
int length = ((body[offset] & 0xFF) << 24) | ((body[offset + 1] & 0xFF) << 16)
| ((body[offset + 2] & 0xFF) << 8) | (body[offset + 3] & 0xFF);
offset += 4;
if (length < 0) {
values.add(null);
continue;
}
values.add(new String(body, offset, length, StandardCharsets.UTF_8));
offset += length;
}
return values;
}
static String columnInfoQuery(CopyStatementParser.S3CopyFrom spec) {
// 1042 = bpchar, 1043 = varchar; atttypmod carries the declared length plus a 4-byte header.
return "SELECT a.attname, CASE WHEN a.atttypid IN (1042, 1043) AND a.atttypmod > 4 "
@@ -836,7 +818,7 @@ public final class S3CopySimulator {
while ((msg = backendDecoder.nextMessage()) != null) {
char type = msg.type();
if (type == 'D') {
List<String> values = parseDataRow(msg.body());
List<String> values = PostgresWire.dataRowValues(msg.body());
if (!values.isEmpty() && values.get(0) != null) {
cols.add(columnInfo(values));
}
@@ -1,6 +1,7 @@
package io.floci.aws.services.redshift.spectrum;
import java.io.InputStream;
import java.util.List;
import java.util.Optional;
public interface BackendSql {
@@ -8,6 +9,43 @@ public interface BackendSql {
return true;
}
/**
* Whether this backend runs inside an Extended Query pipeline where {@code SAVEPOINT} is rejected outside an
* explicit transaction block and collect passes must run inside a PL/pgSQL subtransaction.
*/
default boolean usesSubtransactionCollect() {
return false;
}
/**
* Resolves the PostgreSQL parameter type OIDs for {@code sql}, using any client-supplied {@code declaredTypeOids}.
*/
default List<Integer> resolveParameterTypeOids(String sql, List<Integer> declaredTypeOids, int parameterCount) {
return declaredTypeOids == null ? List.of() : declaredTypeOids;
}
/**
* Runs a query that returns a single text value, binding raw PostgreSQL wire parameters when provided.
*/
default Optional<String> queryString(String sql, RawParameters parameters) {
return queryString(sql);
}
/**
* Raw PostgreSQL Bind parameter section and type OIDs, preserving binary-format values verbatim.
*/
record RawParameters(List<Integer> typeOids, int count, byte[] bindSection) {
public RawParameters {
typeOids = typeOids == null ? List.of() : List.copyOf(typeOids);
bindSection = bindSection == null ? new byte[0] : bindSection.clone();
}
@Override
public byte[] bindSection() {
return bindSection.clone();
}
}
/**
* Identifies the client connection whose transaction this backend runs in, so state staged for that
* transaction can be published or dropped when it ends. Null when the end of the transaction is not reported.
@@ -24,6 +62,21 @@ public interface BackendSql {
return Optional.empty();
}
/**
* Runs a query and returns every row as text values in column order, with {@code null} for SQL NULL.
*/
default List<List<String>> queryRows(String sql) {
return List.of();
}
void execute(String sql);
/**
* Runs a statement with positional text parameters ({@code null} for SQL NULL), or plainly when empty.
*/
default void execute(String sql, List<String> parameters) {
execute(sql);
}
long copyIn(String copySql, InputStream data);
}
@@ -0,0 +1,621 @@
package io.floci.aws.services.redshift.spectrum;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.PostgresWire;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* Evaluates scalar Lambda UDF calls for a statement by running collect passes against plpgsql stubs in PostgreSQL,
* batch-invoking Lambda through {@link LambdaUdfInvoker}, caching results in a per-session temp table, and then
* switching the stubs into execute mode for the real statement.
*/
@ApplicationScoped
public class LambdaUdfEvaluator {
static final int MAX_ROUNDS = 16;
private static final int CACHE_INSERT_BATCH_SIZE = 200;
private static final String DEFAULT_USER = "admin";
private static final ObjectMapper JSON = new ObjectMapper();
private static final Set<String> DISALLOWED_LEADING_KEYWORDS = Set.of(
"begin", "start", "commit", "end", "rollback", "abort", "savepoint", "release", "prepare", "do", "call");
private static final Set<String> VOLATILE_ARGUMENT_FUNCTIONS = Set.of(
"nextval", "setval", "random", "clock_timestamp", "statement_timestamp", "timeofday",
"gen_random_uuid", "uuid_generate_v4", "txid_current", "pg_current_xact_id");
static final String CURRENT_USER_SQL = "SELECT current_user";
static final String CREATE_PENDING_TABLE_SQL = "CREATE TEMP TABLE IF NOT EXISTS pg_temp._floci_udf_pending ("
+ "fn_key text NOT NULL, args_json text NOT NULL, PRIMARY KEY (fn_key, args_json))";
static final String CREATE_CACHE_TABLE_SQL = "CREATE TEMP TABLE IF NOT EXISTS pg_temp._floci_udf_cache ("
+ "fn_key text NOT NULL, args_json text NOT NULL, result_text text, PRIMARY KEY (fn_key, args_json))";
static final String CREATE_CACHE_GUARD_FN_SQL = "CREATE OR REPLACE FUNCTION pg_temp._floci_udf_cache_guard() "
+ "RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN "
+ "RAISE EXCEPTION 'External function cache is read-only' USING ERRCODE = '42501'; END $$";
static final String CREATE_CACHE_GUARD_TRIGGER_SQL = "DO $$ BEGIN "
+ "IF NOT EXISTS (SELECT 1 FROM pg_catalog.pg_trigger t "
+ "JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid "
+ "WHERE c.oid = 'pg_temp._floci_udf_cache'::regclass AND t.tgname = '_floci_udf_cache_readonly') THEN "
+ "CREATE TRIGGER _floci_udf_cache_readonly BEFORE INSERT OR UPDATE OR DELETE OR TRUNCATE "
+ "ON pg_temp._floci_udf_cache FOR EACH STATEMENT EXECUTE FUNCTION pg_temp._floci_udf_cache_guard(); "
+ "END IF; END $$";
static final String DISABLE_CACHE_GUARD_SQL =
"ALTER TABLE pg_temp._floci_udf_cache DISABLE TRIGGER _floci_udf_cache_readonly";
static final String ENABLE_CACHE_GUARD_SQL =
"ALTER TABLE pg_temp._floci_udf_cache ENABLE TRIGGER _floci_udf_cache_readonly";
static final String TRUNCATE_CACHE_SQL = "TRUNCATE pg_temp._floci_udf_cache";
static final String SET_COLLECT_MODE_SQL = "SELECT pg_catalog.set_config('floci.udf_mode', 'collect', true)";
static final String SET_EXECUTE_MODE_SQL = "SELECT pg_catalog.set_config('floci.udf_mode', 'execute', false)";
static final String RESET_MODE_SQL = "SELECT pg_catalog.set_config('floci.udf_mode', '', false)";
static final String RESET_CACHE_SQL = "DO $$ BEGIN "
+ "IF pg_catalog.to_regclass('pg_temp._floci_udf_cache') IS NOT NULL THEN "
+ "ALTER TABLE pg_temp._floci_udf_cache DISABLE TRIGGER _floci_udf_cache_readonly; "
+ "TRUNCATE pg_temp._floci_udf_cache; "
+ "ALTER TABLE pg_temp._floci_udf_cache ENABLE TRIGGER _floci_udf_cache_readonly; "
+ "END IF; END $$";
static final String READ_PENDING_SQL = "SELECT fn_key, args_json FROM pg_temp._floci_udf_pending "
+ "ORDER BY fn_key, args_json";
private final ExternalFunctionRegistry functions;
private final LambdaUdfInvoker invoker;
private final AtomicLong nextQueryId = new AtomicLong();
@Inject
public LambdaUdfEvaluator(ExternalFunctionRegistry functions, LambdaUdfInvoker invoker) {
this.functions = Objects.requireNonNull(functions, "functions must not be null");
this.invoker = Objects.requireNonNull(invoker, "invoker must not be null");
}
/**
* Builds the plpgsql stub DDL for {@code CREATE [OR REPLACE] EXTERNAL FUNCTION}. The stub is always created as
* {@code VOLATILE} in PostgreSQL so it may insert into the temp pending table even when the Redshift UDF was
* declared {@code STABLE}.
*/
static String stubSql(ExternalStatement.CreateFunction function, String schema, boolean replace) {
String key = ExternalFunctionBinding.nameOf(schema, function.functionName(), function.argumentTypes());
String argsExpr = function.argumentTypes().isEmpty()
? "'[]'"
: "pg_catalog.json_build_array("
+ IntStream.rangeClosed(1, function.argumentTypes().size())
.mapToObj(i -> "$" + i + "::text")
.collect(Collectors.joining(", "))
+ ")::text";
String qualifiedName = schema + "." + function.functionName();
// The message is an argument, not the format string, so a % in a quoted name is not read as a placeholder.
String body = "DECLARE "
+ "v_mode text := pg_catalog.current_setting('floci.udf_mode', true); "
+ "v_key text := " + PostgresWire.quoteLiteral(key) + "; "
+ "v_args text := " + argsExpr + "; "
+ "v_result text; "
+ "BEGIN "
+ "IF v_mode = 'collect' THEN "
+ "SELECT c.result_text INTO v_result FROM pg_temp._floci_udf_cache c "
+ "WHERE c.fn_key = v_key AND c.args_json = v_args; "
+ "IF FOUND THEN RETURN v_result::" + function.returnType() + "; END IF; "
+ "INSERT INTO pg_temp._floci_udf_pending (fn_key, args_json) VALUES (v_key, v_args) "
+ "ON CONFLICT DO NOTHING; "
+ "RETURN NULL; "
+ "ELSIF v_mode = 'execute' THEN "
+ "SELECT c.result_text INTO v_result FROM pg_temp._floci_udf_cache c "
+ "WHERE c.fn_key = v_key AND c.args_json = v_args; "
+ "IF FOUND THEN RETURN v_result::" + function.returnType() + "; END IF; "
+ "RAISE EXCEPTION '%', "
+ PostgresWire.quoteLiteral("External function " + qualifiedName
+ " was not prepared for these arguments")
+ " USING ERRCODE = 'XX000'; "
+ "ELSE "
+ "RAISE EXCEPTION '%', "
+ PostgresWire.quoteLiteral("External function " + qualifiedName + " cannot be called directly")
+ " USING ERRCODE = '0A000'; "
+ "END IF; "
+ "END";
return "CREATE " + (replace ? "OR REPLACE " : "") + "FUNCTION "
+ signature(schema, function.functionName(), function.argumentTypes())
+ " RETURNS " + function.returnType() + " LANGUAGE plpgsql VOLATILE AS "
+ PostgresWire.quoteLiteral(body);
}
static String signature(String schema, String functionName, List<String> argumentTypes) {
return ExternalTableMaterializer.quote(schema) + "." + ExternalTableMaterializer.quote(functionName)
+ "(" + String.join(", ", argumentTypes) + ")";
}
/**
* Whether {@code sql} contains a function call matching any registered external function in the session's DB,
* respecting explicit schema qualification and argument arity.
*/
public boolean referencesExternalFunction(String sql, SpectrumSession session) {
if (sql == null || sql.isBlank()) {
return false;
}
List<ExternalFunctionBinding> registered = functions.list(
session.accountId(), session.clusterKey(), session.databaseName());
if (registered.isEmpty()) {
return false;
}
List<SpectrumSqlLexer.Token> tokens = SpectrumSqlLexer.tokenize(sql).tokens();
for (int i = 0; i + 1 < tokens.size(); i++) {
SpectrumSqlLexer.Token token = tokens.get(i);
if ((token.kind() == SpectrumSqlLexer.Kind.WORD || token.kind() == SpectrumSqlLexer.Kind.QUOTED_WORD)
&& tokens.get(i + 1).kind() == SpectrumSqlLexer.Kind.LPAREN) {
String qualifiedSchema = qualifiedSchemaBefore(tokens, i);
int arity = argumentCount(tokens, i + 1);
if (matchesRegistered(registered, qualifiedSchema, token.text(), arity)) {
return true;
}
}
}
return false;
}
private static String qualifiedSchemaBefore(List<SpectrumSqlLexer.Token> tokens, int nameIndex) {
if (nameIndex < 2) {
return null;
}
SpectrumSqlLexer.Token dot = tokens.get(nameIndex - 1);
SpectrumSqlLexer.Token schema = tokens.get(nameIndex - 2);
if (dot.kind() == SpectrumSqlLexer.Kind.OP && ".".equals(dot.text())
&& (schema.kind() == SpectrumSqlLexer.Kind.WORD
|| schema.kind() == SpectrumSqlLexer.Kind.QUOTED_WORD)) {
return schema.text();
}
return null;
}
/** Counts top-level arguments in the parenthesized call starting at {@code lparenIndex}, or -1 if unknown. */
private static int argumentCount(List<SpectrumSqlLexer.Token> tokens, int lparenIndex) {
if (lparenIndex + 1 >= tokens.size()) {
return -1;
}
if (tokens.get(lparenIndex + 1).kind() == SpectrumSqlLexer.Kind.RPAREN) {
return 0;
}
int depth = 1;
int commas = 0;
for (int i = lparenIndex + 1; i < tokens.size(); i++) {
SpectrumSqlLexer.Token token = tokens.get(i);
if (token.kind() == SpectrumSqlLexer.Kind.LPAREN) {
depth++;
} else if (token.kind() == SpectrumSqlLexer.Kind.RPAREN) {
depth--;
if (depth == 0) {
return commas + 1;
}
} else if (depth == 1) {
if (token.kind() == SpectrumSqlLexer.Kind.COMMA) {
commas++;
} else if (token.isWord("variadic")) {
return -1;
}
}
}
return -1;
}
private static boolean matchesRegistered(List<ExternalFunctionBinding> registered, String qualifiedSchema,
String functionName, int arity) {
for (ExternalFunctionBinding binding : registered) {
if (!binding.functionName().equals(functionName)) {
continue;
}
if (qualifiedSchema != null && !binding.schemaName().equals(qualifiedSchema)) {
continue;
}
if (arity >= 0 && binding.argumentTypes().size() != arity) {
continue;
}
return true;
}
return false;
}
/**
* Collects every external function call triggered by {@code sql}, invokes Lambda in batches, populates the
* session cache table, and enables execute mode. Returns {@code false} without doing work when
* {@code parameters} is null (Extended Query {@code Parse} phase) or when {@code sql} references no registered
* external function.
*/
public boolean prepare(String sql, SpectrumSession session, BackendSql backend, List<String> parameters,
String clusterRegion) {
return prepare(sql, session, backend, parameters, null, clusterRegion);
}
public boolean prepare(String sql, SpectrumSession session, BackendSql backend, List<String> parameters,
BackendSql.RawParameters rawParameters, String clusterRegion) {
if ((parameters == null && rawParameters == null) || !referencesExternalFunction(sql, session)) {
return false;
}
validateCollectableSql(sql);
backend.execute(CREATE_PENDING_TABLE_SQL);
backend.execute(CREATE_CACHE_TABLE_SQL);
backend.execute(CREATE_CACHE_GUARD_FN_SQL);
backend.execute(CREATE_CACHE_GUARD_TRIGGER_SQL);
truncateCache(backend);
String user = backend.queryString(CURRENT_USER_SQL).orElse(DEFAULT_USER);
long queryId = nextQueryId.incrementAndGet();
if (backend.usesSubtransactionCollect()) {
BackendSql.RawParameters effectiveRaw = rawParameters != null ? rawParameters
: (parameters == null || parameters.isEmpty() ? null : textRawParameters(parameters));
prepareWithSubtransaction(sql, session, backend, effectiveRaw, clusterRegion, user, queryId);
return true;
}
boolean useSavepoint = session.inTransaction();
List<String> textParams = parameters == null ? List.of() : parameters;
for (int round = 0; round < MAX_ROUNDS; round++) {
List<List<String>> pending = collectRound(sql, textParams, backend, useSavepoint);
if (pending.isEmpty()) {
backend.execute(SET_EXECUTE_MODE_SQL);
return true;
}
invokeAndCache(pending, session, backend, clusterRegion, user, queryId);
}
throw new SpectrumSqlException("54001",
"External function evaluation exceeded maximum nesting depth (" + MAX_ROUNDS + ")");
}
/**
* Clears execute mode and truncates the session UDF cache so later statements that reach a stub indirectly
* cannot observe results cached for an earlier statement.
*/
public void resetState(BackendSql backend) {
backend.execute(RESET_MODE_SQL);
backend.execute(RESET_CACHE_SQL);
}
private void prepareWithSubtransaction(String sql, SpectrumSession session, BackendSql backend,
BackendSql.RawParameters rawParameters, String clusterRegion,
String user, long queryId) {
SubtransactionCollector collector = SubtransactionCollector.create(sql, rawParameters, backend);
RuntimeException primaryFailure = null;
try {
for (int round = 0; round < MAX_ROUNDS; round++) {
List<List<String>> pending = collector.collect(backend);
if (pending.isEmpty()) {
backend.execute(SET_EXECUTE_MODE_SQL);
return;
}
invokeAndCache(pending, session, backend, clusterRegion, user, queryId);
}
throw new SpectrumSqlException("54001",
"External function evaluation exceeded maximum nesting depth (" + MAX_ROUNDS + ")");
} catch (RuntimeException failure) {
primaryFailure = failure;
throw failure;
} finally {
collector.drop(backend, primaryFailure);
}
}
private void invokeAndCache(List<List<String>> pending, SpectrumSession session, BackendSql backend,
String clusterRegion, String user, long queryId) {
Map<String, List<String>> byFunction = new LinkedHashMap<>();
for (List<String> row : pending) {
if (row.size() >= 2 && row.get(0) != null && row.get(1) != null) {
byFunction.computeIfAbsent(row.get(0), ignored -> new ArrayList<>()).add(row.get(1));
}
}
for (Map.Entry<String, List<String>> entry : byFunction.entrySet()) {
String fnKey = entry.getKey();
List<String> argsJsonList = entry.getValue();
ExternalFunctionBinding binding = functions.find(
session.accountId(), session.clusterKey(), session.databaseName(), fnKey)
.orElseThrow(() -> new SpectrumSqlException("42883",
"External function binding \"" + fnKey + "\" does not exist"));
List<List<String>> rows = new ArrayList<>(argsJsonList.size());
for (String argsJson : argsJsonList) {
rows.add(decodeArgs(argsJson));
}
List<String> results = invoker.invoke(binding, session, clusterRegion, user, queryId, rows);
storeResults(backend, fnKey, argsJsonList, results);
}
}
private static void validateCollectableSql(String sql) {
List<SpectrumSqlLexer.Token> tokens = SpectrumSqlLexer.tokenize(sql).tokens();
if (tokens.isEmpty()) {
return;
}
for (int i = 0; i < tokens.size(); i++) {
if (tokens.get(i).kind() == SpectrumSqlLexer.Kind.SEMICOLON && i + 1 < tokens.size()) {
throw new SpectrumSqlException("0A000",
"External function calls are not supported in multi-statement queries");
}
}
SpectrumSqlLexer.Token first = tokens.get(0);
if (first.kind() == SpectrumSqlLexer.Kind.WORD && DISALLOWED_LEADING_KEYWORDS.contains(first.text())) {
throw new SpectrumSqlException("0A000",
"External function calls are not supported with transaction control or procedural blocks");
}
for (int i = 0; i + 1 < tokens.size(); i++) {
SpectrumSqlLexer.Token token = tokens.get(i);
if ((token.kind() == SpectrumSqlLexer.Kind.WORD || token.kind() == SpectrumSqlLexer.Kind.QUOTED_WORD)
&& tokens.get(i + 1).kind() == SpectrumSqlLexer.Kind.LPAREN) {
String lower = token.text().toLowerCase(Locale.ROOT);
if (VOLATILE_ARGUMENT_FUNCTIONS.contains(lower)) {
throw new SpectrumSqlException("0A000",
"External function calls cannot be combined with volatile expression \"" + lower + "()\"");
}
}
}
}
private List<List<String>> collectRound(String sql, List<String> parameters, BackendSql backend,
boolean useSavepoint) {
if (useSavepoint) {
backend.execute("SAVEPOINT _floci_udf_collect");
} else {
backend.execute("BEGIN");
}
List<List<String>> pending;
try {
backend.execute(SET_COLLECT_MODE_SQL);
backend.execute(sql, parameters);
pending = backend.queryRows(READ_PENDING_SQL);
} catch (RuntimeException failure) {
rollbackCollect(backend, useSavepoint, failure);
throw failure;
}
rollbackCollect(backend, useSavepoint, null);
return pending;
}
private static void rollbackCollect(BackendSql backend, boolean useSavepoint, RuntimeException primaryFailure) {
try {
if (useSavepoint) {
backend.execute("ROLLBACK TO SAVEPOINT _floci_udf_collect");
backend.execute("RELEASE SAVEPOINT _floci_udf_collect");
} else {
backend.execute("ROLLBACK");
}
} catch (RuntimeException cleanupFailure) {
if (primaryFailure != null) {
primaryFailure.addSuppressed(cleanupFailure);
} else {
throw cleanupFailure;
}
}
}
private static void truncateCache(BackendSql backend) {
backend.execute(DISABLE_CACHE_GUARD_SQL);
RuntimeException primaryFailure = null;
try {
backend.execute(TRUNCATE_CACHE_SQL);
} catch (RuntimeException failure) {
primaryFailure = failure;
throw failure;
} finally {
reEnableCacheGuard(backend, primaryFailure);
}
}
private static void storeResults(BackendSql backend, String fnKey, List<String> argsJsonList,
List<String> results) {
String quotedKey = PostgresWire.quoteLiteral(fnKey);
backend.execute(DISABLE_CACHE_GUARD_SQL);
RuntimeException primaryFailure = null;
try {
for (int start = 0; start < argsJsonList.size(); start += CACHE_INSERT_BATCH_SIZE) {
int end = Math.min(start + CACHE_INSERT_BATCH_SIZE, argsJsonList.size());
StringBuilder sql = new StringBuilder(
"INSERT INTO pg_temp._floci_udf_cache (fn_key, args_json, result_text) VALUES ");
for (int i = start; i < end; i++) {
if (i > start) {
sql.append(", ");
}
String result = results.get(i);
sql.append('(')
.append(quotedKey).append(", ")
.append(PostgresWire.quoteLiteral(argsJsonList.get(i))).append(", ")
.append(result == null ? "NULL" : PostgresWire.quoteLiteral(result))
.append(')');
}
sql.append(" ON CONFLICT (fn_key, args_json) DO UPDATE SET result_text = EXCLUDED.result_text");
backend.execute(sql.toString());
}
} catch (RuntimeException failure) {
primaryFailure = failure;
throw failure;
} finally {
reEnableCacheGuard(backend, primaryFailure);
}
}
private static void reEnableCacheGuard(BackendSql backend, RuntimeException primaryFailure) {
try {
backend.execute(ENABLE_CACHE_GUARD_SQL);
} catch (RuntimeException cleanupFailure) {
if (primaryFailure != null) {
primaryFailure.addSuppressed(cleanupFailure);
} else {
throw cleanupFailure;
}
}
}
private static List<String> decodeArgs(String argsJson) {
try {
JsonNode node = JSON.readTree(argsJson);
if (node == null || !node.isArray()) {
throw new SpectrumSqlException("XX000", "Invalid collected UDF argument tuple: " + argsJson);
}
List<String> values = new ArrayList<>(node.size());
for (JsonNode element : node) {
values.add(element == null || element.isNull() ? null : element.asText());
}
return values;
} catch (IOException exception) {
throw new SpectrumSqlException("XX000", "Unable to decode collected UDF arguments: "
+ exception.getMessage());
}
}
private static List<List<String>> decodePendingJson(String json) {
if (json == null || json.isBlank()) {
return List.of();
}
try {
JsonNode root = JSON.readTree(json);
if (root == null || !root.isArray()) {
return List.of();
}
List<List<String>> rows = new ArrayList<>(root.size());
for (JsonNode entry : root) {
if (entry != null && entry.isArray() && entry.size() >= 2) {
rows.add(List.of(entry.get(0).asText(), entry.get(1).asText()));
}
}
return rows;
} catch (IOException exception) {
throw new SpectrumSqlException("XX000", "Unable to decode collected UDF rows: "
+ exception.getMessage());
}
}
private static BackendSql.RawParameters textRawParameters(List<String> parameters) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(bytes);
try {
out.writeShort(0);
out.writeShort(parameters.size());
for (String value : parameters) {
if (value == null) {
out.writeInt(-1);
} else {
byte[] utf8 = value.getBytes(StandardCharsets.UTF_8);
out.writeInt(utf8.length);
out.write(utf8);
}
}
} catch (IOException impossible) {
throw new IllegalStateException(impossible);
}
return new BackendSql.RawParameters(List.of(), parameters.size(), bytes.toByteArray());
}
/**
* Temporary PL/pgSQL function that runs a statement inside an internal subtransaction, captures pending UDF calls
* into a local variable, and rolls back the subtransaction via a sentinel exception. Works in Extended Query
* autocommit mode where {@code SAVEPOINT} is rejected with {@code 25P01}.
*/
private static final class SubtransactionCollector {
private final String fnName;
private final List<Integer> resolvedOids;
private final BackendSql.RawParameters boundParameters;
private final String callSql;
private SubtransactionCollector(String fnName, List<Integer> resolvedOids,
BackendSql.RawParameters boundParameters, String callSql) {
this.fnName = fnName;
this.resolvedOids = resolvedOids;
this.boundParameters = boundParameters;
this.callSql = callSql;
}
private static SubtransactionCollector create(String sql, BackendSql.RawParameters rawParameters,
BackendSql backend) {
String id = UUID.randomUUID().toString().replace("-", "");
String fnName = "_floci_udf_collect_" + id;
String sentinel = "_floci_udf_done_" + id;
String ddlTag = "$floci_ddl_" + id + "$";
String bodyTag = "$floci_body_" + id + "$";
String sqlTag = "$floci_sql_" + id + "$";
int paramCount = rawParameters == null ? 0 : rawParameters.count();
List<Integer> resolvedOids = paramCount == 0 ? List.of()
: backend.resolveParameterTypeOids(sql, rawParameters.typeOids(), paramCount);
if (paramCount > 0 && resolvedOids.size() != paramCount) {
throw new SpectrumSqlException("XX000",
"Unable to resolve parameter types for external function collect pass");
}
String usingClause = paramCount == 0 ? ""
: " USING " + IntStream.rangeClosed(1, paramCount)
.mapToObj(i -> "p" + i)
.collect(Collectors.joining(", "));
String body = "DECLARE v_pending text; BEGIN BEGIN "
+ "PERFORM pg_catalog.set_config('floci.udf_mode', 'collect', true); "
+ "EXECUTE " + sqlTag + sql + sqlTag + usingClause + "; "
+ "SELECT pg_catalog.json_agg(pg_catalog.json_build_array(fn_key, args_json) "
+ "ORDER BY fn_key, args_json)::text INTO v_pending FROM pg_temp._floci_udf_pending; "
+ "RAISE EXCEPTION USING ERRCODE = 'P0001', MESSAGE = " + PostgresWire.quoteLiteral(sentinel) + "; "
+ "EXCEPTION WHEN SQLSTATE 'P0001' THEN "
+ "IF SQLERRM <> " + PostgresWire.quoteLiteral(sentinel) + " THEN RAISE; END IF; "
+ "END; RETURN COALESCE(v_pending, '[]'); END;";
String createSql;
String callSql;
BackendSql.RawParameters boundParameters;
if (paramCount == 0) {
createSql = "DO " + ddlTag + " BEGIN EXECUTE 'CREATE FUNCTION pg_temp." + fnName
+ "() RETURNS text LANGUAGE plpgsql AS ' || pg_catalog.quote_literal("
+ bodyTag + body + bodyTag + "); END " + ddlTag;
callSql = "SELECT pg_temp." + fnName + "()";
boundParameters = null;
} else {
String paramDeclExpr = IntStream.range(0, paramCount)
.mapToObj(i -> "'p" + (i + 1) + " ' || pg_catalog.format_type(" + resolvedOids.get(i) + ", -1)")
.collect(Collectors.joining(" || ', ' || "));
createSql = "DO " + ddlTag + " BEGIN EXECUTE 'CREATE FUNCTION pg_temp." + fnName
+ "(' || " + paramDeclExpr
+ " || ') RETURNS text LANGUAGE plpgsql AS ' || pg_catalog.quote_literal("
+ bodyTag + body + bodyTag + "); END " + ddlTag;
String placeholders = IntStream.rangeClosed(1, paramCount)
.mapToObj(i -> "$" + i)
.collect(Collectors.joining(", "));
callSql = "SELECT pg_temp." + fnName + "(" + placeholders + ")";
boundParameters = new BackendSql.RawParameters(resolvedOids, paramCount, rawParameters.bindSection());
}
backend.execute(createSql);
return new SubtransactionCollector(fnName, resolvedOids, boundParameters, callSql);
}
private List<List<String>> collect(BackendSql backend) {
String json = boundParameters == null
? backend.queryString(callSql).orElse("[]")
: backend.queryString(callSql, boundParameters).orElse("[]");
return decodePendingJson(json);
}
private void drop(BackendSql backend, RuntimeException primaryFailure) {
if (primaryFailure != null) {
return;
}
String id = UUID.randomUUID().toString().replace("-", "");
String ddlTag = "$floci_drop_" + id + "$";
String dropSql;
if (resolvedOids.isEmpty()) {
dropSql = "DO " + ddlTag + " BEGIN EXECUTE 'DROP FUNCTION IF EXISTS pg_temp." + fnName
+ "()'; END " + ddlTag;
} else {
String argTypesExpr = resolvedOids.stream()
.map(oid -> "pg_catalog.format_type(" + oid + ", -1)")
.collect(Collectors.joining(" || ', ' || "));
dropSql = "DO " + ddlTag + " BEGIN EXECUTE 'DROP FUNCTION IF EXISTS pg_temp." + fnName
+ "(' || " + argTypesExpr + " || ')'; END " + ddlTag;
}
backend.execute(dropSql);
}
}
}
@@ -1,5 +1,6 @@
package io.floci.aws.services.redshift.spectrum;
import io.floci.aws.core.common.PostgresWire;
import io.floci.aws.services.redshift.proxy.PostgresWireDecoder;
import java.io.IOException;
@@ -7,6 +8,8 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public final class PostgresBackendSession implements BackendSql {
@@ -35,6 +38,19 @@ public final class PostgresBackendSession implements BackendSql {
}
}
@Override
public List<List<String>> queryRows(String sql) {
try {
OutputStream output = backend.getOutputStream();
output.write(PostgresWireDecoder.encodeQuery(sql));
output.flush();
return awaitRows(new PostgresWireDecoder(backend.getInputStream()));
} catch (IOException exception) {
abandon(backend, exception);
throw new SpectrumReadException(SQLSTATE_IO, "Unable to run a statement on the Redshift backend", exception);
}
}
/**
* Closes a backend whose private exchange did not finish. Its replies may still arrive, and the response pump
* would forward them to the client as if the client had asked; a closed connection is the one state where
@@ -175,20 +191,29 @@ public final class PostgresBackendSession implements BackendSql {
throw new IOException("PostgreSQL closed before ReadyForQuery");
}
private static List<List<String>> awaitRows(PostgresWireDecoder decoder) throws IOException {
SpectrumReadException failure = null;
List<List<String>> rows = new ArrayList<>();
PostgresWireDecoder.FrontendMessage message = decoder.nextMessage();
while (message != null) {
if (message.type() == 'D') {
rows.add(PostgresWire.dataRowValues(message.body()));
} else if (message.type() == 'E') {
failure = toException(message.body());
} else if (message.type() == 'Z') {
if (failure != null) {
throw failure;
}
return rows;
}
message = decoder.nextMessage();
}
throw new IOException("PostgreSQL closed before ReadyForQuery");
}
static String firstColumn(byte[] body) {
if (body == null || body.length < 6) {
return null;
}
int columns = ((body[0] & 0xff) << 8) | (body[1] & 0xff);
if (columns < 1) {
return null;
}
int length = ((body[2] & 0xff) << 24) | ((body[3] & 0xff) << 16)
| ((body[4] & 0xff) << 8) | (body[5] & 0xff);
if (length < 0 || body.length < 6 + length) {
return null;
}
return new String(body, 6, length, StandardCharsets.UTF_8);
List<String> row = PostgresWire.dataRowValues(body);
return row.isEmpty() ? null : row.get(0);
}
private static long rowCount(String tag) {
@@ -1,5 +1,7 @@
package io.floci.aws.services.redshift.spectrum;
import io.floci.aws.core.common.PostgresWire;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
@@ -7,6 +9,8 @@ import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@@ -25,6 +29,57 @@ public final class PostgresExtendedBackendSession implements BackendSql {
return false;
}
@Override
public boolean usesSubtransactionCollect() {
return true;
}
@Override
public List<Integer> resolveParameterTypeOids(String sql, List<Integer> declaredTypeOids, int parameterCount) {
if (declaredTypeOids != null && declaredTypeOids.size() == parameterCount && !declaredTypeOids.contains(0)) {
return declaredTypeOids;
}
try {
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);
List<Integer> declared = declaredTypeOids == null ? List.of() : declaredTypeOids;
body.writeShort(declared.size());
for (Integer oid : declared) {
body.writeInt(oid == null ? 0 : oid);
}
frame('P', bytes.toByteArray());
frame('D', ("S" + name + "\0").getBytes(StandardCharsets.UTF_8));
frame('C', ("S" + name + "\0").getBytes(StandardCharsets.UTF_8));
frame('H', new byte[0]);
backend.getOutputStream().flush();
return awaitParameterDescriptionClosed();
} catch (IOException exception) {
PostgresBackendSession.abandon(backend, exception);
throw failure(exception);
}
}
@Override
public Optional<String> queryString(String sql, RawParameters parameters) {
if (parameters == null || parameters.count() == 0) {
return queryString(sql);
}
try {
startRaw(sql, parameters);
closeAndFlush();
return awaitSingleStringClosed();
} catch (IOException exception) {
PostgresBackendSession.abandon(backend, exception);
throw failure(exception);
}
}
@Override
public Object connectionKey() {
return backend;
@@ -42,7 +97,7 @@ public final class PostgresExtendedBackendSession implements BackendSql {
@Override
public Optional<String> queryString(String sql) {
try {
start(sql);
start(sql, List.of());
closeAndFlush();
return awaitSingleStringClosed();
} catch (IOException exception) {
@@ -51,10 +106,37 @@ public final class PostgresExtendedBackendSession implements BackendSql {
}
}
@Override
public List<List<String>> queryRows(String sql) {
try {
start(sql, List.of());
closeAndFlush();
return awaitRowsClosed();
} catch (IOException exception) {
PostgresBackendSession.abandon(backend, exception);
throw failure(exception);
}
}
@Override
public void execute(String sql) {
try {
start(atomicCommand(sql));
start(atomicCommand(sql), List.of());
closeAndFlush();
awaitClosed();
} catch (IOException exception) {
throw failure(exception);
}
}
@Override
public void execute(String sql, List<String> parameters) {
if (parameters == null || parameters.isEmpty()) {
execute(sql);
return;
}
try {
start(sql, parameters);
closeAndFlush();
awaitClosed();
} catch (IOException exception) {
@@ -73,7 +155,7 @@ public final class PostgresExtendedBackendSession implements BackendSql {
@Override
public long copyIn(String sql, InputStream data) {
try {
start(sql);
start(sql, List.of());
frame('H', new byte[0]);
backend.getOutputStream().flush();
readUntil('G');
@@ -105,7 +187,7 @@ public final class PostgresExtendedBackendSession implements BackendSql {
}
}
private void start(String sql) throws IOException {
private void start(String sql, List<String> parameters) throws IOException {
if (failedUntilSync) {
throw new SpectrumReadException("25P02", "Preparation is waiting for Sync after a backend error");
}
@@ -120,7 +202,16 @@ public final class PostgresExtendedBackendSession implements BackendSql {
cstring(body, name);
cstring(body, name);
body.writeShort(0);
body.writeShort(0);
body.writeShort(parameters.size());
for (String value : parameters) {
if (value == null) {
body.writeInt(-1);
} else {
byte[] utf8 = value.getBytes(StandardCharsets.UTF_8);
body.writeInt(utf8.length);
body.write(utf8);
}
}
body.writeShort(0);
frame('B', bytes.toByteArray());
bytes.reset();
@@ -129,6 +220,65 @@ public final class PostgresExtendedBackendSession implements BackendSql {
frame('E', bytes.toByteArray());
}
private void startRaw(String sql, RawParameters parameters) 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);
List<Integer> typeOids = parameters.typeOids();
body.writeShort(typeOids.size());
for (Integer oid : typeOids) {
body.writeInt(oid == null ? 0 : oid);
}
frame('P', bytes.toByteArray());
bytes.reset();
cstring(body, name);
cstring(body, name);
body.write(parameters.bindSection());
body.writeShort(0);
frame('B', bytes.toByteArray());
bytes.reset();
cstring(body, name);
body.writeInt(0);
frame('E', bytes.toByteArray());
}
private List<Integer> awaitParameterDescriptionClosed() throws IOException {
List<Integer> oids = List.of();
while (true) {
Response response = read();
if (response.type() == 't') {
oids = decodeParameterDescription(response.body());
} else if (response.type() == '3') {
return oids;
}
}
}
private static List<Integer> decodeParameterDescription(byte[] body) throws IOException {
if (body == null || body.length < 2) {
throw new IOException("Invalid ParameterDescription response");
}
int count = ((body[0] & 0xff) << 8) | (body[1] & 0xff);
if (body.length < 2 + count * 4) {
throw new IOException("Truncated ParameterDescription response");
}
List<Integer> oids = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
int offset = 2 + i * 4;
int oid = ((body[offset] & 0xff) << 24)
| ((body[offset + 1] & 0xff) << 16)
| ((body[offset + 2] & 0xff) << 8)
| (body[offset + 3] & 0xff);
oids.add(oid);
}
return List.copyOf(oids);
}
private void closeAndFlush() throws IOException {
frame('C', ("P" + name + "\0").getBytes(StandardCharsets.UTF_8));
frame('C', ("S" + name + "\0").getBytes(StandardCharsets.UTF_8));
@@ -164,6 +314,19 @@ public final class PostgresExtendedBackendSession implements BackendSql {
return Optional.ofNullable(value);
}
private List<List<String>> awaitRowsClosed() throws IOException {
List<List<String>> rows = new ArrayList<>();
for (int closed = 0; closed < 2;) {
Response response = read();
if (response.type() == 'D') {
rows.add(PostgresWire.dataRowValues(response.body()));
} else if (response.type() == '3') {
closed++;
}
}
return rows;
}
private void readUntil(char type) throws IOException {
Response response;
do {
@@ -20,6 +20,7 @@ import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@@ -46,6 +47,7 @@ public class SpectrumQueryPreparation {
private final KinesisSchemaRegistry kinesisSchemas;
private final MskSchemaRegistry mskSchemas;
private final ExternalFunctionRegistry functions;
private final LambdaUdfEvaluator udfEvaluator;
private final KinesisStreamingViews views;
private final MskStreamingViews mskViews;
private final ExternalTableMaterializer materializer;
@@ -73,12 +75,13 @@ public class SpectrumQueryPreparation {
@Inject
public SpectrumQueryPreparation(ExternalCatalogRegistry registry, KinesisSchemaRegistry kinesisSchemas,
MskSchemaRegistry mskSchemas, ExternalFunctionRegistry functions,
LambdaUdfEvaluator udfEvaluator,
ExternalTableMaterializer materializer, ExternalStatementParser parser,
GlueService glue, ExternalMetadataWriter metadata,
ExternalCatalogLocks catalogLocks, KinesisStreamingViews views,
MskStreamingViews mskViews, Instance<RedshiftService> redshift) {
this(registry, kinesisSchemas, mskSchemas, functions, materializer, parser, glue, metadata, catalogLocks,
views, mskViews,
this(registry, kinesisSchemas, mskSchemas, functions, udfEvaluator, materializer, parser, glue, metadata,
catalogLocks, views, mskViews,
(accountId, clusterIdentifier) -> redshift.get().clusterRegion(accountId, clusterIdentifier).orElse(null));
}
@@ -127,7 +130,30 @@ public class SpectrumQueryPreparation {
GlueService glue, ExternalMetadataWriter metadata, ExternalCatalogLocks catalogLocks,
KinesisStreamingViews views, MskStreamingViews mskViews,
BiFunction<String, String, String> clusterRegion) {
this(registry, kinesisSchemas, mskSchemas, functions,
new LambdaUdfEvaluator(functions, unconfiguredUdfInvoker()),
materializer, parser, glue, metadata, catalogLocks, views, mskViews, clusterRegion);
}
private static LambdaUdfInvoker unconfiguredUdfInvoker() {
return new LambdaUdfInvoker(null, null, null, null, null, null) {
@Override
public List<String> invoke(ExternalFunctionBinding function, SpectrumSession session, String clusterRegion,
String user, long queryId, List<List<String>> rows) {
throw new SpectrumSqlException("XX000", "Lambda UDF invoker is not configured");
}
};
}
SpectrumQueryPreparation(ExternalCatalogRegistry registry, KinesisSchemaRegistry kinesisSchemas,
MskSchemaRegistry mskSchemas, ExternalFunctionRegistry functions,
LambdaUdfEvaluator udfEvaluator,
ExternalTableMaterializer materializer, ExternalStatementParser parser,
GlueService glue, ExternalMetadataWriter metadata, ExternalCatalogLocks catalogLocks,
KinesisStreamingViews views, MskStreamingViews mskViews,
BiFunction<String, String, String> clusterRegion) {
this.functions = functions;
this.udfEvaluator = Objects.requireNonNull(udfEvaluator, "udfEvaluator must not be null");
this.views = views;
this.mskViews = mskViews;
this.clusterRegion = clusterRegion;
@@ -160,22 +186,61 @@ public class SpectrumQueryPreparation {
* where it is unusable; null {@code parameters} means the statement is only being parsed, with no values yet.
*/
public boolean prepare(String sql, SpectrumSession session, BackendSql backend, List<String> parameters) {
return prepare(sql, session, backend, parameters, true);
}
/**
* Prepares Spectrum external tables and DDL without running Lambda UDF collect passes, used during Extended Query
* {@code Bind} so UDF preparation runs per portal at {@code Execute} time.
*/
public boolean prepareTables(String sql, SpectrumSession session, BackendSql backend, List<String> parameters) {
return prepare(sql, session, backend, parameters, false);
}
/**
* Evaluates Lambda UDF calls for a bound Extended Query portal right before {@code Execute}.
*/
public boolean prepareExternalFunctions(String sql, SpectrumSession session, BackendSql backend,
List<String> parameters, BackendSql.RawParameters rawParameters) {
try {
return RequestScopes.callAs(session.accountId(), catalogRegion(session),
() -> prepareInScope(sql, session, backend, parameters));
() -> udfEvaluator.prepare(sql, session, backend, parameters, rawParameters,
catalogRegion(session)));
} catch (AwsException exception) {
String state = switch (exception.getErrorCode()) {
case "AlreadyExistsException" -> "42P07";
case "EntityNotFoundException" -> "42P01";
case "ResourceNotFoundException" -> "42P01";
case "AccessDenied", "AccessDeniedException" -> "42501";
case "InvalidInputException" -> "42601";
default -> "58030";
};
throw new SpectrumSqlException(state, exception.getMessage());
throw toSpectrumSqlException(exception);
}
}
public boolean referencesExternalFunction(String sql, SpectrumSession session) {
return udfEvaluator.referencesExternalFunction(sql, session);
}
public void resetUdfState(BackendSql backend) {
udfEvaluator.resetState(backend);
}
private boolean prepare(String sql, SpectrumSession session, BackendSql backend, List<String> parameters,
boolean includeUdfs) {
try {
return RequestScopes.callAs(session.accountId(), catalogRegion(session),
() -> prepareInScope(sql, session, backend, parameters, includeUdfs));
} catch (AwsException exception) {
throw toSpectrumSqlException(exception);
}
}
private static SpectrumSqlException toSpectrumSqlException(AwsException exception) {
String state = switch (exception.getErrorCode()) {
case "AlreadyExistsException" -> "42P07";
case "EntityNotFoundException" -> "42P01";
case "ResourceNotFoundException" -> "42P01";
case "AccessDenied", "AccessDeniedException" -> "42501";
case "InvalidInputException" -> "42601";
default -> "58030";
};
return new SpectrumSqlException(state, exception.getMessage());
}
public boolean referencesExternal(String sql, SpectrumSession session) {
Set<String> schemas = bindingsOf(registry, session).keySet();
Set<String> kinesisSchemaNames = bindingsOf(kinesisSchemas, session).keySet();
@@ -184,7 +249,8 @@ public class SpectrumQueryPreparation {
|| !ExternalReferenceScanner.scan(sql, kinesisSchemaNames).isEmpty()
|| !ExternalReferenceScanner.scan(sql, mskSchemaNames).isEmpty()
|| ExternalReferenceScanner.writeTarget(sql,
externalSchemaNames(schemas, kinesisSchemaNames, mskSchemaNames)).isPresent();
externalSchemaNames(schemas, kinesisSchemaNames, mskSchemaNames)).isPresent()
|| udfEvaluator.referencesExternalFunction(sql, session);
}
public boolean needsBackendForDdl(String sql, SpectrumSession session) {
@@ -241,7 +307,8 @@ public class SpectrumQueryPreparation {
};
}
private boolean prepareInScope(String sql, SpectrumSession session, BackendSql backend, List<String> parameters) {
private boolean prepareInScope(String sql, SpectrumSession session, BackendSql backend, List<String> parameters,
boolean includeUdfs) {
Optional<ExternalStatement> statement = parser.parse(sql);
if (statement.orElse(null) instanceof ExternalStatement.CreateSchema schema) {
return createSchema(schema, session, backend);
@@ -397,6 +464,9 @@ public class SpectrumQueryPreparation {
}
}
}
if (includeUdfs) {
udfEvaluator.prepare(sql, session, backend, parameters, catalogRegion(session));
}
return false;
}
@@ -597,8 +667,7 @@ public class SpectrumQueryPreparation {
}
/**
* Creates the stub function the backend holds and remembers what the statement declared. The stub refuses every
* call with {@code 0A000}: the backend cannot reach Lambda, so evaluating a call is not wired yet.
* Creates the plpgsql stub function the backend holds and remembers what the statement declared.
*/
private boolean createFunction(ExternalStatement.CreateFunction function, SpectrumSession session,
BackendSql backend) {
@@ -613,7 +682,7 @@ public class SpectrumQueryPreparation {
// The backend still decides whether the return type differs on a replace (42P13).
boolean replace = function.orReplace() && functions.findFunction(session, schema, function.functionName(),
function.argumentTypes()).isPresent();
backend.execute(stubSql(function, schema, replace));
backend.execute(LambdaUdfEvaluator.stubSql(function, schema, replace));
try {
functions.replace(binding);
} catch (RuntimeException exception) {
@@ -692,29 +761,13 @@ public class SpectrumQueryPreparation {
+ "WHERE p.oid = pg_catalog.to_regprocedure(" + PostgresWire.quoteLiteral(signature) + ")";
}
private static String stubSql(ExternalStatement.CreateFunction function, String schema, boolean replace) {
// The message is an argument, not the format string, so a % in a quoted name is not read as a placeholder.
String body = "BEGIN RAISE EXCEPTION '%', "
+ PostgresWire.quoteLiteral("External function " + schema + "." + function.functionName()
+ " cannot be called: invoking Lambda from SQL is not supported yet")
+ " USING ERRCODE = '0A000'; END";
return "CREATE " + (replace ? "OR REPLACE " : "") + "FUNCTION "
+ signature(schema, function.functionName(), function.argumentTypes())
+ " RETURNS " + function.returnType() + " LANGUAGE plpgsql " + function.volatility() + " AS "
+ PostgresWire.quoteLiteral(body);
}
private static String dropStubSql(String schema, String functionName, List<String> argumentTypes,
boolean ifExists, boolean cascade) {
return "DROP FUNCTION " + (ifExists ? "IF EXISTS " : "") + signature(schema, functionName, argumentTypes)
return "DROP FUNCTION " + (ifExists ? "IF EXISTS " : "")
+ LambdaUdfEvaluator.signature(schema, functionName, argumentTypes)
+ (cascade ? " CASCADE" : " RESTRICT");
}
private static String signature(String schema, String functionName, List<String> argumentTypes) {
return ExternalTableMaterializer.quote(schema) + "." + ExternalTableMaterializer.quote(functionName)
+ "(" + String.join(", ", argumentTypes) + ")";
}
/** A name is taken when any kind of external schema already holds it. */
private boolean schemaExists(SpectrumSession session, String schemaName) {
return registry.find(session.accountId(), session.clusterKey(), session.databaseName(), schemaName).isPresent()
@@ -7,9 +7,13 @@ import org.postgresql.PGConnection;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
final class RedshiftDataBackendSql implements BackendSql {
@@ -43,6 +47,33 @@ final class RedshiftDataBackendSql implements BackendSql {
}
}
@Override
public List<List<String>> queryRows(String sql) {
try (Statement statement = connection.createStatement()) {
if (execution != null) {
execution.track(statement);
}
try (ResultSet rows = statement.executeQuery(sql)) {
int columns = rows.getMetaData().getColumnCount();
List<List<String>> result = new ArrayList<>();
while (rows.next()) {
List<String> row = new ArrayList<>(columns);
for (int i = 1; i <= columns; i++) {
row.add(rows.getString(i));
}
result.add(row);
}
return result;
} finally {
if (execution != null) {
execution.untrack(statement);
}
}
} catch (SQLException exception) {
throw failure(exception);
}
}
@Override
public void execute(String sql) {
try (Statement statement = connection.createStatement()) {
@@ -61,6 +92,36 @@ final class RedshiftDataBackendSql implements BackendSql {
}
}
@Override
public void execute(String sql, List<String> parameters) {
if (parameters == null || parameters.isEmpty()) {
execute(sql);
return;
}
try (PreparedStatement statement = connection.prepareStatement(sql)) {
if (execution != null) {
execution.track(statement);
}
try {
for (int i = 0; i < parameters.size(); i++) {
String value = parameters.get(i);
if (value == null) {
statement.setNull(i + 1, Types.NULL);
} else {
statement.setString(i + 1, value);
}
}
statement.execute();
} finally {
if (execution != null) {
execution.untrack(statement);
}
}
} catch (SQLException exception) {
throw failure(exception);
}
}
@Override
public long copyIn(String copySql, InputStream data) {
try {
@@ -697,14 +697,44 @@ public class RedshiftDataService implements Resettable, StoredResourceArns {
Connection connection, String sql, Map<String, String> parameters, SpectrumSession context,
RedshiftDataExecution execution, boolean autoCommit)
throws SQLException {
String rewritten = CopyJobSql.rewrite(sql, !autoCommit || !connection.getAutoCommit());
ParsedSql parsed = RedshiftDataSqlParameters.parse(RedshiftSqlInterceptor.rewrite(rewritten));
boolean udfPrepared = false;
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, execution))) {
RedshiftDataBackendSql backend = new RedshiftDataBackendSql(connection, execution);
boolean ddl = preparation.needsBackendForDdl(sql, session)
? preparation.handlesDdl(sql, session, backend)
: preparation.handlesDdl(sql, session);
boolean usesUdf = !ddl && preparation.referencesExternalFunction(parsed.sql(), session);
List<String> positional = positionalParameters(parsed.parameterOrder(), parameters);
boolean handled;
if (ddl) {
handled = preparation.prepare(sql, session, backend);
} else if (usesUdf) {
handled = preparation.prepareTables(parsed.sql(), session, backend, positional);
if (!handled) {
// The collect passes and the statement share one transaction, so now() and the other
// transaction-time arguments the cached results are keyed on cannot change between them.
if (!autoCommit) {
connection.setAutoCommit(false);
}
preparation.prepareExternalFunctions(parsed.sql(), new SpectrumSession(context.accountId(),
context.clusterKey(), context.databaseName(), context.iamRoleArns(),
!connection.getAutoCommit()), backend, positional, null);
}
} else if (parsed.parameterOrder().isEmpty()) {
handled = preparation.prepare(parsed.sql(), session, backend);
} else {
handled = preparation.prepare(parsed.sql(), session, backend, positional);
}
if (handled) {
stored.status = RedshiftDataStatementStore.Status.FINISHED;
return;
}
udfPrepared = usesUdf;
} catch (SpectrumSqlException exception) {
throw new SQLException(exception.getMessage(), exception.sqlState(), exception);
} catch (SpectrumReadException exception) {
@@ -714,13 +744,12 @@ public class RedshiftDataService implements Resettable, StoredResourceArns {
throw new SQLException("External query preparation failed: " + exception.getMessage(), "58030", exception);
}
}
String rewritten = CopyJobSql.rewrite(sql, !autoCommit || !connection.getAutoCommit());
ParsedSql parsed = RedshiftDataSqlParameters.parse(RedshiftSqlInterceptor.rewrite(rewritten));
execution.checkCancellation();
if (!autoCommit) {
connection.setAutoCommit(false);
}
long t0 = System.nanoTime();
boolean statementSucceeded = false;
try (PreparedStatement statement = connection.prepareStatement(parsed.sql())) {
execution.track(statement);
try {
@@ -740,14 +769,37 @@ public class RedshiftDataService implements Resettable, StoredResourceArns {
stored.hasResultSet = false;
stored.resultRows = Math.max(statement.getUpdateCount(), 0);
}
statementSucceeded = true;
} finally {
execution.untrack(statement);
}
} finally {
if (udfPrepared && (statementSucceeded || connection.getAutoCommit()) && !connection.isClosed()) {
try {
preparation.resetUdfState(new RedshiftDataBackendSql(connection, execution));
} catch (RuntimeException ignored) {
// Best-effort cleanup so a subsequent statement on a retained session cannot see stale UDF state.
}
}
}
stored.durationNanos = System.nanoTime() - t0;
stored.status = RedshiftDataStatementStore.Status.FINISHED;
}
private static List<String> positionalParameters(List<String> order, Map<String, String> valuesByName) {
if (order.isEmpty()) {
return List.of();
}
List<String> values = new ArrayList<>(order.size());
for (String name : order) {
if (!valuesByName.containsKey(name)) {
return null;
}
values.add(valuesByName.get(name));
}
return values;
}
private ObjectNode executeResponse(RedshiftDataStatementStore.StoredStatement stored) {
ObjectNode response = objectMapper.createObjectNode();
response.put("Id", stored.id);