feat(redshift): register scalar Lambda UDFs with CREATE EXTERNAL FUNCTION (#9172)

CREATE [OR REPLACE] EXTERNAL FUNCTION and DROP FUNCTION are now handled on Redshift clusters.
Each function's Lambda name, IAM role, volatility and batch options are kept in
ExternalFunctionRegistry, and a plpgsql stub of the same signature is created in the backend, so
name clashes, overloads, ownership and OR REPLACE return-type rules come from PostgreSQL. OR REPLACE
replaces only a function the registry made. Calling the function raises 0A000 until the evaluator
lands.

IMMUTABLE, IAM_ROLE default and types outside the documented Lambda UDF list are refused with
0A000, malformed clauses with 42601 and out-of-range options with 22023; the clause defaults and
bounds follow the CREATE EXTERNAL FUNCTION reference. A DROP FUNCTION of a function Floci does not
track is left to PostgreSQL. Both statements fail with 25001 inside a transaction block, and an
unqualified name is created in public.

Part of #7815.
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-22 00:18:55 -04:00
1 parent 5b4bc0e44e
commit a9d0aab496
13 files changed
+1207 -14

No files matched your search

+35
View File
@@ -1132,6 +1132,41 @@ service, never through Firehose or S3.
the last view that reads the stream, so `DROP SCHEMA` without `CASCADE` works once every view is dropped.
- Refreshes of the views over one stream run one at a time.
### Scalar Lambda UDFs
`CREATE EXTERNAL FUNCTION` registers a scalar Lambda UDF, and `DROP FUNCTION` removes it.
```sql
CREATE [OR REPLACE] EXTERNAL FUNCTION exfunc_sum(INT, INT)
RETURNS INT
{ VOLATILE | STABLE }
LAMBDA 'lambda_sum'
IAM_ROLE 'arn:aws:iam::123456789012:role/LambdaUdfRole'
[RETRY_TIMEOUT 20000] [MAX_BATCH_ROWS 1000] [MAX_BATCH_SIZE 5 MB];
DROP FUNCTION exfunc_sum(INT, INT) [CASCADE | RESTRICT];
```
The statement creates a stub function of the same signature in the local database and remembers the Lambda function,
role, volatility and batch options. `CREATE OR REPLACE` replaces only a function that `CREATE EXTERNAL FUNCTION` made, with the same signature and return type; an ordinary function of that signature is refused with `42723`. An overload of
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.
- 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.
- An unqualified name is created in `public`. The role and the Lambda function are not checked at creation.
- `CREATE EXTERNAL FUNCTION` and `DROP FUNCTION` of such a function inside an explicit transaction fail with SQLSTATE
`25001`, because the registration is not part of the PostgreSQL transaction.
- Privileges on `LANGUAGE exfunc` are not modeled: any user the backend lets create a function can create one.
- `DROP SCHEMA ... CASCADE` of a schema holding such a function removes the stub. The registration is cleared by the
next `DROP FUNCTION` of it, or replaced by a new `CREATE`.
### COPY from S3
`COPY <table> [(<columns>)] FROM 's3://<bucket>/<keyOrPrefix>' [options]` sent over the Simple
@@ -0,0 +1,51 @@
package io.floci.aws.services.redshift.spectrum;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
/**
* A scalar Lambda UDF created with {@code CREATE EXTERNAL FUNCTION}. The backend holds a stub function of the same
* signature; this binding keeps what Redshift records about it and PostgreSQL has no place for.
*/
@RegisterForReflection
public record ExternalFunctionBinding(String accountId, String clusterKey, String databaseName, String schemaName,
String functionName, List<String> argumentTypes, String returnType,
String volatility, String lambdaFunction, String iamRoleArn,
long retryTimeoutMillis, int maxBatchRows, long maxBatchSizeBytes)
implements SchemaBinding {
public ExternalFunctionBinding {
SchemaBinding.require(accountId, "accountId");
SchemaBinding.require(clusterKey, "clusterKey");
SchemaBinding.require(databaseName, "databaseName");
SchemaBinding.require(schemaName, "schemaName");
SchemaBinding.require(functionName, "functionName");
SchemaBinding.require(returnType, "returnType");
SchemaBinding.require(lambdaFunction, "lambdaFunction");
SchemaBinding.require(iamRoleArn, "iamRoleArn");
if (!"STABLE".equals(volatility) && !"VOLATILE".equals(volatility)) {
throw new IllegalArgumentException("volatility must be STABLE or VOLATILE");
}
argumentTypes = List.copyOf(argumentTypes);
}
/** Keys the binding by its signature, as PostgreSQL does, so overloads of one name are separate functions. */
@Override
public String bindingName() {
return nameOf(schemaName, functionName, argumentTypes);
}
/**
* Each part is length-prefixed, so a quoted name holding a dot, a parenthesis or text that looks like an argument
* list can never read as another function's schema, name or signature.
*/
public static String nameOf(String schemaName, String functionName, List<String> argumentTypes) {
StringBuilder name = new StringBuilder(part(schemaName)).append(part(functionName));
argumentTypes.forEach(type -> name.append(part(type)));
return name.toString();
}
private static String part(String value) {
return value.length() + ":" + value + ";";
}
}
@@ -0,0 +1,33 @@
package io.floci.aws.services.redshift.spectrum;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;
import java.util.Optional;
@ApplicationScoped
public class ExternalFunctionRegistry extends SchemaBindingRegistry<ExternalFunctionBinding> {
@Inject
public ExternalFunctionRegistry(StorageFactory storageFactory) {
super(storageFactory.<ExternalFunctionBinding>create("redshift", "redshift-external-functions.json",
new TypeReference<>() { }));
}
ExternalFunctionRegistry(AccountAwareStorageBackend<ExternalFunctionBinding> bindings) {
super(bindings);
}
public Optional<ExternalFunctionBinding> findFunction(SpectrumSession session, String schemaName,
String functionName, List<String> argumentTypes) {
return find(session.accountId(), session.clusterKey(), session.databaseName(),
ExternalFunctionBinding.nameOf(schemaName, functionName, argumentTypes));
}
public void unbindFunction(ExternalFunctionBinding binding) {
unbind(binding.accountId(), binding.clusterKey(), binding.databaseName(), binding.bindingName());
}
}
@@ -0,0 +1,89 @@
package io.floci.aws.services.redshift.spectrum;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The data types a Lambda UDF takes and returns, as the Redshift documentation lists them, and the PostgreSQL name
* each maps to. Aliases collapse to one canonical name so two spellings of a signature are the same function.
*/
final class ExternalFunctionTypes {
private static final Pattern MODIFIER = Pattern.compile("\\s*\\(\\s*(\\d+)(?:\\s*,\\s*(\\d+))?\\s*\\)\\s*$");
private static final Map<String, String> CANONICAL = Map.ofEntries(
Map.entry("smallint", "smallint"), Map.entry("int2", "smallint"),
Map.entry("integer", "integer"), Map.entry("int", "integer"), Map.entry("int4", "integer"),
Map.entry("bigint", "bigint"), Map.entry("int8", "bigint"),
Map.entry("decimal", "numeric"), Map.entry("numeric", "numeric"),
Map.entry("real", "real"), Map.entry("float4", "real"),
Map.entry("double precision", "double precision"), Map.entry("float8", "double precision"),
Map.entry("float", "double precision"),
Map.entry("char", "character"), Map.entry("character", "character"), Map.entry("nchar", "character"),
Map.entry("bpchar", "character"),
Map.entry("varchar", "character varying"), Map.entry("character varying", "character varying"),
Map.entry("nvarchar", "character varying"), Map.entry("text", "text"),
Map.entry("boolean", "boolean"), Map.entry("bool", "boolean"),
Map.entry("date", "date"),
Map.entry("timestamp", "timestamp"), Map.entry("timestamp without time zone", "timestamp"));
private ExternalFunctionTypes() {
}
/** The canonical base name, with no length or precision; what identifies an argument in a signature. */
static String base(String declared) {
return resolve(declared).base();
}
/** The canonical name with the length or precision the declaration gave, for a return type. */
static String declared(String declared) {
Resolved type = resolve(declared);
return type.modifier() == null ? type.base() : type.base() + type.modifier();
}
private record Resolved(String base, String modifier) { }
private static Resolved resolve(String declared) {
String text = declared.trim().replaceAll("\\s+", " ").toLowerCase(Locale.ROOT);
String modifier = null;
int precision = -1;
int scale = -1;
Matcher matcher = MODIFIER.matcher(text);
if (matcher.find()) {
precision = Integer.parseInt(matcher.group(1));
scale = matcher.group(2) == null ? -1 : Integer.parseInt(matcher.group(2));
modifier = "(" + matcher.group(1) + (matcher.group(2) == null ? "" : "," + matcher.group(2)) + ")";
text = text.substring(0, matcher.start());
}
String base = CANONICAL.get(text);
if (base == null) {
throw new SpectrumSqlException("0A000", "Data type \"" + declared.trim()
+ "\" is not supported for a Lambda UDF");
}
if (modifier != null && !modifierFits(base, precision, scale)) {
throw new SpectrumSqlException("42601", "Invalid type modifier " + modifier + " for data type \""
+ base + "\"");
}
return new Resolved(base, modifier);
}
/** Only the types that take a length or precision accept one, within the bounds Redshift documents. */
private static boolean modifierFits(String base, int precision, int scale) {
return switch (base) {
case "numeric" -> precision >= 1 && precision <= 38 && scale <= precision;
case "character" -> scale < 0 && precision >= 1 && precision <= 4096;
case "character varying" -> scale < 0 && precision >= 1 && precision <= 65535;
default -> false;
};
}
/** True when the text names a supported type, which tells an argument name from the start of a type. */
static boolean isType(String declared) {
try {
resolve(declared);
return true;
} catch (SpectrumSqlException unsupported) {
return false;
}
}
}
@@ -8,7 +8,8 @@ import java.util.Map;
public sealed interface ExternalStatement permits ExternalStatement.CreateSchema, ExternalStatement.CreateKinesisSchema,
ExternalStatement.CreateMskSchema, ExternalStatement.CreateTable, ExternalStatement.AddPartitions,
ExternalStatement.DropSchema, ExternalStatement.DropTable, ExternalStatement.CreateStreamingView,
ExternalStatement.RefreshView, ExternalStatement.DropView {
ExternalStatement.RefreshView, ExternalStatement.DropView, ExternalStatement.CreateFunction,
ExternalStatement.DropFunction {
/** Read-only copy that keeps statement order, so Glue payloads are stable across runs. */
private static <V> Map<String, V> ordered(Map<String, V> source) {
return Collections.unmodifiableMap(new LinkedHashMap<>(source));
@@ -58,4 +59,18 @@ public sealed interface ExternalStatement permits ExternalStatement.CreateSchema
String select) implements ExternalStatement { }
record RefreshView(String viewSchema, String viewName) implements ExternalStatement { }
record DropView(String viewSchema, String viewName, boolean ifExists, boolean cascade) implements ExternalStatement { }
/**
* {@code CREATE [OR REPLACE] EXTERNAL FUNCTION}. {@code schemaName} is null when the name is unqualified, and
* {@code argumentTypes} are the canonical base type names, which is what identifies an overload.
* {@code returnType} keeps its length or precision, and {@code volatility} is {@code STABLE} or {@code VOLATILE}.
*/
record CreateFunction(String schemaName, String functionName, List<String> argumentTypes, String returnType,
String volatility, String lambdaFunction, String iamRoleArn, long retryTimeoutMillis,
int maxBatchRows, long maxBatchSizeBytes, boolean orReplace) implements ExternalStatement {
public CreateFunction { argumentTypes = List.copyOf(argumentTypes); }
}
record DropFunction(String schemaName, String functionName, List<String> argumentTypes, boolean ifExists,
boolean cascade) implements ExternalStatement {
public DropFunction { argumentTypes = List.copyOf(argumentTypes); }
}
}
@@ -9,6 +9,7 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -22,6 +23,15 @@ public class ExternalStatementParser {
private static final String NAME = "(\"(?:\"\"|[^\"])+\"|[^.;,\\s\"()]+)";
private static final Pattern CREATE_MSK_SCHEMA_HEAD = Pattern.compile(
"(?is)^\\s*CREATE\\s+EXTERNAL\\s+SCHEMA\\s+(IF\\s+NOT\\s+EXISTS\\s+)?" + NAME + "\\s+FROM\\s+MSK\\b(.*?)\\s*;?\\s*$");
private static final Pattern CREATE_FUNCTION_HEAD = Pattern.compile(
"(?is)^\\s*CREATE\\s+(OR\\s+REPLACE\\s+)?EXTERNAL\\s+FUNCTION\\s+" + NAME + "(?:\\s*\\.\\s*" + NAME + ")?\\s*\\(");
private static final Pattern DROP_FUNCTION = Pattern.compile(
"(?is)^\\s*DROP\\s+FUNCTION\\s+(IF\\s+EXISTS\\s+)?" + NAME + "(?:\\s*\\.\\s*" + NAME + ")?\\s*\\((.*)\\)"
+ "(?:\\s+(CASCADE|RESTRICT))?\\s*;?\\s*$");
private static final Set<String> FUNCTION_CLAUSES = Set.of("VOLATILE", "STABLE", "IMMUTABLE", "LAMBDA",
"IAM_ROLE", "RETRY_TIMEOUT", "MAX_BATCH_ROWS", "MAX_BATCH_SIZE");
private static final long DEFAULT_RETRY_TIMEOUT_MILLIS = 20_000L;
private static final long MAX_BATCH_SIZE_BYTES = 5L * 1024 * 1024;
private static final Pattern CREATE_TABLE_HEAD = Pattern.compile("(?is)^\\s*CREATE\\s+EXTERNAL\\s+TABLE\\s+" + NAME + "\\s*\\.\\s*" + NAME + "\\s*\\(");
private static final Pattern CREATE_VIEW = Pattern.compile("(?is)^\\s*CREATE\\s+MATERIALIZED\\s+VIEW\\s+" + NAME + "(?:\\s*\\.\\s*" + NAME + ")?\\s+(?:BACKUP\\s+(?:YES|NO)\\s+)?(?:AUTO\\s+REFRESH\\s+(YES|NO)\\s+)?AS\\s+((?:SELECT|WITH)\\b.*?)\\s*;?\\s*$");
private static final Pattern REFRESH_VIEW = Pattern.compile("(?is)^\\s*REFRESH\\s+MATERIALIZED\\s+VIEW\\s+" + NAME + "(?:\\s*\\.\\s*" + NAME + ")?\\s*;?\\s*$");
@@ -65,6 +75,14 @@ public class ExternalStatementParser {
if (msk.matches()) {
return Optional.of(parseMskSchema(identifier(msk.group(2)), msk.group(1) != null, msk.group(3)));
}
Matcher createFunction = CREATE_FUNCTION_HEAD.matcher(viewText);
if (createFunction.find()) {
return Optional.of(parseFunction(createFunction, viewText));
}
Matcher dropFunction = DROP_FUNCTION.matcher(viewText);
if (dropFunction.matches()) {
return parseDropFunction(dropFunction);
}
Matcher createView = CREATE_VIEW.matcher(viewText);
if (createView.matches()) {
if (hasStatementSeparator(createView.group(4))) {
@@ -259,6 +277,178 @@ public class ExternalStatementParser {
clusterArn, ifNotExists);
}
private static ExternalStatement.CreateFunction parseFunction(Matcher head, String text) {
int open = head.end() - 1;
int close = matchingParen(text, open);
if (close < 0) {
throw new SpectrumSqlException("42601", "Unbalanced parentheses in CREATE EXTERNAL FUNCTION");
}
List<String> argumentTypes = new ArrayList<>();
for (String argument : argumentList(text.substring(open + 1, close))) {
argumentTypes.add(ExternalFunctionTypes.base(argument));
}
String tail = text.substring(close + 1).replaceFirst("[\\s;]+$", "");
int pos = skipWhitespace(tail, 0);
int keywordEnd = readKeywordEnd(tail, pos);
if (!tail.substring(pos, keywordEnd).equalsIgnoreCase("RETURNS")) {
throw new SpectrumSqlException("42601", "CREATE EXTERNAL FUNCTION requires RETURNS");
}
pos = skipWhitespace(tail, keywordEnd);
StringBuilder returnType = new StringBuilder();
while (pos < tail.length()) {
int tokenEnd = readKeywordEnd(tail, pos);
String token = tail.substring(pos, tokenEnd);
if (FUNCTION_CLAUSES.contains(token.toUpperCase(Locale.ROOT))) {
break;
}
returnType.append(returnType.isEmpty() ? "" : " ").append(token);
pos = skipWhitespace(tail, tokenEnd);
}
if (returnType.isEmpty()) {
throw new SpectrumSqlException("42601", "CREATE EXTERNAL FUNCTION requires a RETURNS data type");
}
String volatility = null;
String lambda = null;
String iamRoleArn = null;
Long retryTimeout = null;
Long maxBatchRows = null;
Long maxBatchSize = null;
while (true) {
pos = skipWhitespace(tail, pos);
if (pos >= tail.length()) {
break;
}
int end = readKeywordEnd(tail, pos);
String keyword = tail.substring(pos, end).toUpperCase(Locale.ROOT);
pos = skipWhitespace(tail, end);
switch (keyword) {
case "VOLATILE", "STABLE" -> {
if (volatility != null) {
throw new SpectrumSqlException("42601", "Duplicate volatility clause");
}
volatility = keyword;
}
case "IMMUTABLE" -> throw new SpectrumSqlException("0A000",
"IMMUTABLE is not supported for Lambda UDFs; use STABLE or VOLATILE");
case "LAMBDA" -> {
if (lambda != null) {
throw new SpectrumSqlException("42601", "Duplicate LAMBDA clause");
}
TokenSlice slice = readValueToken(tail, pos, "LAMBDA");
pos = slice.end();
lambda = requireQuotedLiteral(slice.text(), "LAMBDA must be a single quoted function name");
}
case "IAM_ROLE" -> {
if (iamRoleArn != null) {
throw new SpectrumSqlException("42601", "Duplicate IAM_ROLE clause");
}
TokenSlice slice = readValueToken(tail, pos, "IAM_ROLE");
pos = slice.end();
iamRoleArn = roleArn(slice.text());
}
case "RETRY_TIMEOUT" -> {
if (retryTimeout != null) {
throw new SpectrumSqlException("42601", "Duplicate RETRY_TIMEOUT clause");
}
TokenSlice slice = readValueToken(tail, pos, "RETRY_TIMEOUT");
pos = slice.end();
retryTimeout = wholeNumber(slice.text(), "RETRY_TIMEOUT");
if (retryTimeout < 0) {
throw new SpectrumSqlException("22023", "RETRY_TIMEOUT must not be negative");
}
}
case "MAX_BATCH_ROWS" -> {
if (maxBatchRows != null) {
throw new SpectrumSqlException("42601", "Duplicate MAX_BATCH_ROWS clause");
}
TokenSlice slice = readValueToken(tail, pos, "MAX_BATCH_ROWS");
pos = slice.end();
maxBatchRows = wholeNumber(slice.text(), "MAX_BATCH_ROWS");
if (maxBatchRows < 1 || maxBatchRows > Integer.MAX_VALUE) {
throw new SpectrumSqlException("22023", "MAX_BATCH_ROWS must be between 1 and 2147483647");
}
}
case "MAX_BATCH_SIZE" -> {
if (maxBatchSize != null) {
throw new SpectrumSqlException("42601", "Duplicate MAX_BATCH_SIZE clause");
}
TokenSlice slice = readValueToken(tail, pos, "MAX_BATCH_SIZE");
pos = skipWhitespace(tail, slice.end());
long unit = 1024L;
int unitEnd = readKeywordEnd(tail, pos);
String unitText = tail.substring(pos, unitEnd).toUpperCase(Locale.ROOT);
if (unitText.equals("KB") || unitText.equals("MB")) {
unit = unitText.equals("MB") ? 1024L * 1024 : 1024L;
pos = skipWhitespace(tail, unitEnd);
}
long size = wholeNumber(slice.text(), "MAX_BATCH_SIZE");
if (size < 1 || size > MAX_BATCH_SIZE_BYTES / unit || size * unit < 1024L) {
throw new SpectrumSqlException("22023", "MAX_BATCH_SIZE must be between 1 KB and 5 MB");
}
maxBatchSize = size * unit;
}
default -> throw new SpectrumSqlException("42601",
"Unexpected clause in CREATE EXTERNAL FUNCTION: " + keyword);
}
}
if (volatility == null) {
throw new SpectrumSqlException("42601", "CREATE EXTERNAL FUNCTION requires VOLATILE or STABLE");
}
if (lambda == null) {
throw new SpectrumSqlException("42601", "CREATE EXTERNAL FUNCTION requires LAMBDA");
}
if (iamRoleArn == null) {
throw new SpectrumSqlException("42601", "CREATE EXTERNAL FUNCTION requires IAM_ROLE");
}
return new ExternalStatement.CreateFunction(qualifier(head.group(2), head.group(3)),
objectName(head.group(2), head.group(3)), argumentTypes,
ExternalFunctionTypes.declared(returnType.toString()), volatility, lambda, iamRoleArn,
retryTimeout == null ? DEFAULT_RETRY_TIMEOUT_MILLIS : retryTimeout,
maxBatchRows == null ? Integer.MAX_VALUE : maxBatchRows.intValue(),
maxBatchSize == null ? MAX_BATCH_SIZE_BYTES : maxBatchSize, head.group(1) != null);
}
/**
* A {@code DROP FUNCTION} is only an external one when every argument is a Lambda UDF type. Any other signature
* names a function Floci does not track, so it is left to the backend rather than refused.
*/
private static Optional<ExternalStatement> parseDropFunction(Matcher drop) {
List<String> argumentTypes = new ArrayList<>();
try {
for (String argument : argumentList(drop.group(4))) {
argumentTypes.add(dropArgumentType(argument));
}
} catch (SpectrumSqlException notExternal) {
return Optional.empty();
}
return Optional.of(new ExternalStatement.DropFunction(qualifier(drop.group(2), drop.group(3)),
objectName(drop.group(2), drop.group(3)), argumentTypes, drop.group(1) != null,
"CASCADE".equalsIgnoreCase(drop.group(5))));
}
/** DROP FUNCTION lets an argument carry a name, which plays no part in the function's identity. */
private static String dropArgumentType(String argument) {
String trimmed = argument.trim();
if (ExternalFunctionTypes.isType(trimmed)) {
return ExternalFunctionTypes.base(trimmed);
}
int nameEnd = trimmed.startsWith("\"") ? columnNameEnd(trimmed) : trimmed.indexOf(' ');
return ExternalFunctionTypes.base(nameEnd > 0 ? trimmed.substring(nameEnd) : trimmed);
}
private static long wholeNumber(String token, String clause) {
try {
return Long.parseLong(token.trim());
} catch (NumberFormatException notANumber) {
throw new SpectrumSqlException("42601", clause + " must be a whole number");
}
}
/** The items of an argument list, none for an empty one; a comma inside a length or precision stays in its item. */
private static List<String> argumentList(String list) {
return list.isBlank() ? List.of() : split(list);
}
private record TokenSlice(String text, int end) { }
private static int skipWhitespace(String text, int pos) {
@@ -32,6 +32,9 @@ import java.util.regex.Pattern;
public class SpectrumQueryPreparation {
private static final Logger LOG = Logger.getLogger(SpectrumQueryPreparation.class);
private static final String DUPLICATE_SCHEMA = "42P06";
private static final String UNDEFINED_FUNCTION = "42883";
/** Where an unqualified function lands: the default search path of a Redshift database resolves to it. */
private static final String DEFAULT_FUNCTION_SCHEMA = "public";
private static final Pattern JOIN = Pattern.compile("\\bJOIN\\b", Pattern.CASE_INSENSITIVE);
// Each batch is inserted on its own, so a view that groups or aggregates would keep a partial row per batch.
private static final Pattern AGGREGATE = Pattern.compile(
@@ -41,6 +44,7 @@ public class SpectrumQueryPreparation {
private final ExternalCatalogRegistry registry;
private final KinesisSchemaRegistry kinesisSchemas;
private final MskSchemaRegistry mskSchemas;
private final ExternalFunctionRegistry functions;
private final KinesisStreamingViews views;
private final ExternalTableMaterializer materializer;
private final ExternalStatementParser parser;
@@ -66,12 +70,13 @@ public class SpectrumQueryPreparation {
@Inject
public SpectrumQueryPreparation(ExternalCatalogRegistry registry, KinesisSchemaRegistry kinesisSchemas,
MskSchemaRegistry mskSchemas, ExternalTableMaterializer materializer,
ExternalStatementParser parser, GlueService glue, ExternalMetadataWriter metadata,
MskSchemaRegistry mskSchemas, ExternalFunctionRegistry functions,
ExternalTableMaterializer materializer, ExternalStatementParser parser,
GlueService glue, ExternalMetadataWriter metadata,
ExternalCatalogLocks catalogLocks, KinesisStreamingViews views,
Instance<RedshiftService> redshift) {
this(registry, kinesisSchemas, mskSchemas, materializer, parser, glue, metadata, catalogLocks, views,
(accountId, clusterIdentifier) -> redshift.get().clusterRegion(accountId, clusterIdentifier).orElse(null));
this(registry, kinesisSchemas, mskSchemas, functions, materializer, parser, glue, metadata, catalogLocks,
views, (accountId, clusterIdentifier) -> redshift.get().clusterRegion(accountId, clusterIdentifier).orElse(null));
}
SpectrumQueryPreparation(ExternalCatalogRegistry registry, ExternalTableMaterializer materializer,
@@ -87,7 +92,7 @@ public class SpectrumQueryPreparation {
BiFunction<String, String, String> clusterRegion) {
this(registry, kinesisSchemas,
new MskSchemaRegistry(AccountAwareStorageBackend.<MskSchemaBinding>inMemory("000000000000")),
materializer, parser, glue, metadata, catalogLocks,
inMemoryFunctions(), materializer, parser, glue, metadata, catalogLocks,
new KinesisStreamingViews(new KinesisViewRegistry(
AccountAwareStorageBackend.<KinesisViewBinding>inMemory("000000000000")),
null, null, null, Clock.systemUTC()), clusterRegion);
@@ -99,14 +104,19 @@ public class SpectrumQueryPreparation {
KinesisStreamingViews views, BiFunction<String, String, String> clusterRegion) {
this(registry, kinesisSchemas,
new MskSchemaRegistry(AccountAwareStorageBackend.<MskSchemaBinding>inMemory("000000000000")),
materializer, parser, glue, metadata, catalogLocks, views, clusterRegion);
inMemoryFunctions(), materializer, parser, glue, metadata, catalogLocks, views, clusterRegion);
}
private static ExternalFunctionRegistry inMemoryFunctions() {
return new ExternalFunctionRegistry(AccountAwareStorageBackend.<ExternalFunctionBinding>inMemory("000000000000"));
}
SpectrumQueryPreparation(ExternalCatalogRegistry registry, KinesisSchemaRegistry kinesisSchemas,
MskSchemaRegistry mskSchemas, ExternalTableMaterializer materializer,
ExternalStatementParser parser, GlueService glue, ExternalMetadataWriter metadata,
ExternalCatalogLocks catalogLocks, KinesisStreamingViews views,
BiFunction<String, String, String> clusterRegion) {
MskSchemaRegistry mskSchemas, ExternalFunctionRegistry functions,
ExternalTableMaterializer materializer, ExternalStatementParser parser,
GlueService glue, ExternalMetadataWriter metadata, ExternalCatalogLocks catalogLocks,
KinesisStreamingViews views, BiFunction<String, String, String> clusterRegion) {
this.functions = functions;
this.views = views;
this.clusterRegion = clusterRegion;
this.registry = registry;
@@ -171,6 +181,10 @@ public class SpectrumQueryPreparation {
case ExternalStatement.CreateSchema ignored -> true;
case ExternalStatement.CreateKinesisSchema ignored -> true;
case ExternalStatement.CreateMskSchema ignored -> true;
case ExternalStatement.CreateFunction ignored -> true;
case ExternalStatement.DropFunction function -> functions.findFunction(session,
schemaOrDefault(function.schemaName()), function.functionName(),
function.argumentTypes()).isPresent();
case ExternalStatement.CreateTable table -> session.inTransaction()
|| bindingsOf(registry, session).containsKey(table.schemaName())
|| bindingsOf(kinesisSchemas, session).containsKey(table.schemaName())
@@ -199,6 +213,8 @@ public class SpectrumQueryPreparation {
case ExternalStatement.CreateStreamingView ignored -> "CREATE MATERIALIZED VIEW";
case ExternalStatement.RefreshView ignored -> "REFRESH MATERIALIZED VIEW";
case ExternalStatement.DropView ignored -> "DROP MATERIALIZED VIEW";
case ExternalStatement.CreateFunction ignored -> "CREATE FUNCTION";
case ExternalStatement.DropFunction ignored -> "DROP FUNCTION";
case null, default -> "CREATE EXTERNAL";
};
}
@@ -214,6 +230,12 @@ public class SpectrumQueryPreparation {
if (statement.orElse(null) instanceof ExternalStatement.CreateMskSchema schema) {
return createMskSchema(schema, session, backend);
}
if (statement.orElse(null) instanceof ExternalStatement.CreateFunction function) {
return createFunction(function, session, backend);
}
if (statement.orElse(null) instanceof ExternalStatement.DropFunction function) {
return dropFunction(function, session, backend);
}
Map<String, KinesisSchemaBinding> kinesis = bindingsOf(kinesisSchemas, session);
Map<String, MskSchemaBinding> msk = bindingsOf(mskSchemas, session);
if (statement.orElse(null) instanceof ExternalStatement.DropSchema schema
@@ -527,6 +549,88 @@ public class SpectrumQueryPreparation {
return true;
}
/**
* 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.
*/
private boolean createFunction(ExternalStatement.CreateFunction function, SpectrumSession session,
BackendSql backend) {
rejectTransaction(session);
String schema = schemaOrDefault(function.schemaName());
ExternalFunctionBinding binding = new ExternalFunctionBinding(session.accountId(), session.clusterKey(),
session.databaseName(), schema, function.functionName(), function.argumentTypes(),
function.returnType(), function.volatility(), function.lambdaFunction(), function.iamRoleArn(),
function.retryTimeoutMillis(), function.maxBatchRows(), function.maxBatchSizeBytes());
// OR REPLACE only replaces a function this registry made: any other function of the signature is an
// ordinary one that a stub must not overwrite, so it is created plainly and the backend refuses it (42723).
// 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));
try {
functions.replace(binding);
} catch (RuntimeException exception) {
if (!replace) {
try {
backend.execute(dropStubSql(schema, function.functionName(), function.argumentTypes(), false, false));
} catch (RuntimeException cleanupFailure) {
LOG.warnv(cleanupFailure, "Could not clean up failed external function {0}", function.functionName());
}
}
throw exception;
}
return true;
}
private boolean dropFunction(ExternalStatement.DropFunction function, SpectrumSession session, BackendSql backend) {
rejectTransaction(session);
String schema = schemaOrDefault(function.schemaName());
Optional<ExternalFunctionBinding> binding = functions.findFunction(session, schema, function.functionName(),
function.argumentTypes());
if (binding.isEmpty()) {
return false;
}
try {
backend.execute(dropStubSql(schema, function.functionName(), function.argumentTypes(),
function.ifExists(), function.cascade()));
} catch (SpectrumReadException exception) {
// The stub went with its schema, so the binding describes nothing and must not outlive the failure.
if (UNDEFINED_FUNCTION.equals(exception.sqlState())) {
functions.unbindFunction(binding.get());
}
throw exception;
}
functions.unbindFunction(binding.get());
return true;
}
private static String schemaOrDefault(String schemaName) {
return schemaName == null ? DEFAULT_FUNCTION_SCHEMA : schemaName;
}
private static String stubSql(ExternalStatement.CreateFunction function, String schema, boolean replace) {
// The message is an argument, not the format string, so a % in a quoted name is not read as a placeholder.
String body = "BEGIN RAISE EXCEPTION '%', "
+ PostgresWire.quoteLiteral("External function " + schema + "." + function.functionName()
+ " cannot be called: invoking Lambda from SQL is not supported yet")
+ " USING ERRCODE = '0A000'; END";
return "CREATE " + (replace ? "OR REPLACE " : "") + "FUNCTION "
+ signature(schema, function.functionName(), function.argumentTypes())
+ " RETURNS " + function.returnType() + " LANGUAGE plpgsql " + function.volatility() + " AS "
+ PostgresWire.quoteLiteral(body);
}
private static String dropStubSql(String schema, String functionName, List<String> argumentTypes,
boolean ifExists, boolean cascade) {
return "DROP FUNCTION " + (ifExists ? "IF EXISTS " : "") + signature(schema, functionName, argumentTypes)
+ (cascade ? " CASCADE" : " RESTRICT");
}
private static String signature(String schema, String functionName, List<String> argumentTypes) {
return ExternalTableMaterializer.quote(schema) + "." + ExternalTableMaterializer.quote(functionName)
+ "(" + String.join(", ", argumentTypes) + ")";
}
/** A name is taken when any kind of external schema already holds it. */
private boolean schemaExists(SpectrumSession session, String schemaName) {
return registry.find(session.accountId(), session.clusterKey(), session.databaseName(), schemaName).isPresent()
@@ -655,6 +759,7 @@ public class SpectrumQueryPreparation {
registry.removeCluster(accountId, clusterKey);
kinesisSchemas.removeCluster(accountId, clusterKey);
mskSchemas.removeCluster(accountId, clusterKey);
functions.removeCluster(accountId, clusterKey);
views.forgetCluster(accountId, clusterKey);
materializer.forgetCluster(clusterKey);
}
@@ -0,0 +1,130 @@
package io.floci.aws.services.redshift;
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.testing.DockerAvailability;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
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.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** Creates and drops scalar Lambda UDFs through a real cluster connection. */
@QuarkusTest
class RedshiftExternalFunctionIntegrationTest {
private static final String ACCOUNT = "000000000000";
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/FunctionItRole";
@Inject
RedshiftService redshiftService;
@Inject
ExternalFunctionRegistry functions;
private String clusterId;
@BeforeAll
static void requireDocker() throws InterruptedException {
Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker daemon must be available for Redshift integration tests");
}
@AfterEach
void cleanUp() {
if (clusterId != null) {
redshiftService.deleteCluster(clusterId);
}
}
private boolean bound(String schema, String name, List<String> argumentTypes) {
SpectrumSession session = new SpectrumSession(ACCOUNT, ACCOUNT + ":" + clusterId, "dev", List.of(), false);
return functions.findFunction(session, schema, name, argumentTypes).isPresent();
}
private static int stubCount(Statement statement, String name) throws SQLException {
try (ResultSet rows = statement.executeQuery("SELECT count(*) FROM pg_proc p JOIN pg_namespace n "
+ "ON n.oid = p.pronamespace WHERE n.nspname = 'public' AND p.proname = '" + name + "'")) {
rows.next();
return rows.getInt(1);
}
}
private static String create(String name, String args, String lambda) {
return "CREATE EXTERNAL FUNCTION " + name + "(" + args + ") RETURNS INT VOLATILE LAMBDA '" + lambda
+ "' IAM_ROLE '" + ROLE_ARN + "'";
}
@Test
@Timeout(120)
void createsReplacesAndDropsAFunctionByItsSignature() 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"));
assertTrue(bound("public", "exfunc_sum", List.of("integer", "integer")));
assertEquals(1, stubCount(statement, "exfunc_sum"));
SQLException duplicate = assertThrows(SQLException.class,
() -> statement.execute(create("exfunc_sum", "INT, INT", "lambda_sum")));
assertEquals("42723", duplicate.getSQLState());
statement.execute(create("exfunc_sum", "BIGINT", "lambda_sum_big"));
assertEquals(2, stubCount(statement, "exfunc_sum"));
statement.execute(create("exfunc_sum", "INT, INT", "lambda_sum_v2")
.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());
statement.execute("DROP FUNCTION exfunc_sum(INT, INT)");
assertFalse(bound("public", "exfunc_sum", List.of("integer", "integer")));
assertTrue(bound("public", "exfunc_sum", List.of("bigint")));
assertEquals(1, stubCount(statement, "exfunc_sum"));
statement.execute("DROP FUNCTION exfunc_sum(BIGINT)");
assertFalse(bound("public", "exfunc_sum", List.of("bigint")));
assertEquals(0, stubCount(statement, "exfunc_sum"));
}
}
@Test
@Timeout(120)
void refusesToCreateAFunctionInsideATransaction() 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()) {
connection.setAutoCommit(false);
try {
SQLException rejected = assertThrows(SQLException.class,
() -> statement.execute(create("exfunc_tx", "INT", "lambda_tx")));
assertEquals("25001", rejected.getSQLState());
} finally {
connection.rollback();
connection.setAutoCommit(true);
}
assertFalse(bound("public", "exfunc_tx", List.of("integer")));
assertEquals(0, stubCount(statement, "exfunc_tx"));
}
}
}
@@ -0,0 +1,116 @@
package io.floci.aws.services.redshift.spectrum;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.core.storage.StorageFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
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.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class ExternalFunctionRegistryTest {
private static final String ACCOUNT = "000000000000";
private static final String ROLE = "arn:aws:iam::000000000000:role/R";
private static final SpectrumSession SESSION = new SpectrumSession(ACCOUNT, ACCOUNT + ":c", "dev", List.of(), false);
private ExternalFunctionRegistry registry;
@BeforeEach
@SuppressWarnings("unchecked")
void setUp() {
StorageFactory factory = mock(StorageFactory.class);
when(factory.create(eq("redshift"), eq("redshift-external-functions.json"), any(TypeReference.class)))
.thenReturn(new AccountAwareStorageBackend<ExternalFunctionBinding>(new InMemoryStorage<>(), null, ACCOUNT));
registry = new ExternalFunctionRegistry(factory);
}
private static ExternalFunctionBinding binding(String cluster, String schema, String name, List<String> args) {
return new ExternalFunctionBinding(ACCOUNT, cluster, "dev", schema, name, args, "integer", "STABLE",
"lambda_" + name, ROLE, 20_000L, Integer.MAX_VALUE, 5L * 1024 * 1024);
}
@Test
void findsAFunctionBySignatureSoOverloadsStaySeparate() {
registry.replace(binding(SESSION.clusterKey(), "public", "f", List.of("integer")));
registry.replace(binding(SESSION.clusterKey(), "public", "f", List.of("integer", "integer")));
assertThat(registry.findFunction(SESSION, "public", "f", List.of("integer")).orElseThrow().argumentTypes(),
equalTo(List.of("integer")));
assertThat(registry.findFunction(SESSION, "public", "f", List.of("integer", "integer")).isPresent(),
equalTo(true));
assertThat(registry.findFunction(SESSION, "public", "f", List.of("bigint")).isPresent(), equalTo(false));
}
@Test
void replaceOverwritesAnExistingFunctionOfTheSameSignature() {
registry.replace(binding(SESSION.clusterKey(), "public", "f", List.of("integer")));
ExternalFunctionBinding changed = new ExternalFunctionBinding(ACCOUNT, SESSION.clusterKey(), "dev", "public",
"f", List.of("integer"), "bigint", "VOLATILE", "other", ROLE, 0L, 10, 1024L);
registry.replace(changed);
assertThat(registry.findFunction(SESSION, "public", "f", List.of("integer")).orElseThrow(), equalTo(changed));
assertThat(registry.list(ACCOUNT, SESSION.clusterKey(), "dev").size(), equalTo(1));
}
@Test
void unbindsOneFunctionAndForgetsAWholeCluster() {
ExternalFunctionBinding one = binding(SESSION.clusterKey(), "public", "f", List.of("integer"));
registry.replace(one);
registry.replace(binding(SESSION.clusterKey(), "sales", "g", List.of()));
registry.replace(binding(ACCOUNT + ":other", "public", "f", List.of("integer")));
registry.unbindFunction(one);
assertThat(registry.list(ACCOUNT, SESSION.clusterKey(), "dev").stream()
.map(ExternalFunctionBinding::functionName).toList(), contains("g"));
registry.removeCluster(ACCOUNT, SESSION.clusterKey());
assertThat(registry.list(ACCOUNT, SESSION.clusterKey(), "dev"), empty());
assertThat(registry.list(ACCOUNT, ACCOUNT + ":other", "dev").size(), equalTo(1));
}
@Test
void punctuationInAQuotedNameNeverMakesTwoFunctionsShareARegistration() {
ExternalFunctionBinding dottedSchema = binding(SESSION.clusterKey(), "a.b", "c", List.of("integer"));
ExternalFunctionBinding dottedName = binding(SESSION.clusterKey(), "a", "b.c", List.of("integer"));
ExternalFunctionBinding listLikeName = binding(SESSION.clusterKey(), "public", "f(integer)", List.of());
ExternalFunctionBinding plain = binding(SESSION.clusterKey(), "public", "f", List.of("integer"));
List.of(dottedSchema, dottedName, listLikeName, plain).forEach(registry::replace);
assertThat(registry.list(ACCOUNT, SESSION.clusterKey(), "dev").size(), equalTo(4));
registry.unbindFunction(dottedSchema);
registry.unbindFunction(listLikeName);
assertThat(registry.findFunction(SESSION, "a", "b.c", List.of("integer")).isPresent(), equalTo(true));
assertThat(registry.findFunction(SESSION, "public", "f", List.of("integer")).isPresent(), equalTo(true));
assertThat(registry.findFunction(SESSION, "a.b", "c", List.of("integer")).isPresent(), equalTo(false));
assertThat(registry.findFunction(SESSION, "public", "f(integer)", List.of()).isPresent(), equalTo(false));
}
@Test
void clearForgetsEverything() {
registry.replace(binding(SESSION.clusterKey(), "public", "f", List.of()));
registry.clear();
assertThat(registry.list(ACCOUNT, SESSION.clusterKey(), "dev"), empty());
}
@Test
void rejectsABindingThatNamesNeitherVolatilityNorALambda() {
assertThrows(IllegalArgumentException.class, () -> new ExternalFunctionBinding(ACCOUNT, "c", "dev", "public",
"f", List.of(), "integer", "IMMUTABLE", "l", ROLE, 0L, 1, 1024L));
assertThrows(IllegalArgumentException.class, () -> new ExternalFunctionBinding(ACCOUNT, "c", "dev", "public",
"f", List.of(), "integer", "STABLE", " ", ROLE, 0L, 1, 1024L));
}
}
@@ -0,0 +1,193 @@
package io.floci.aws.services.redshift.spectrum;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ExternalFunctionStatementParserTest {
private static final String ROLE = "arn:aws:iam::000000000000:role/R";
private static final String BASIC = "CREATE EXTERNAL FUNCTION exfunc_sum(INT, INT) RETURNS INT VOLATILE "
+ "LAMBDA 'lambda_sum' IAM_ROLE '" + ROLE + "'";
private final ExternalStatementParser parser = new ExternalStatementParser();
private ExternalStatement.CreateFunction create(String sql) {
return (ExternalStatement.CreateFunction) parser.parse(sql).orElseThrow();
}
private String errorState(String sql) {
return assertThrows(SpectrumSqlException.class, () -> parser.parse(sql)).sqlState();
}
@Test
void parsesTheDocumentedExampleWithDefaults() {
ExternalStatement.CreateFunction function = create(BASIC + ";");
assertThat(function.schemaName(), nullValue());
assertThat(function.functionName(), equalTo("exfunc_sum"));
assertThat(function.argumentTypes(), equalTo(List.of("integer", "integer")));
assertThat(function.returnType(), equalTo("integer"));
assertThat(function.volatility(), equalTo("VOLATILE"));
assertThat(function.lambdaFunction(), equalTo("lambda_sum"));
assertThat(function.iamRoleArn(), equalTo(ROLE));
assertThat(function.orReplace(), equalTo(false));
assertThat(function.retryTimeoutMillis(), equalTo(20_000L));
assertThat(function.maxBatchRows(), equalTo(Integer.MAX_VALUE));
assertThat(function.maxBatchSizeBytes(), equalTo(5L * 1024 * 1024));
}
@Test
void parsesOrReplaceSchemaQualifiedNamesAndAFunctionWithoutArguments() {
ExternalStatement.CreateFunction function = create("create or replace external function \"Sales\".F_Now() "
+ "returns varchar(32) stable lambda 'now' iam_role '" + ROLE + "'");
assertThat(function.orReplace(), equalTo(true));
assertThat(function.schemaName(), equalTo("Sales"));
assertThat(function.functionName(), equalTo("f_now"));
assertThat(function.argumentTypes(), equalTo(List.of()));
assertThat(function.returnType(), equalTo("character varying(32)"));
assertThat(function.volatility(), equalTo("STABLE"));
}
@Test
void collapsesTypeAliasesAndDropsLengthsFromTheSignature() {
ExternalStatement.CreateFunction function = create("CREATE EXTERNAL FUNCTION f(INT2, int8, DECIMAL(10, 2), "
+ "FLOAT4, FLOAT8, NVARCHAR(20), BOOL, DATE, TIMESTAMP WITHOUT TIME ZONE, DOUBLE PRECISION, "
+ "CHAR(3)) RETURNS DECIMAL(10,2) STABLE LAMBDA 'f' IAM_ROLE '" + ROLE + "'");
assertThat(function.argumentTypes(), equalTo(List.of("smallint", "bigint", "numeric", "real",
"double precision", "character varying", "boolean", "date", "timestamp", "double precision",
"character")));
assertThat(function.returnType(), equalTo("numeric(10,2)"));
}
@Test
void readsTheBatchAndRetryOptionsInAnyOrder() {
ExternalStatement.CreateFunction function = create("CREATE EXTERNAL FUNCTION f(INT) RETURNS INT STABLE "
+ "LAMBDA 'f' MAX_BATCH_SIZE 2 MB MAX_BATCH_ROWS 100 RETRY_TIMEOUT 0 IAM_ROLE '" + ROLE + "'");
assertThat(function.maxBatchSizeBytes(), equalTo(2L * 1024 * 1024));
assertThat(function.maxBatchRows(), equalTo(100));
assertThat(function.retryTimeoutMillis(), equalTo(0L));
}
@Test
void aBatchSizeWithoutAUnitIsInKilobytes() {
ExternalStatement.CreateFunction function = create("CREATE EXTERNAL FUNCTION f(INT) RETURNS INT STABLE "
+ "LAMBDA 'f' IAM_ROLE '" + ROLE + "' MAX_BATCH_SIZE 64");
assertThat(function.maxBatchSizeBytes(), equalTo(64L * 1024));
}
@Test
void rejectsOutOfRangeOptions() {
String head = "CREATE EXTERNAL FUNCTION f(INT) RETURNS INT STABLE LAMBDA 'f' IAM_ROLE '" + ROLE + "' ";
assertThat(errorState(head + "MAX_BATCH_ROWS 0"), equalTo("22023"));
assertThat(errorState(head + "MAX_BATCH_ROWS 2147483648"), equalTo("22023"));
assertThat(errorState(head + "MAX_BATCH_SIZE 6 MB"), equalTo("22023"));
assertThat(errorState(head + "MAX_BATCH_SIZE 0 KB"), equalTo("22023"));
assertThat(errorState(head + "RETRY_TIMEOUT -1"), equalTo("22023"));
assertThat(errorState(head + "RETRY_TIMEOUT soon"), equalTo("42601"));
}
@Test
void rejectsWhatTheStatementCannotExpress() {
assertThat(errorState(BASIC.replace("VOLATILE", "IMMUTABLE")), equalTo("0A000"));
assertThat(errorState(BASIC.replace("'" + ROLE + "'", "DEFAULT")), equalTo("0A000"));
assertThat(errorState("CREATE EXTERNAL FUNCTION f(TIMESTAMPTZ) RETURNS INT STABLE LAMBDA 'f' IAM_ROLE '"
+ ROLE + "'"), equalTo("0A000"));
assertThat(errorState("CREATE EXTERNAL FUNCTION f(INT) RETURNS SUPER STABLE LAMBDA 'f' IAM_ROLE '"
+ ROLE + "'"), equalTo("0A000"));
}
@Test
void rejectsMalformedOrIncompleteStatements() {
assertThat(errorState("CREATE EXTERNAL FUNCTION f(INT) VOLATILE LAMBDA 'f' IAM_ROLE '" + ROLE + "'"),
equalTo("42601"));
assertThat(errorState("CREATE EXTERNAL FUNCTION f(INT) RETURNS INT LAMBDA 'f' IAM_ROLE '" + ROLE + "'"),
equalTo("42601"));
assertThat(errorState("CREATE EXTERNAL FUNCTION f(INT) RETURNS INT STABLE IAM_ROLE '" + ROLE + "'"),
equalTo("42601"));
assertThat(errorState("CREATE EXTERNAL FUNCTION f(INT) RETURNS INT STABLE LAMBDA 'f'"), equalTo("42601"));
assertThat(errorState("CREATE EXTERNAL FUNCTION f(INT RETURNS INT STABLE LAMBDA 'f' IAM_ROLE '" + ROLE + "'"),
equalTo("42601"));
assertThat(errorState(BASIC + " LAMBDA 'other'"), equalTo("42601"));
assertThat(errorState(BASIC + " SOMETHING 'else'"), equalTo("42601"));
assertThat(errorState(BASIC.replace("'lambda_sum'", "lambda_sum")), equalTo("42601"));
}
@Test
void parsesDropFunctionByItsSignatureIgnoringArgumentNames() {
ExternalStatement.DropFunction drop = (ExternalStatement.DropFunction) parser.parse(
"DROP FUNCTION IF EXISTS Sales.exfunc_sum(a INT, b double precision, VARCHAR(5)) CASCADE;").orElseThrow();
assertThat(drop.schemaName(), equalTo("sales"));
assertThat(drop.functionName(), equalTo("exfunc_sum"));
assertThat(drop.argumentTypes(), equalTo(List.of("integer", "double precision", "character varying")));
assertThat(drop.ifExists(), equalTo(true));
assertThat(drop.cascade(), equalTo(true));
}
@Test
void dropFunctionDefaultsToRestrictAndAllowsNoArguments() {
ExternalStatement.DropFunction drop = (ExternalStatement.DropFunction) parser.parse(
"DROP FUNCTION f_now()").orElseThrow();
assertThat(drop.argumentTypes(), equalTo(List.of()));
assertThat(drop.cascade(), equalTo(false));
assertThat(drop.ifExists(), equalTo(false));
}
@Test
void leavesADropOfAnyOtherFunctionToTheBackend() {
assertThat(parser.parse("DROP FUNCTION f_py(INTERVAL)").isPresent(), equalTo(false));
assertThat(parser.parse("DROP FUNCTION f_py").isPresent(), equalTo(false));
}
@Test
void dropFunctionReadsAQuotedArgumentNameThatHoldsASpace() {
ExternalStatement.DropFunction drop = (ExternalStatement.DropFunction) parser.parse(
"DROP FUNCTION f(\"arg name\" INT, \"a\"\"b c\" double precision)").orElseThrow();
assertThat(drop.argumentTypes(), equalTo(List.of("integer", "double precision")));
}
@Test
void rejectsATypeModifierTheTypeDoesNotTake() {
String tail = ") RETURNS INT STABLE LAMBDA 'f' IAM_ROLE '" + ROLE + "'";
assertThat(errorState("CREATE EXTERNAL FUNCTION f(INT(10)" + tail), equalTo("42601"));
assertThat(errorState("CREATE EXTERNAL FUNCTION f(DATE(3)" + tail), equalTo("42601"));
assertThat(errorState("CREATE EXTERNAL FUNCTION f(DECIMAL(39, 2)" + tail), equalTo("42601"));
assertThat(errorState("CREATE EXTERNAL FUNCTION f(DECIMAL(5, 6)" + tail), equalTo("42601"));
assertThat(errorState("CREATE EXTERNAL FUNCTION f(CHAR(0)" + tail), equalTo("42601"));
assertThat(errorState("CREATE EXTERNAL FUNCTION f(VARCHAR(65536)" + tail), equalTo("42601"));
assertThat(errorState("CREATE EXTERNAL FUNCTION f(VARCHAR(5, 2)" + tail), equalTo("42601"));
assertThat(errorState("CREATE EXTERNAL FUNCTION f() RETURNS BIGINT(8) STABLE LAMBDA 'f' IAM_ROLE '" + ROLE + "'"),
equalTo("42601"));
}
@Test
void textStaysItsOwnTypeSoDroppingTextNeverNamesAVarcharFunction() {
ExternalStatement.CreateFunction text = create("CREATE EXTERNAL FUNCTION f(TEXT) RETURNS INT STABLE "
+ "LAMBDA 'f' IAM_ROLE '" + ROLE + "'");
ExternalStatement.DropFunction drop = (ExternalStatement.DropFunction) parser.parse(
"DROP FUNCTION f(VARCHAR)").orElseThrow();
assertThat(text.argumentTypes(), equalTo(List.of("text")));
assertThat(drop.argumentTypes(), equalTo(List.of("character varying")));
}
@Test
void anUnsupportedStatementErrorNamesTheType() {
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
() -> parser.parse("CREATE EXTERNAL FUNCTION f(JSONB) RETURNS INT STABLE LAMBDA 'f' IAM_ROLE '"
+ ROLE + "'"));
assertThat(error.getMessage(), containsString("JSONB"));
}
}
@@ -240,7 +240,7 @@ class ExternalStatementParserTest {
@Test
void otherCreateExternalStatementsAreReportedAsUnsupported() {
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
() -> parser.parse("CREATE EXTERNAL FUNCTION f(int) RETURNS int LAMBDA 'x' IAM_ROLE 'r'"));
() -> parser.parse("CREATE EXTERNAL MODEL m FROM 's3://bucket/model'"));
assertThat(error.sqlState(), equalTo("0A000"));
assertThat(error.getMessage().contains("unsupported"), equalTo(true));
}
@@ -0,0 +1,234 @@
package io.floci.aws.services.redshift.spectrum;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.services.glue.GlueService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.util.List;
import java.util.Optional;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.doThrow;
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;
class SpectrumExternalFunctionPreparationTest {
private static final String ACCOUNT = "000000000000";
private static final String ROLE = "arn:aws:iam::000000000000:role/R";
private static final SpectrumSession SESSION = new SpectrumSession(ACCOUNT, ACCOUNT + ":c", "dev", List.of(), false);
private static final String CREATE = "CREATE EXTERNAL FUNCTION exfunc_sum(INT, INT) RETURNS INT VOLATILE "
+ "LAMBDA 'lambda_sum' IAM_ROLE '" + ROLE + "'";
private ExternalFunctionRegistry functions;
private BackendSql backend;
private SpectrumQueryPreparation preparation;
@BeforeEach
void setUp() {
functions = new ExternalFunctionRegistry(AccountAwareStorageBackend.<ExternalFunctionBinding>inMemory(ACCOUNT));
backend = mock(BackendSql.class);
GlueService glue = mock(GlueService.class);
KinesisStreamingViews views = new KinesisStreamingViews(
new KinesisViewRegistry(AccountAwareStorageBackend.<KinesisViewBinding>inMemory(ACCOUNT)),
null, null, null, Clock.systemUTC());
preparation = new SpectrumQueryPreparation(mock(ExternalCatalogRegistry.class),
new KinesisSchemaRegistry(AccountAwareStorageBackend.<KinesisSchemaBinding>inMemory(ACCOUNT)),
new MskSchemaRegistry(AccountAwareStorageBackend.<MskSchemaBinding>inMemory(ACCOUNT)), functions,
mock(ExternalTableMaterializer.class), new ExternalStatementParser(), glue,
new ExternalMetadataWriter(glue, new ObjectMapper()), new ExternalCatalogLocks(), views,
(accountId, clusterIdentifier) -> null);
}
private Optional<ExternalFunctionBinding> bound(String schema, String name, List<String> args) {
return functions.findFunction(SESSION, schema, name, args);
}
@Test
void createsAStubThatRefusesCallsAndRemembersTheDeclaration() {
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")
&& sql.contains("USING ERRCODE = ''0A000''")));
ExternalFunctionBinding binding = bound("public", "exfunc_sum", List.of("integer", "integer")).orElseThrow();
assertThat(binding.lambdaFunction(), equalTo("lambda_sum"));
assertThat(binding.iamRoleArn(), equalTo(ROLE));
assertThat(binding.returnType(), equalTo("integer"));
assertThat(binding.volatility(), equalTo("VOLATILE"));
assertThat(binding.maxBatchSizeBytes(), equalTo(5L * 1024 * 1024));
}
@Test
void createsInTheSchemaTheNameQualifiesWith() {
preparation.prepare("CREATE OR REPLACE EXTERNAL FUNCTION \"Sales\".f_now() RETURNS VARCHAR(8) STABLE "
+ "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));
}
@Test
void orReplaceOnlyReplacesAFunctionTheRegistryMade() {
String replace = CREATE.replace("CREATE EXTERNAL", "CREATE OR REPLACE EXTERNAL");
preparation.prepare(replace, SESSION, backend);
preparation.prepare(replace, SESSION, backend);
verify(backend, times(1)).execute(argThat(sql -> sql.startsWith("CREATE FUNCTION")));
verify(backend, times(1)).execute(argThat(sql -> sql.startsWith("CREATE OR REPLACE FUNCTION")));
}
@Test
void anOrdinaryFunctionOfTheSignatureIsNeverOverwrittenByAStub() {
doThrow(new SpectrumReadException("42723", "function already exists")).when(backend)
.execute(argThat(sql -> sql.startsWith("CREATE FUNCTION")));
SpectrumReadException error = assertThrows(SpectrumReadException.class, () -> preparation.prepare(
CREATE.replace("CREATE EXTERNAL", "CREATE OR REPLACE EXTERNAL"), SESSION, backend));
assertThat(error.sqlState(), equalTo("42723"));
verify(backend, never()).execute(argThat(sql -> sql.startsWith("CREATE OR REPLACE")));
assertThat(bound("public", "exfunc_sum", List.of("integer", "integer")).isPresent(), equalTo(false));
}
@Test
void aPercentSignInAQuotedNameIsNotAPlaceholderOfTheStubsMessage() {
preparation.prepare("CREATE EXTERNAL FUNCTION \"pct%fn\"(INT) RETURNS INT STABLE LAMBDA 'f' IAM_ROLE '"
+ ROLE + "'", SESSION, backend);
verify(backend).execute(argThat(sql -> sql.contains("RAISE EXCEPTION ''%'', E''External function public.pct%fn ")));
}
@Test
void doesNotBindWhenTheBackendRefusesTheStub() {
doThrow(new SpectrumReadException("42723", "function already exists")).when(backend)
.execute(argThat(sql -> sql.startsWith("CREATE FUNCTION")));
SpectrumReadException error = assertThrows(SpectrumReadException.class,
() -> preparation.prepare(CREATE, SESSION, backend));
assertThat(error.sqlState(), equalTo("42723"));
assertThat(bound("public", "exfunc_sum", List.of("integer", "integer")).isPresent(), equalTo(false));
}
@Test
void replacingAFunctionKeepsOneBindingWithTheNewDeclaration() {
preparation.prepare(CREATE, SESSION, backend);
preparation.prepare(CREATE.replace("CREATE EXTERNAL", "CREATE OR REPLACE EXTERNAL")
.replace("lambda_sum", "lambda_sum_v2"), SESSION, backend);
assertThat(bound("public", "exfunc_sum", List.of("integer", "integer")).orElseThrow().lambdaFunction(),
equalTo("lambda_sum_v2"));
assertThat(functions.list(ACCOUNT, SESSION.clusterKey(), "dev").size(), equalTo(1));
}
@Test
void refusesToRunInsideATransactionBlock() {
SpectrumSession transaction = new SpectrumSession(ACCOUNT, SESSION.clusterKey(), "dev", List.of(), true);
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
() -> preparation.prepare(CREATE, transaction, backend));
assertThat(error.sqlState(), equalTo("25001"));
verifyNoInteractions(backend);
}
@Test
void dropsTheStubAndTheBinding() {
preparation.prepare(CREATE, SESSION, backend);
String drop = "DROP FUNCTION exfunc_sum(INT, INT)";
assertThat(preparation.handlesDdl(drop, SESSION), equalTo(true));
assertThat(preparation.commandTag(drop), equalTo("DROP FUNCTION"));
assertThat(preparation.prepare(drop, SESSION, backend), equalTo(true));
verify(backend).execute("DROP FUNCTION \"public\".\"exfunc_sum\"(integer, integer) RESTRICT");
assertThat(bound("public", "exfunc_sum", List.of("integer", "integer")).isPresent(), equalTo(false));
}
@Test
void passesCascadeAndIfExistsToTheBackend() {
preparation.prepare(CREATE, SESSION, backend);
preparation.prepare("DROP FUNCTION IF EXISTS public.exfunc_sum(integer, integer) CASCADE", SESSION, backend);
verify(backend).execute("DROP FUNCTION IF EXISTS \"public\".\"exfunc_sum\"(integer, integer) CASCADE");
}
@Test
void leavesADropOfAnUntrackedFunctionToTheBackend() {
preparation.prepare(CREATE, SESSION, backend);
assertThat(preparation.handlesDdl("DROP FUNCTION exfunc_sum(BIGINT)", SESSION), equalTo(false));
assertThat(preparation.handlesDdl("DROP FUNCTION other.exfunc_sum(INT, INT)", SESSION), equalTo(false));
assertThat(preparation.prepare("DROP FUNCTION exfunc_sum(BIGINT)", SESSION, backend), equalTo(false));
assertThat(bound("public", "exfunc_sum", List.of("integer", "integer")).isPresent(), equalTo(true));
}
@Test
void keepsTheBindingWhenTheBackendRefusesTheDrop() {
preparation.prepare(CREATE, SESSION, backend);
doThrow(new SpectrumReadException("42501", "must be owner of function")).when(backend)
.execute(argThat(sql -> sql.startsWith("DROP FUNCTION")));
assertThrows(SpectrumReadException.class,
() -> preparation.prepare("DROP FUNCTION exfunc_sum(INT, INT)", SESSION, backend));
assertThat(bound("public", "exfunc_sum", List.of("integer", "integer")).isPresent(), equalTo(true));
}
@Test
void forgetsABindingWhoseStubIsAlreadyGone() {
preparation.prepare(CREATE, SESSION, backend);
doThrow(new SpectrumReadException("42883", "function does not exist")).when(backend)
.execute(argThat(sql -> sql.startsWith("DROP FUNCTION")));
SpectrumReadException error = assertThrows(SpectrumReadException.class,
() -> preparation.prepare("DROP FUNCTION exfunc_sum(INT, INT)", SESSION, backend));
assertThat(error.sqlState(), equalTo("42883"));
assertThat(bound("public", "exfunc_sum", List.of("integer", "integer")).isPresent(), equalTo(false));
}
@Test
void dropRefusesToRunInsideATransactionBlock() {
preparation.prepare(CREATE, SESSION, backend);
SpectrumSession transaction = new SpectrumSession(ACCOUNT, SESSION.clusterKey(), "dev", List.of(), true);
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
() -> preparation.prepare("DROP FUNCTION exfunc_sum(INT, INT)", transaction, backend));
assertThat(error.sqlState(), equalTo("25001"));
verify(backend, never()).execute(argThat(sql -> sql.startsWith("DROP FUNCTION")));
}
@Test
void forgetRuntimeDropsTheClustersFunctions() {
preparation.prepare(CREATE, SESSION, backend);
preparation.forgetRuntime(ACCOUNT, SESSION.clusterKey());
assertThat(functions.list(ACCOUNT, SESSION.clusterKey(), "dev").isEmpty(), equalTo(true));
}
@Test
void theStubNamesTheFunctionInItsError() {
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")));
}
}
@@ -38,6 +38,8 @@ class SpectrumMskSchemaPreparationTest {
private ExternalCatalogRegistry glueSchemas;
private KinesisSchemaRegistry kinesisSchemas;
private MskSchemaRegistry mskSchemas;
private final ExternalFunctionRegistry functions =
new ExternalFunctionRegistry(AccountAwareStorageBackend.<ExternalFunctionBinding>inMemory(ACCOUNT));
private KinesisService kinesisService;
private ExternalTableMaterializer materializer;
private BackendSql backend;
@@ -56,7 +58,7 @@ class SpectrumMskSchemaPreparationTest {
KinesisStreamingViews views = new KinesisStreamingViews(
new KinesisViewRegistry(AccountAwareStorageBackend.<KinesisViewBinding>inMemory(ACCOUNT)),
kinesisService, null, null, Clock.systemUTC());
preparation = new SpectrumQueryPreparation(glueSchemas, kinesisSchemas, mskSchemas, materializer,
preparation = new SpectrumQueryPreparation(glueSchemas, kinesisSchemas, mskSchemas, functions, materializer,
new ExternalStatementParser(), mock(GlueService.class), metadata, new ExternalCatalogLocks(),
views, (accountId, clusterIdentifier) -> null);
}
@@ -148,7 +150,7 @@ class SpectrumMskSchemaPreparationTest {
new KinesisViewRegistry(AccountAwareStorageBackend.<KinesisViewBinding>inMemory(ACCOUNT)),
null, null, null, Clock.systemUTC());
SpectrumQueryPreparation withGlue = new SpectrumQueryPreparation(glueSchemas, kinesisSchemas, mskSchemas,
materializer, new ExternalStatementParser(), glue, new ExternalMetadataWriter(glue, new ObjectMapper()),
functions, materializer, new ExternalStatementParser(), glue, new ExternalMetadataWriter(glue, new ObjectMapper()),
new ExternalCatalogLocks(), views, (accountId, clusterIdentifier) -> null);
preparation.prepare(CREATE, SESSION, backend);