mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
5b4bc0e44e
commit
a9d0aab496
13 files changed
+1207
-14
No files matched your search
@@ -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) {
|
||||
|
||||
+115
-10
@@ -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);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user