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

@@ -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);