diff --git a/docs/services/redshift.md b/docs/services/redshift.md index f206451aa3..f9fbce1018 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -1214,14 +1214,31 @@ role, volatility and batch options. `CREATE OR REPLACE` replaces only a function the same name with other argument types is a separate function. `DROP FUNCTION` removes both the stub and the registration; a `DROP FUNCTION` of any function Floci does not track is left to PostgreSQL. -- **Calling the function is not supported yet.** The stub refuses every call with SQLSTATE `0A000`; invoking Lambda - from SQL is a later change. Creating and dropping the function work today. +- **Calling the function works over both the PostgreSQL wire protocol (Simple and Extended Query) and the Redshift Data API.** + Before executing a statement that references a registered external function, Floci runs bounded collect passes (inside a + rolled-back savepoint, or a PL/pgSQL subtransaction for Extended Query), batches the collected argument tuples + according to `MAX_BATCH_ROWS` and `MAX_BATCH_SIZE`, invokes Lambda via the documented Redshift JSON contract (with + `RETRY_TIMEOUT` backoff on throttling), and caches the results in a trigger-guarded session temp table for the + statement's execution. In autocommit the collect passes and the statement share one transaction, so transaction-time + arguments such as `now()` and `current_timestamp` keep the value Lambda was called with. +- Nested calls (such as `outer_udf(inner_udf(x))`), `WHERE` filters, `PreparedStatement` bind parameters (including + binary-format parameters and interleaved bound portals), Data API named parameters, explicit transactions + (`BEGIN` / `COMMIT` / `ROLLBACK`), and write statements (`INSERT ... SELECT`, `UPDATE`, `DELETE`) are supported. Write + statements whose target table enforces a `NOT NULL` or `CHECK` constraint that rejects `NULL` during the collect pass + will fail with PostgreSQL's constraint error. +- Multi-statement queries, transaction-control statements (`BEGIN`, `COMMIT`, `ROLLBACK`, `SAVEPOINT`), procedural blocks + (`DO`, `CALL`), and volatile argument expressions (`nextval`, `setval`, `random`, `clock_timestamp`, + `statement_timestamp`, `timeofday`, `gen_random_uuid`, `txid_current`) cannot be combined with external function calls and fail with SQLSTATE `0A000`. +- Results are cached per statement only, never across statements, for both `STABLE` and `VOLATILE` functions; execute + mode and cached rows are cleared after each statement. - Argument and return types are `SMALLINT`, `INTEGER`, `BIGINT`, `DECIMAL`, `REAL`, `DOUBLE PRECISION`, `CHAR`, `VARCHAR`, `BOOLEAN`, `DATE` and `TIMESTAMP`, with their aliases. Any other type is refused with `0A000`. - `VOLATILE` or `STABLE` is required, and `IMMUTABLE` is refused with `0A000`, as Redshift does not support it for Lambda UDFs. `IAM_ROLE DEFAULT` is refused with `0A000`. - `MAX_BATCH_SIZE` takes `KB` or `MB` (`KB` when omitted) between 1 KB and 5 MB, and `MAX_BATCH_ROWS` is at least 1. - The defaults are the documented 20000 ms, 2147483647 rows and 5 MB. The options are stored, and not applied yet. + The defaults are the documented 20000 ms, 2147483647 rows and 5 MB. +- When IAM enforcement is enabled, the function's `IAM_ROLE` must trust `redshift.amazonaws.com` and be allowed to call + `lambda:InvokeFunction` on the target Lambda function; refusals fail with SQLSTATE `42501`. - An unqualified name is created in the session's current schema (`search_path`), failing with `3F000` if no schema is selected, and unqualified `DROP FUNCTION` resolves through `search_path`. The role and the Lambda function are not checked at creation. diff --git a/src/main/java/io/floci/aws/core/common/PostgresWire.java b/src/main/java/io/floci/aws/core/common/PostgresWire.java index 1ba2da479b..4aa60a9f37 100644 --- a/src/main/java/io/floci/aws/core/common/PostgresWire.java +++ b/src/main/java/io/floci/aws/core/common/PostgresWire.java @@ -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 dataRowValues(byte[] body) { + if (body == null || body.length < 2) { + return List.of(); + } + int count = ((body[0] & 0xFF) << 8) | (body[1] & 0xFF); + List 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. */ diff --git a/src/main/java/io/floci/aws/services/redshift/proxy/CopyBackendSession.java b/src/main/java/io/floci/aws/services/redshift/proxy/CopyBackendSession.java index ad9c6266e7..7b893e5697 100644 --- a/src/main/java/io/floci/aws/services/redshift/proxy/CopyBackendSession.java +++ b/src/main/java/io/floci/aws/services/redshift/proxy/CopyBackendSession.java @@ -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; diff --git a/src/main/java/io/floci/aws/services/redshift/proxy/PostgresWireDecoder.java b/src/main/java/io/floci/aws/services/redshift/proxy/PostgresWireDecoder.java index 213a309d4a..a6c3cee4b6 100644 --- a/src/main/java/io/floci/aws/services/redshift/proxy/PostgresWireDecoder.java +++ b/src/main/java/io/floci/aws/services/redshift/proxy/PostgresWireDecoder.java @@ -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 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 diff --git a/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridge.java b/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridge.java index 828ce0c8fd..eea4dc10b0 100644 --- a/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridge.java +++ b/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridge.java @@ -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 relationalStatements = new HashMap<>(); + private final Map relationalPortals = new HashMap<>(); private final ExtendedQuerySession session = new ExtendedQuerySession(); private final Map spectrumStatements = new HashMap<>(); private final Map 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 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 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 parameterValues; + private final BackendSql.RawParameters rawParameters; + private boolean prepared; + + private BoundPortal(RelationalStatement statement, List 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; diff --git a/src/main/java/io/floci/aws/services/redshift/proxy/S3CopySimulator.java b/src/main/java/io/floci/aws/services/redshift/proxy/S3CopySimulator.java index 2e42302b7a..273f66e0eb 100644 --- a/src/main/java/io/floci/aws/services/redshift/proxy/S3CopySimulator.java +++ b/src/main/java/io/floci/aws/services/redshift/proxy/S3CopySimulator.java @@ -784,24 +784,6 @@ public final class S3CopySimulator { return CopyRecordTransformer.ColumnKind.OTHER; } - static List parseDataRow(byte[] body) { - int count = ((body[0] & 0xFF) << 8) | (body[1] & 0xFF); - List 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 values = parseDataRow(msg.body()); + List values = PostgresWire.dataRowValues(msg.body()); if (!values.isEmpty() && values.get(0) != null) { cols.add(columnInfo(values)); } diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/BackendSql.java b/src/main/java/io/floci/aws/services/redshift/spectrum/BackendSql.java index 66819bd40c..baf6da3b8e 100644 --- a/src/main/java/io/floci/aws/services/redshift/spectrum/BackendSql.java +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/BackendSql.java @@ -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 resolveParameterTypeOids(String sql, List 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 queryString(String sql, RawParameters parameters) { + return queryString(sql); + } + + /** + * Raw PostgreSQL Bind parameter section and type OIDs, preserving binary-format values verbatim. + */ + record RawParameters(List 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> 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 parameters) { + execute(sql); + } + long copyIn(String copySql, InputStream data); } diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/LambdaUdfEvaluator.java b/src/main/java/io/floci/aws/services/redshift/spectrum/LambdaUdfEvaluator.java new file mode 100644 index 0000000000..c1f9dea9c7 --- /dev/null +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/LambdaUdfEvaluator.java @@ -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 DISALLOWED_LEADING_KEYWORDS = Set.of( + "begin", "start", "commit", "end", "rollback", "abort", "savepoint", "release", "prepare", "do", "call"); + private static final Set 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 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 registered = functions.list( + session.accountId(), session.clusterKey(), session.databaseName()); + if (registered.isEmpty()) { + return false; + } + List 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 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 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 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 parameters, + String clusterRegion) { + return prepare(sql, session, backend, parameters, null, clusterRegion); + } + + public boolean prepare(String sql, SpectrumSession session, BackendSql backend, List 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 textParams = parameters == null ? List.of() : parameters; + for (int round = 0; round < MAX_ROUNDS; round++) { + List> 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> 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> pending, SpectrumSession session, BackendSql backend, + String clusterRegion, String user, long queryId) { + Map> byFunction = new LinkedHashMap<>(); + for (List 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> entry : byFunction.entrySet()) { + String fnKey = entry.getKey(); + List 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> rows = new ArrayList<>(argsJsonList.size()); + for (String argsJson : argsJsonList) { + rows.add(decodeArgs(argsJson)); + } + List results = invoker.invoke(binding, session, clusterRegion, user, queryId, rows); + storeResults(backend, fnKey, argsJsonList, results); + } + } + + private static void validateCollectableSql(String sql) { + List 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> collectRound(String sql, List parameters, BackendSql backend, + boolean useSavepoint) { + if (useSavepoint) { + backend.execute("SAVEPOINT _floci_udf_collect"); + } else { + backend.execute("BEGIN"); + } + List> 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 argsJsonList, + List 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 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 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> 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> 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 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 resolvedOids; + private final BackendSql.RawParameters boundParameters; + private final String callSql; + + private SubtransactionCollector(String fnName, List 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 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> 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); + } + } +} diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/PostgresBackendSession.java b/src/main/java/io/floci/aws/services/redshift/spectrum/PostgresBackendSession.java index c1ed92634a..b9ab46bc2c 100644 --- a/src/main/java/io/floci/aws/services/redshift/spectrum/PostgresBackendSession.java +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/PostgresBackendSession.java @@ -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> 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> awaitRows(PostgresWireDecoder decoder) throws IOException { + SpectrumReadException failure = null; + List> 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 row = PostgresWire.dataRowValues(body); + return row.isEmpty() ? null : row.get(0); } private static long rowCount(String tag) { diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/PostgresExtendedBackendSession.java b/src/main/java/io/floci/aws/services/redshift/spectrum/PostgresExtendedBackendSession.java index 0c63d91016..ad07d9dab0 100644 --- a/src/main/java/io/floci/aws/services/redshift/spectrum/PostgresExtendedBackendSession.java +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/PostgresExtendedBackendSession.java @@ -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 resolveParameterTypeOids(String sql, List 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 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 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 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> 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 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 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 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 awaitParameterDescriptionClosed() throws IOException { + List 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 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 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> awaitRowsClosed() throws IOException { + List> 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 { diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumQueryPreparation.java b/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumQueryPreparation.java index e42da4a9d9..d1b9323f29 100644 --- a/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumQueryPreparation.java +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumQueryPreparation.java @@ -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 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 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 invoke(ExternalFunctionBinding function, SpectrumSession session, String clusterRegion, + String user, long queryId, List> 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 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 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 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 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 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 schemas = bindingsOf(registry, session).keySet(); Set 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 parameters) { + private boolean prepareInScope(String sql, SpectrumSession session, BackendSql backend, List parameters, + boolean includeUdfs) { Optional 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 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 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() diff --git a/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataBackendSql.java b/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataBackendSql.java index 3e652ec45d..64a82a9b63 100644 --- a/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataBackendSql.java +++ b/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataBackendSql.java @@ -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> 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> result = new ArrayList<>(); + while (rows.next()) { + List 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 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 { diff --git a/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataService.java b/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataService.java index fe2dc54cec..31bc649603 100644 --- a/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataService.java +++ b/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataService.java @@ -697,14 +697,44 @@ public class RedshiftDataService implements Resettable, StoredResourceArns { Connection connection, String sql, Map 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 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 positionalParameters(List order, Map valuesByName) { + if (order.isEmpty()) { + return List.of(); + } + List 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); diff --git a/src/test/java/io/floci/aws/core/common/PostgresWireTest.java b/src/test/java/io/floci/aws/core/common/PostgresWireTest.java index 2d51d464ef..85e55de089 100644 --- a/src/test/java/io/floci/aws/core/common/PostgresWireTest.java +++ b/src/test/java/io/floci/aws/core/common/PostgresWireTest.java @@ -6,6 +6,8 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -123,4 +125,24 @@ class PostgresWireTest { assertEquals(fields, PostgresWire.parseFields(framed, 5)); assertEquals(List.of('S', 'C', 'M'), List.copyOf(PostgresWire.parseFields(framed, 5).keySet())); } + + @Test + void dataRowValuesReadsTextColumnsAndNulls() throws IOException { + ByteArrayOutputStream body = new ByteArrayOutputStream(); + body.write(new byte[]{0, 3}); + body.write(PostgresWire.int32(2)); + body.write("ok".getBytes(StandardCharsets.UTF_8)); + body.write(PostgresWire.int32(-1)); + body.write(PostgresWire.int32(3)); + body.write("é!".getBytes(StandardCharsets.UTF_8)); + + assertEquals(Arrays.asList("ok", null, "é!"), PostgresWire.dataRowValues(body.toByteArray())); + assertEquals(List.of(), PostgresWire.dataRowValues(new byte[0])); + } + + @Test + void dataRowValuesRejectsATruncatedRow() { + byte[] truncated = {0, 1, 0, 0, 0, 5, 'a', 'b'}; + assertThrows(IllegalArgumentException.class, () -> PostgresWire.dataRowValues(truncated)); + } } diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftExternalFunctionIntegrationTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftExternalFunctionIntegrationTest.java index a7bf83bf84..eb6bd3471e 100644 --- a/src/test/java/io/floci/aws/services/redshift/RedshiftExternalFunctionIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftExternalFunctionIntegrationTest.java @@ -1,42 +1,72 @@ package io.floci.aws.services.redshift; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.services.lambda.LambdaService; +import io.floci.aws.services.lambda.model.InvocationType; +import io.floci.aws.services.lambda.model.InvokeResult; import io.floci.aws.services.redshift.model.Cluster; import io.floci.aws.services.redshift.spectrum.ExternalFunctionRegistry; import io.floci.aws.services.redshift.spectrum.SpectrumSession; +import io.floci.aws.services.redshiftdata.RedshiftDataService; import io.floci.aws.testing.DockerAvailability; +import io.quarkus.test.InjectMock; import io.quarkus.test.junit.QuarkusTest; import jakarta.inject.Inject; +import org.awaitility.Awaitility; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; +import java.nio.charset.StandardCharsets; 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.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; import java.util.List; +import java.util.Set; import java.util.UUID; import static io.floci.aws.services.redshift.RedshiftConnections.waitForConnection; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; -/** Creates and drops scalar Lambda UDFs through a real cluster connection. */ +/** Creates, invokes and drops scalar Lambda UDFs through both the PostgreSQL wire and Redshift Data API. */ @QuarkusTest class RedshiftExternalFunctionIntegrationTest { private static final String ACCOUNT = "000000000000"; private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/FunctionItRole"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final Set FINAL_STATUSES = Set.of("FINISHED", "FAILED", "ABORTED"); @Inject RedshiftService redshiftService; + @Inject + RedshiftDataService redshiftDataService; + @Inject ExternalFunctionRegistry functions; + @InjectMock + LambdaService lambdaService; + private String clusterId; @BeforeAll @@ -44,6 +74,12 @@ class RedshiftExternalFunctionIntegrationTest { Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker daemon must be available for Redshift integration tests"); } + @BeforeEach + void stubLambda() { + when(lambdaService.invokeArn(anyString(), any(byte[].class), any(InvocationType.class))) + .thenAnswer(invocation -> handleLambda(invocation.getArgument(0), invocation.getArgument(1))); + } + @AfterEach void cleanUp() { if (clusterId != null) { @@ -51,6 +87,45 @@ class RedshiftExternalFunctionIntegrationTest { } } + private static InvokeResult handleLambda(String functionArn, byte[] payload) throws Exception { + JsonNode request = JSON.readTree(payload); + JsonNode arguments = request.get("arguments"); + ObjectNode response = JSON.createObjectNode(); + if (functionArn.endsWith(":function:lambda_fail")) { + response.put("success", false); + response.put("error_msg", "boom from lambda"); + return okResult(response); + } + response.put("success", true); + response.put("num_records", arguments.size()); + ArrayNode results = response.putArray("results"); + for (JsonNode row : arguments) { + if (functionArn.endsWith(":function:lambda_double")) { + if (row.get(0).isNull()) { + results.addNull(); + } else { + results.add(row.get(0).asLong() * 2); + } + } else { + // lambda_sum / lambda_sum_v2: sum two integers, propagating NULL + if (row.size() >= 2 && !row.get(0).isNull() && !row.get(1).isNull()) { + long bonus = functionArn.endsWith(":function:lambda_sum_v2") ? 100 : 0; + results.add(row.get(0).asLong() + row.get(1).asLong() + bonus); + } else { + results.addNull(); + } + } + } + return okResult(response); + } + + private static InvokeResult okResult(ObjectNode response) { + InvokeResult result = new InvokeResult(); + result.setStatusCode(200); + result.setPayload(response.toString().getBytes(StandardCharsets.UTF_8)); + return result; + } + private boolean bound(String schema, String name, List argumentTypes) { SpectrumSession session = new SpectrumSession(ACCOUNT, ACCOUNT + ":" + clusterId, "dev", List.of(), false); return functions.findFunction(session, schema, name, argumentTypes).isPresent(); @@ -75,7 +150,7 @@ class RedshiftExternalFunctionIntegrationTest { @Test @Timeout(120) - void createsReplacesAndDropsAFunctionByItsSignature() throws Exception { + void createsReplacesCallsAndDropsAFunctionByItsSignature() throws Exception { clusterId = "it-fn-" + UUID.randomUUID().toString().substring(0, 8); Cluster cluster = redshiftService.createCluster(clusterId, "dc2.large", "admin", "Secret123"); try (Connection connection = waitForConnection(cluster, "admin", "Secret123"); @@ -96,8 +171,10 @@ class RedshiftExternalFunctionIntegrationTest { .replace("CREATE EXTERNAL", "CREATE OR REPLACE EXTERNAL")); assertEquals(2, stubCount(statement, "exfunc_sum")); - SQLException call = assertThrows(SQLException.class, () -> statement.executeQuery("SELECT exfunc_sum(1, 2)")); - assertEquals("0A000", call.getSQLState()); + try (ResultSet rows = statement.executeQuery("SELECT exfunc_sum(1, 2)")) { + assertTrue(rows.next()); + assertEquals(103, rows.getInt(1)); + } statement.execute("DROP FUNCTION exfunc_sum(INT, INT)"); @@ -150,9 +227,10 @@ class RedshiftExternalFunctionIntegrationTest { assertEquals(1, stubCount(statement, "analytics", "exfunc_sum")); assertEquals(0, stubCount(statement, "public", "exfunc_sum")); - SQLException qualifiedCall = assertThrows(SQLException.class, - () -> statement.executeQuery("SELECT analytics.exfunc_sum(1, 2)")); - assertEquals("0A000", qualifiedCall.getSQLState()); + try (ResultSet rows = statement.executeQuery("SELECT analytics.exfunc_sum(1, 2)")) { + assertTrue(rows.next()); + assertEquals(3, rows.getInt(1)); + } statement.execute("DROP FUNCTION analytics.exfunc_sum(INT, INT)"); assertFalse(bound("analytics", "exfunc_sum", List.of("integer", "integer"))); @@ -170,4 +248,183 @@ class RedshiftExternalFunctionIntegrationTest { assertEquals("3F000", noSchema.getSQLState()); } } + + @Test + @Timeout(120) + void keepsTransactionTimeArgumentsStableInAutocommit() throws Exception { + clusterId = "it-fn-" + UUID.randomUUID().toString().substring(0, 8); + Cluster cluster = redshiftService.createCluster(clusterId, "dc2.large", "admin", "Secret123"); + String sameNow = "SELECT exfunc_sum(extract(microseconds FROM now())::int, 0) " + + "= extract(microseconds FROM now())::int"; + try (Connection connection = waitForConnection(cluster, "admin", "Secret123"); + Statement statement = connection.createStatement()) { + statement.execute(create("exfunc_sum", "INT, INT", "lambda_sum")); + statement.execute(create("exfunc_fail", "INT, INT", "lambda_fail")); + statement.execute("CREATE TABLE stamped (val INT)"); + } + + try (Connection simple = waitForConnection( + RedshiftConnections.jdbcUrl(cluster) + "?preferQueryMode=simple", "admin", "Secret123"); + Statement statement = simple.createStatement()) { + try (ResultSet rows = statement.executeQuery(sameNow)) { + assertTrue(rows.next()); + assertTrue(rows.getBoolean(1)); + } + statement.execute("INSERT INTO stamped SELECT exfunc_sum(extract(microseconds FROM current_timestamp)::int, 1)"); + SQLException failed = assertThrows(SQLException.class, + () -> statement.executeQuery("SELECT exfunc_fail(extract(microseconds FROM now())::int, 1)")); + assertEquals("XX000", failed.getSQLState()); + try (ResultSet rows = statement.executeQuery("SELECT count(*) FROM stamped")) { + assertTrue(rows.next()); + assertEquals(1, rows.getInt(1)); + } + } + + ObjectNode request = JSON.createObjectNode(); + request.put("ClusterIdentifier", clusterId); + request.put("Database", "dev"); + request.put("DbUser", "admin"); + request.put("Sql", sameNow); + String statementId = redshiftDataService.executeStatement(request, "us-east-1").get("Id").asText(); + ObjectNode described = awaitDataStatement(statementId); + assertEquals("FINISHED", described.get("Status").asText(), described.toString()); + ObjectNode result = redshiftDataService.getStatementResult(JSON.createObjectNode().put("Id", statementId)); + assertTrue(result.get("Records").get(0).get(0).get("booleanValue").asBoolean(), result.toString()); + } + + @Test + @Timeout(120) + void evaluatesNestedWhereWriteTransactionExtendedQueryAndDataApi() throws Exception { + clusterId = "it-fn-" + UUID.randomUUID().toString().substring(0, 8); + Cluster cluster = redshiftService.createCluster(clusterId, "dc2.large", "admin", "Secret123"); + try (Connection connection = waitForConnection(cluster, "admin", "Secret123"); + Statement statement = connection.createStatement()) { + statement.execute(create("exfunc_sum", "INT, INT", "lambda_sum")); + statement.execute("CREATE EXTERNAL FUNCTION exfunc_double(INT) RETURNS INT STABLE " + + "LAMBDA 'lambda_double' IAM_ROLE '" + ROLE_ARN + "'"); + statement.execute(create("exfunc_fail", "INT, INT", "lambda_fail")); + + statement.execute("CREATE TABLE nums (a INT, b INT)"); + statement.execute("INSERT INTO nums VALUES (1, 2), (10, 5), (NULL, 4)"); + + // Multi-row + WHERE + nested UDF + NULL propagation + List nested = new ArrayList<>(); + try (ResultSet rows = statement.executeQuery( + "SELECT exfunc_double(exfunc_sum(a, b)) FROM nums WHERE exfunc_sum(a, b) > 5 ORDER BY a")) { + while (rows.next()) { + nested.add(rows.getInt(1)); + } + } + assertEquals(List.of(30), nested); + + // Write statement (INSERT ... SELECT) runs collect in a rolled-back transaction so rows are inserted once + statement.execute("CREATE TABLE out_sums (val INT)"); + statement.execute("INSERT INTO out_sums SELECT exfunc_sum(a, b) FROM nums"); + List inserted = new ArrayList<>(); + try (ResultSet rows = statement.executeQuery("SELECT val FROM out_sums ORDER BY val NULLS LAST")) { + while (rows.next()) { + Object value = rows.getObject(1); + inserted.add(value == null ? null : ((Number) value).intValue()); + } + } + assertEquals(Arrays.asList(3, 15, null), inserted); + + // Explicit transaction block preserves open transaction + connection.setAutoCommit(false); + try { + try (ResultSet rows = statement.executeQuery("SELECT exfunc_sum(7, 8)")) { + assertTrue(rows.next()); + assertEquals(15, rows.getInt(1)); + } + statement.execute("INSERT INTO out_sums VALUES (99)"); + connection.rollback(); + } finally { + connection.setAutoCommit(true); + } + try (ResultSet rows = statement.executeQuery("SELECT count(*) FROM out_sums WHERE val = 99")) { + assertTrue(rows.next()); + assertEquals(0, rows.getInt(1)); + } + + // Extended query protocol with bind parameters (including NULL) + try (PreparedStatement prepared = connection.prepareStatement("SELECT exfunc_sum(?, ?)")) { + prepared.setInt(1, 20); + prepared.setInt(2, 22); + try (ResultSet rows = prepared.executeQuery()) { + assertTrue(rows.next()); + assertEquals(42, rows.getInt(1)); + } + prepared.setNull(1, Types.INTEGER); + prepared.setInt(2, 5); + try (ResultSet rows = prepared.executeQuery()) { + assertTrue(rows.next()); + assertNull(rows.getObject(1)); + } + } + + // Lambda failure surfaces as SQLSTATE XX000 + SQLException failed = assertThrows(SQLException.class, + () -> statement.executeQuery("SELECT exfunc_fail(1, 2)")); + assertEquals("XX000", failed.getSQLState()); + assertTrue(failed.getMessage().contains("boom from lambda"), failed.getMessage()); + + // Security: a data-modifying CTE cannot forge rows in pg_temp._floci_udf_cache + SQLException forged = assertThrows(SQLException.class, () -> statement.executeQuery( + "WITH forge AS (INSERT INTO pg_temp._floci_udf_cache VALUES " + + "('public.exfunc_sum(integer,integer)', '[\"9\",\"9\"]', '999') RETURNING 1) " + + "SELECT exfunc_sum(9, 9) FROM forge")); + assertEquals("42501", forged.getSQLState()); + + // Indirect call through a view after a UDF statement must not reuse stale execute mode or cache + statement.execute("CREATE VIEW v_indirect_udf AS SELECT exfunc_sum(20, 22) AS val"); + SQLException indirect = assertThrows(SQLException.class, + () -> statement.executeQuery("SELECT val FROM v_indirect_udf")); + assertEquals("0A000", indirect.getSQLState()); + + // Multi-statement Simple Query with transaction control is rejected before collect so no NULL rows commit + try (Connection simpleConn = waitForConnection( + RedshiftConnections.jdbcUrl(cluster) + "?preferQueryMode=simple", "admin", "Secret123"); + Statement simpleStmt = simpleConn.createStatement()) { + SQLException multi = assertThrows(SQLException.class, () -> simpleStmt.execute( + "BEGIN; INSERT INTO out_sums SELECT exfunc_sum(1, 2); COMMIT;")); + assertEquals("0A000", multi.getSQLState()); + } + + // Volatile argument expression (nextval) is rejected without advancing the sequence + statement.execute("CREATE SEQUENCE udf_seq START 1"); + SQLException volatileErr = assertThrows(SQLException.class, + () -> statement.executeQuery("SELECT exfunc_sum(nextval('udf_seq')::int, 1)")); + assertEquals("0A000", volatileErr.getSQLState()); + try (ResultSet rows = statement.executeQuery("SELECT nextval('udf_seq')")) { + assertTrue(rows.next()); + assertEquals(1L, rows.getLong(1)); + } + } + + // Redshift Data API with named parameters + ObjectNode request = JSON.createObjectNode(); + request.put("ClusterIdentifier", clusterId); + request.put("Database", "dev"); + request.put("DbUser", "admin"); + request.put("Sql", "SELECT exfunc_double(exfunc_sum(:a, :b)) AS total"); + ArrayNode params = request.putArray("Parameters"); + params.addObject().put("name", "a").put("value", "4"); + params.addObject().put("name", "b").put("value", "6"); + + String statementId = redshiftDataService.executeStatement(request, "us-east-1").get("Id").asText(); + ObjectNode described = awaitDataStatement(statementId); + assertEquals("FINISHED", described.get("Status").asText(), described.toString()); + + ObjectNode resultReq = JSON.createObjectNode().put("Id", statementId); + ObjectNode result = redshiftDataService.getStatementResult(resultReq); + assertEquals(20L, result.get("Records").get(0).get(0).get("longValue").asLong()); + } + + private ObjectNode awaitDataStatement(String statementId) { + ObjectNode describeReq = JSON.createObjectNode().put("Id", statementId); + return Awaitility.await().atMost(Duration.ofSeconds(30)).pollDelay(Duration.ZERO) + .pollInterval(Duration.ofMillis(50)) + .until(() -> redshiftDataService.describeStatement(describeReq), + status -> FINAL_STATUSES.contains(status.get("Status").asText())); + } } diff --git a/src/test/java/io/floci/aws/services/redshift/spectrum/LambdaUdfEvaluatorTest.java b/src/test/java/io/floci/aws/services/redshift/spectrum/LambdaUdfEvaluatorTest.java new file mode 100644 index 0000000000..58b3e006e9 --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/spectrum/LambdaUdfEvaluatorTest.java @@ -0,0 +1,278 @@ +package io.floci.aws.services.redshift.spectrum; + +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +class LambdaUdfEvaluatorTest { + private static final String ACCOUNT = "000000000000"; + private static final String CLUSTER = ACCOUNT + ":c"; + private static final String ROLE = "arn:aws:iam::000000000000:role/UdfRole"; + private static final SpectrumSession SESSION = new SpectrumSession(ACCOUNT, CLUSTER, "dev", List.of(), false); + private static final ExternalFunctionBinding SUM = new ExternalFunctionBinding( + ACCOUNT, CLUSTER, "dev", "public", "exfunc_sum", List.of("integer", "integer"), "integer", + "VOLATILE", "lambda_sum", ROLE, 20_000, Integer.MAX_VALUE, 5L * 1024 * 1024); + private static final ExternalFunctionBinding DOUBLE = new ExternalFunctionBinding( + ACCOUNT, CLUSTER, "dev", "public", "exfunc_double", List.of("integer"), "integer", + "STABLE", "lambda_double", ROLE, 20_000, Integer.MAX_VALUE, 5L * 1024 * 1024); + + private ExternalFunctionRegistry functions; + private LambdaUdfInvoker invoker; + private BackendSql backend; + private LambdaUdfEvaluator evaluator; + + @BeforeEach + void setUp() { + functions = new ExternalFunctionRegistry(AccountAwareStorageBackend.inMemory(ACCOUNT)); + functions.replace(SUM); + invoker = mock(LambdaUdfInvoker.class); + backend = mock(BackendSql.class); + when(backend.queryString(LambdaUdfEvaluator.CURRENT_USER_SQL)).thenReturn(Optional.of("alice")); + evaluator = new LambdaUdfEvaluator(functions, invoker); + } + + @Test + void rejectsNullInvokerAtConstruction() { + assertThrows(NullPointerException.class, () -> new LambdaUdfEvaluator(functions, null)); + } + + @Test + void detectsExternalFunctionCallsRespectingSchemaQualificationAndArity() { + assertThat(evaluator.referencesExternalFunction("SELECT exfunc_sum(1, 2)", SESSION), equalTo(true)); + assertThat(evaluator.referencesExternalFunction("SELECT public.EXFUNC_SUM(a, b) FROM t", SESSION), equalTo(true)); + assertThat(evaluator.referencesExternalFunction("SELECT exfunc_sum(coalesce(a, 0), b) FROM t", SESSION), + equalTo(true)); + assertThat(evaluator.referencesExternalFunction("SELECT other.exfunc_sum(1, 2)", SESSION), equalTo(false)); + assertThat(evaluator.referencesExternalFunction("SELECT exfunc_sum(1)", SESSION), equalTo(false)); + assertThat(evaluator.referencesExternalFunction("SELECT exfunc_sum(1, 2, 3)", SESSION), equalTo(false)); + assertThat(evaluator.referencesExternalFunction("SELECT 'exfunc_sum(1, 2)'", SESSION), equalTo(false)); + assertThat(evaluator.referencesExternalFunction("SELECT 1 -- exfunc_sum(1, 2)", SESSION), equalTo(false)); + assertThat(evaluator.referencesExternalFunction("SELECT exfunc_sum FROM t", SESSION), equalTo(false)); + assertThat(evaluator.referencesExternalFunction("SELECT other_fn(1, 2)", SESSION), equalTo(false)); + } + + @Test + void skipsPreparationWhenParametersAreNullOrNoFunctionIsReferenced() { + assertThat(evaluator.prepare("SELECT exfunc_sum($1, $2)", SESSION, backend, null, "us-east-1"), equalTo(false)); + assertThat(evaluator.prepare("SELECT 1", SESSION, backend, List.of(), "us-east-1"), equalTo(false)); + + verifyNoInteractions(backend, invoker); + } + + @Test + void rejectsMultiStatementAndTransactionControlSql() { + SpectrumSqlException multi = assertThrows(SpectrumSqlException.class, + () -> evaluator.prepare("BEGIN; INSERT INTO t SELECT exfunc_sum(1, 2); COMMIT;", + SESSION, backend, List.of(), "us-east-1")); + assertThat(multi.sqlState(), equalTo("0A000")); + + SpectrumSqlException callBlock = assertThrows(SpectrumSqlException.class, + () -> evaluator.prepare("CALL exfunc_sum(1, 2)", + SESSION, backend, List.of(), "us-east-1")); + assertThat(callBlock.sqlState(), equalTo("0A000")); + + // Dollar-quoted DO bodies are not detected as direct UDF calls, so execute mode is never enabled for them. + assertThat(evaluator.prepare("DO $$ BEGIN PERFORM exfunc_sum(1, 2); END $$", + SESSION, backend, List.of(), "us-east-1"), equalTo(false)); + + verifyNoInteractions(backend, invoker); + } + + @Test + void rejectsVolatileArgumentExpressions() { + SpectrumSqlException seq = assertThrows(SpectrumSqlException.class, + () -> evaluator.prepare("SELECT exfunc_sum(nextval('s'), 1)", + SESSION, backend, List.of(), "us-east-1")); + assertThat(seq.sqlState(), equalTo("0A000")); + assertThat(seq.getMessage(), containsString("nextval()")); + + SpectrumSqlException rand = assertThrows(SpectrumSqlException.class, + () -> evaluator.prepare("SELECT exfunc_sum((random() * 10)::int, 1)", + SESSION, backend, List.of(), "us-east-1")); + assertThat(rand.sqlState(), equalTo("0A000")); + assertThat(rand.getMessage(), containsString("random()")); + + SpectrumSqlException statementTime = assertThrows(SpectrumSqlException.class, + () -> evaluator.prepare("SELECT exfunc_sum(extract(second FROM statement_timestamp())::int, 1)", + SESSION, backend, List.of(), "us-east-1")); + assertThat(statementTime.sqlState(), equalTo("0A000")); + assertThat(statementTime.getMessage(), containsString("statement_timestamp()")); + + verifyNoInteractions(backend, invoker); + } + + @Test + void collectsInvokesCachesWithReadOnlyGuardAndEnablesExecuteModeInAutoCommit() { + String key = SUM.bindingName(); + when(backend.queryRows(LambdaUdfEvaluator.READ_PENDING_SQL)) + .thenReturn(List.of(List.of(key, "[\"1\",\"2\"]"), List.of(key, "[null,\"5\"]"))) + .thenReturn(List.of()); + when(invoker.invoke(eq(SUM), eq(SESSION), eq("us-east-1"), eq("alice"), anyLong(), + eq(List.of(List.of("1", "2"), Arrays.asList(null, "5"))))) + .thenReturn(Arrays.asList("3", null)); + + assertThat(evaluator.prepare("SELECT exfunc_sum(a, b) FROM t", SESSION, backend, List.of(), "us-east-1"), + equalTo(true)); + + InOrder order = inOrder(backend); + order.verify(backend).execute(LambdaUdfEvaluator.CREATE_PENDING_TABLE_SQL); + order.verify(backend).execute(LambdaUdfEvaluator.CREATE_CACHE_TABLE_SQL); + order.verify(backend).execute(LambdaUdfEvaluator.CREATE_CACHE_GUARD_FN_SQL); + order.verify(backend).execute(LambdaUdfEvaluator.CREATE_CACHE_GUARD_TRIGGER_SQL); + order.verify(backend).execute(LambdaUdfEvaluator.DISABLE_CACHE_GUARD_SQL); + order.verify(backend).execute(LambdaUdfEvaluator.TRUNCATE_CACHE_SQL); + order.verify(backend).execute(LambdaUdfEvaluator.ENABLE_CACHE_GUARD_SQL); + order.verify(backend).execute("BEGIN"); + order.verify(backend).execute(LambdaUdfEvaluator.SET_COLLECT_MODE_SQL); + order.verify(backend).execute("SELECT exfunc_sum(a, b) FROM t", List.of()); + order.verify(backend).queryRows(LambdaUdfEvaluator.READ_PENDING_SQL); + order.verify(backend).execute("ROLLBACK"); + order.verify(backend).execute(LambdaUdfEvaluator.DISABLE_CACHE_GUARD_SQL); + order.verify(backend).execute(argThat(sql -> sql.startsWith("INSERT INTO pg_temp._floci_udf_cache") + && sql.contains("E'3'") && sql.contains(", NULL)"))); + order.verify(backend).execute(LambdaUdfEvaluator.ENABLE_CACHE_GUARD_SQL); + order.verify(backend).execute("BEGIN"); + order.verify(backend).execute(LambdaUdfEvaluator.SET_COLLECT_MODE_SQL); + order.verify(backend).execute("SELECT exfunc_sum(a, b) FROM t", List.of()); + order.verify(backend).queryRows(LambdaUdfEvaluator.READ_PENDING_SQL); + order.verify(backend).execute("ROLLBACK"); + order.verify(backend).execute(LambdaUdfEvaluator.SET_EXECUTE_MODE_SQL); + } + + @Test + void runsMultipleCollectRoundsForNestedCalls() { + functions.replace(DOUBLE); + String sumKey = SUM.bindingName(); + String doubleKey = DOUBLE.bindingName(); + when(backend.queryRows(LambdaUdfEvaluator.READ_PENDING_SQL)) + .thenReturn(List.of(List.of(sumKey, "[\"2\",\"3\"]"))) + .thenReturn(List.of(List.of(doubleKey, "[\"5\"]"))) + .thenReturn(List.of()); + when(invoker.invoke(eq(SUM), eq(SESSION), eq("us-east-1"), eq("alice"), anyLong(), + eq(List.of(List.of("2", "3"))))) + .thenReturn(List.of("5")); + when(invoker.invoke(eq(DOUBLE), eq(SESSION), eq("us-east-1"), eq("alice"), anyLong(), + eq(List.of(List.of("5"))))) + .thenReturn(List.of("10")); + + evaluator.prepare("SELECT exfunc_double(exfunc_sum(2, 3))", SESSION, backend, List.of(), "us-east-1"); + + verify(invoker, times(1)).invoke(eq(SUM), any(), anyString(), anyString(), anyLong(), anyList()); + verify(invoker, times(1)).invoke(eq(DOUBLE), any(), anyString(), anyString(), anyLong(), anyList()); + verify(backend).execute(LambdaUdfEvaluator.SET_EXECUTE_MODE_SQL); + } + + @Test + void usesSavepointInsideExplicitTransaction() { + SpectrumSession inTx = new SpectrumSession(ACCOUNT, CLUSTER, "dev", List.of(), true); + when(backend.queryRows(LambdaUdfEvaluator.READ_PENDING_SQL)).thenReturn(List.of()); + + evaluator.prepare("SELECT exfunc_sum(1, 2)", inTx, backend, List.of(), "us-east-1"); + + InOrder txOrder = inOrder(backend); + txOrder.verify(backend).execute("SAVEPOINT _floci_udf_collect"); + txOrder.verify(backend).execute("ROLLBACK TO SAVEPOINT _floci_udf_collect"); + txOrder.verify(backend).execute("RELEASE SAVEPOINT _floci_udf_collect"); + verify(backend, never()).execute("BEGIN"); + verify(backend, never()).execute("ROLLBACK"); + } + + @Test + void usesSubtransactionCollectorAndRawBinaryParametersForExtendedQuery() { + BackendSql extended = mock(BackendSql.class); + when(extended.usesSubtransactionCollect()).thenReturn(true); + when(extended.queryString(LambdaUdfEvaluator.CURRENT_USER_SQL)).thenReturn(Optional.of("alice")); + when(extended.resolveParameterTypeOids(eq("SELECT exfunc_sum($1, $2)"), anyList(), eq(2))) + .thenReturn(List.of(23, 23)); + String key = SUM.bindingName(); + String pendingJson = "[[\"" + key + "\",\"[\\\"10\\\",\\\"20\\\"]\"]]"; + when(extended.queryString(argThat(sql -> sql != null && sql.startsWith("SELECT pg_temp._floci_udf_collect_")), + any(BackendSql.RawParameters.class))) + .thenReturn(Optional.of(pendingJson)) + .thenReturn(Optional.of("[]")); + when(invoker.invoke(eq(SUM), eq(SESSION), eq("us-east-1"), eq("alice"), anyLong(), + eq(List.of(List.of("10", "20"))))) + .thenReturn(List.of("30")); + + byte[] rawBind = new byte[]{0, 1, 0, 1, 0, 2, 0, 0, 0, 4, 0, 0, 0, 10, 0, 0, 0, 4, 0, 0, 0, 20}; + BackendSql.RawParameters raw = new BackendSql.RawParameters(List.of(23, 23), 2, rawBind); + + evaluator.prepare("SELECT exfunc_sum($1, $2)", SESSION, extended, List.of("10", "20"), raw, "us-east-1"); + + verify(extended, never()).execute("SAVEPOINT _floci_udf_collect"); + verify(extended, never()).execute("BEGIN"); + verify(extended).resolveParameterTypeOids("SELECT exfunc_sum($1, $2)", List.of(23, 23), 2); + verify(extended).execute(argThat(sql -> sql.contains("CREATE FUNCTION pg_temp._floci_udf_collect_") + && sql.contains("pg_catalog.format_type(23, -1)") + && sql.contains("USING p1, p2"))); + verify(extended, times(2)).queryString( + argThat(sql -> sql != null && sql.startsWith("SELECT pg_temp._floci_udf_collect_")), + argThat(params -> params != null && params.count() == 2 + && Arrays.equals(params.bindSection(), rawBind))); + verify(extended).execute(argThat(sql -> sql.contains("DROP FUNCTION IF EXISTS pg_temp._floci_udf_collect_"))); + verify(extended).execute(LambdaUdfEvaluator.SET_EXECUTE_MODE_SQL); + } + + @Test + void resetStateClearsModeAndCache() { + evaluator.resetState(backend); + + InOrder order = inOrder(backend); + order.verify(backend).execute(LambdaUdfEvaluator.RESET_MODE_SQL); + order.verify(backend).execute(LambdaUdfEvaluator.RESET_CACHE_SQL); + } + + @Test + void rollsBackCollectTransactionWhenCollectQueryFails() { + doThrow(new SpectrumReadException("42P01", "relation \"missing\" does not exist")) + .when(backend).execute("SELECT exfunc_sum(a, b) FROM missing", List.of()); + + SpectrumReadException error = assertThrows(SpectrumReadException.class, + () -> evaluator.prepare("SELECT exfunc_sum(a, b) FROM missing", SESSION, backend, List.of(), "us-east-1")); + + assertThat(error.sqlState(), equalTo("42P01")); + verify(backend).execute("BEGIN"); + verify(backend).execute("ROLLBACK"); + verify(backend, never()).execute(LambdaUdfEvaluator.SET_EXECUTE_MODE_SQL); + } + + @Test + void stopsAfterMaximumNestingRounds() { + String key = SUM.bindingName(); + when(backend.queryRows(LambdaUdfEvaluator.READ_PENDING_SQL)) + .thenReturn(List.of(List.of(key, "[\"1\",\"2\"]"))); + when(invoker.invoke(eq(SUM), any(), anyString(), anyString(), anyLong(), anyList())) + .thenReturn(List.of("3")); + + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> evaluator.prepare("SELECT exfunc_sum(1, 2)", SESSION, backend, List.of(), "us-east-1")); + + assertThat(error.sqlState(), equalTo("54001")); + assertThat(error.getMessage(), containsString(String.valueOf(LambdaUdfEvaluator.MAX_ROUNDS))); + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/spectrum/PostgresBackendSessionTest.java b/src/test/java/io/floci/aws/services/redshift/spectrum/PostgresBackendSessionTest.java index 210fac8a6e..2df6f1a2cb 100644 --- a/src/test/java/io/floci/aws/services/redshift/spectrum/PostgresBackendSessionTest.java +++ b/src/test/java/io/floci/aws/services/redshift/spectrum/PostgresBackendSessionTest.java @@ -397,4 +397,79 @@ class PostgresBackendSessionTest { executor.shutdownNow(); } } + + @Test + void extendedResolveParameterTypeOidsUsesDescribeWhenOidsMissing() throws Exception { + try (ServerSocket listener = new ServerSocket(0); + Socket backend = new Socket("localhost", listener.getLocalPort())) { + ExecutorService executor = Executors.newSingleThreadExecutor(); + Future messages = executor.submit(() -> { + try (Socket socket = listener.accept()) { + StringBuilder types = new StringBuilder(); + Frame frame; + do { + frame = readFrame(socket.getInputStream()); + types.append(frame.type()); + } while (frame.type() != 'H'); + send(socket.getOutputStream(), '1', new byte[0]); + // ParameterDescription: 2 parameters, OID 23 (int4) and OID 701 (float8) + send(socket.getOutputStream(), 't', new byte[]{ + 0, 2, + 0, 0, 0, 23, + 0, 0, 2, (byte) 189 + }); + send(socket.getOutputStream(), 'n', new byte[0]); + send(socket.getOutputStream(), '3', new byte[0]); + return types.toString(); + } + }); + PostgresExtendedBackendSession session = new PostgresExtendedBackendSession(backend); + assertEquals(List.of(23, 701), session.resolveParameterTypeOids("SELECT f($1, $2)", List.of(), 2)); + assertEquals("PDCH", messages.get()); + // Already-known non-zero OIDs return directly without a round trip. + assertEquals(List.of(23, 701), session.resolveParameterTypeOids("SELECT f($1, $2)", List.of(23, 701), 2)); + executor.shutdownNow(); + } + } + + @Test + void extendedQueryStringWithRawParametersForwardsBinaryBindSectionVerbatim() throws Exception { + byte[] binaryBindSection = new byte[]{0, 1, 0, 1, 0, 1, 0, 0, 0, 4, 0, 0, 0, 42}; + try (ServerSocket listener = new ServerSocket(0); + Socket backend = new Socket("localhost", listener.getLocalPort())) { + ExecutorService executor = Executors.newSingleThreadExecutor(); + Future capturedBind = executor.submit(() -> { + try (Socket socket = listener.accept()) { + byte[] bindBody = null; + Frame frame; + do { + frame = readFrame(socket.getInputStream()); + if (frame.type() == 'B') { + bindBody = frame.body(); + } + } while (frame.type() != 'H'); + send(socket.getOutputStream(), '1', new byte[0]); + send(socket.getOutputStream(), '2', new byte[0]); + send(socket.getOutputStream(), 'D', dataRow(List.of("[]"))); + send(socket.getOutputStream(), 'C', "SELECT 1\0".getBytes(StandardCharsets.UTF_8)); + send(socket.getOutputStream(), '3', new byte[0]); + send(socket.getOutputStream(), '3', new byte[0]); + return bindBody; + } + }); + BackendSql.RawParameters raw = new BackendSql.RawParameters(List.of(23), 1, binaryBindSection); + Optional result = new PostgresExtendedBackendSession(backend) + .queryString("SELECT pg_temp._floci_udf_collect($1)", raw); + assertEquals(Optional.of("[]"), result); + byte[] bindBody = capturedBind.get(); + // Bind body ends with binaryBindSection + resultFormatCount (0x00, 0x00) + int offset = bindBody.length - binaryBindSection.length - 2; + for (int i = 0; i < binaryBindSection.length; i++) { + assertEquals(binaryBindSection[i], bindBody[offset + i]); + } + assertEquals(0, bindBody[bindBody.length - 2]); + assertEquals(0, bindBody[bindBody.length - 1]); + executor.shutdownNow(); + } + } } diff --git a/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumExternalFunctionPreparationTest.java b/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumExternalFunctionPreparationTest.java index 6fa3fa64a6..8b9a3bbecc 100644 --- a/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumExternalFunctionPreparationTest.java +++ b/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumExternalFunctionPreparationTest.java @@ -42,11 +42,15 @@ class SpectrumExternalFunctionPreparationTest { KinesisStreamingViews views = new KinesisStreamingViews( new KinesisViewRegistry(AccountAwareStorageBackend.inMemory(ACCOUNT)), null, null, null, Clock.systemUTC()); + MskStreamingViews mskViews = new MskStreamingViews( + new MskViewRegistry(AccountAwareStorageBackend.inMemory(ACCOUNT)), + null, null, null, null, Clock.systemUTC()); + LambdaUdfEvaluator udfEvaluator = new LambdaUdfEvaluator(functions, mock(LambdaUdfInvoker.class)); preparation = new SpectrumQueryPreparation(mock(ExternalCatalogRegistry.class), new KinesisSchemaRegistry(AccountAwareStorageBackend.inMemory(ACCOUNT)), new MskSchemaRegistry(AccountAwareStorageBackend.inMemory(ACCOUNT)), functions, - mock(ExternalTableMaterializer.class), new ExternalStatementParser(), glue, - new ExternalMetadataWriter(glue, new ObjectMapper()), new ExternalCatalogLocks(), views, + udfEvaluator, mock(ExternalTableMaterializer.class), new ExternalStatementParser(), glue, + new ExternalMetadataWriter(glue, new ObjectMapper()), new ExternalCatalogLocks(), views, mskViews, (accountId, clusterIdentifier) -> null); } @@ -55,13 +59,15 @@ class SpectrumExternalFunctionPreparationTest { } @Test - void createsAStubThatRefusesCallsAndRemembersTheDeclaration() { + void createsAStubThatEvaluatesThroughTheSessionTablesAndRemembersTheDeclaration() { assertThat(preparation.handlesDdl(CREATE, SESSION), equalTo(true)); assertThat(preparation.commandTag(CREATE), equalTo("CREATE FUNCTION")); assertThat(preparation.prepare(CREATE, SESSION, backend), equalTo(true)); verify(backend).execute(argThat(sql -> sql.startsWith("CREATE FUNCTION \"public\".\"exfunc_sum\"(integer, integer) " - + "RETURNS integer LANGUAGE plpgsql VOLATILE AS E'BEGIN RAISE EXCEPTION") + + "RETURNS integer LANGUAGE plpgsql VOLATILE AS E'DECLARE ") + && sql.contains("pg_temp._floci_udf_pending") + && sql.contains("pg_temp._floci_udf_cache") && sql.contains("USING ERRCODE = ''0A000''"))); ExternalFunctionBinding binding = bound("public", "exfunc_sum", List.of("integer", "integer")).orElseThrow(); assertThat(binding.lambdaFunction(), equalTo("lambda_sum")); @@ -77,8 +83,9 @@ class SpectrumExternalFunctionPreparationTest { + "LAMBDA 'now' IAM_ROLE '" + ROLE + "'", SESSION, backend); verify(backend).execute(argThat(sql -> sql.startsWith("CREATE FUNCTION \"Sales\".\"f_now\"() " - + "RETURNS character varying(8) LANGUAGE plpgsql STABLE"))); - assertThat(bound("Sales", "f_now", List.of()).isPresent(), equalTo(true)); + + "RETURNS character varying(8) LANGUAGE plpgsql VOLATILE"))); + ExternalFunctionBinding binding = bound("Sales", "f_now", List.of()).orElseThrow(); + assertThat(binding.volatility(), equalTo("STABLE")); } @Test @@ -231,7 +238,7 @@ class SpectrumExternalFunctionPreparationTest { preparation.prepare(CREATE, SESSION, backend); verify(backend).execute(argThat(sql -> sql.contains("public.exfunc_sum") - && sql.contains("invoking Lambda from SQL is not supported yet"))); + && sql.contains("cannot be called directly"))); } @Test diff --git a/src/test/java/io/floci/aws/services/redshiftdata/RedshiftDataServiceTest.java b/src/test/java/io/floci/aws/services/redshiftdata/RedshiftDataServiceTest.java index ee761e2346..a5e0bb1656 100644 --- a/src/test/java/io/floci/aws/services/redshiftdata/RedshiftDataServiceTest.java +++ b/src/test/java/io/floci/aws/services/redshiftdata/RedshiftDataServiceTest.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.redshift.spectrum.BackendSql; import io.floci.aws.services.redshift.spectrum.SpectrumQueryPreparation; import io.floci.aws.services.redshift.spectrum.SpectrumReadException; import io.floci.aws.services.redshift.spectrum.SpectrumSession; @@ -18,6 +19,7 @@ import org.junit.jupiter.params.provider.ValueSource; import java.sql.Connection; import java.sql.DriverManager; +import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; @@ -36,6 +38,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -163,6 +166,37 @@ class RedshiftDataServiceTest { assertEquals("S3 access denied", described.path("Error").asText()); } + @Test + void externalFunctionCallsArePreparedInTheStatementsOwnTransaction() throws SQLException { + try (Connection connection = DriverManager.getConnection(jdbcUrl, "sa", ""); + Statement statement = connection.createStatement()) { + statement.execute("CREATE TABLE udf_marker (id int)"); + } + String succeeds = "SELECT 1"; + String fails = "SELECT * FROM udf_missing_table"; + for (String sql : List.of(succeeds, fails)) { + when(preparation.referencesExternalFunction(eq(sql), any())).thenReturn(true); + when(preparation.prepareExternalFunctions(eq(sql), any(), any(), any(), any())).thenAnswer(invocation -> { + invocation.getArgument(2).execute("INSERT INTO udf_marker VALUES (1)"); + return true; + }); + } + + String finished = service.executeStatement(req(succeeds), REGION).path("Id").asText(); + String failed = service.executeStatement(req(fails), REGION).path("Id").asText(); + + assertEquals("FINISHED", service.describeStatement(idOf(finished)).path("Status").asText()); + assertEquals("FAILED", service.describeStatement(idOf(failed)).path("Status").asText()); + verify(preparation).prepareExternalFunctions(eq(succeeds), argThat(SpectrumSession::inTransaction), any(), + eq(List.of()), isNull()); + try (Connection connection = DriverManager.getConnection(jdbcUrl, "sa", ""); + Statement statement = connection.createStatement(); + ResultSet rows = statement.executeQuery("SELECT count(*) FROM udf_marker")) { + assertTrue(rows.next()); + assertEquals(1, rows.getInt(1), "the failed statement must roll back what its collect passes wrote"); + } + } + @Test void batchPreparationUsesTransactionContext() { ObjectNode request = req("unused");