feat(redshift): add external schemas over Amazon MSK (#9091)

This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-21 12:40:26 -04:00
1 parent 7706e5705d
commit 3d6a05d656
18 files changed
+1117 -91

No files matched your search

+20 -1
View File
@@ -1067,9 +1067,28 @@ kept, as in Redshift.
- `CREATE EXTERNAL SCHEMA` inside an explicit transaction fails with SQLSTATE `0A000`, and `DROP SCHEMA`
with `25001`, because the schema registration is not part of the PostgreSQL transaction.
- `DROP EXTERNAL DATABASE` and dropping several schemas in one statement are outside this implementation.
- Schemas over Amazon MSK or Kafka are not supported.
- `DROP SCHEMA ... CASCADE` also drops the streaming views that read the schema.
### External schemas over Amazon MSK
An external schema over an Amazon MSK cluster maps a local schema to the cluster for streaming ingestion.
```sql
CREATE EXTERNAL SCHEMA [IF NOT EXISTS] msk
FROM MSK
IAM_ROLE 'arn:aws:iam::123456789012:role/StreamRole'
AUTHENTICATION iam
CLUSTER_ARN 'arn:aws:kafka:us-east-1:123456789012:cluster/my-cluster/00000000-0000-0000-0000-000000000000-1';
```
`CREATE EXTERNAL SCHEMA` creates a local PostgreSQL schema, remembers the role, authentication mode and cluster ARN, and lists the schema in `svv_external_schemas` with `eskind` 10 and those options in `esoptions`. `DROP SCHEMA [IF EXISTS] msk [CASCADE | RESTRICT]` removes the local schema, its metadata row and its registration; `RESTRICT` is the default, as in Redshift.
- `AUTHENTICATION` accepts `iam` or `none`. `AUTHENTICATION mtls`, `AUTHENTICATION_ARN`, `SECRET_ARN`, `URI`, `IAM_ROLE DEFAULT` and `FROM KAFKA` schemas are refused with SQLSTATE `0A000`.
- The role and cluster ARN are not checked when the schema is created.
- A statement that names a relation of the schema (`SELECT * FROM msk.my_topic`, `INSERT INTO msk.t`, `UPDATE msk.t`, `CREATE TABLE msk.t (...)`) is refused with SQLSTATE `0A000`. Streaming materialized views over MSK topics are not yet wired.
- `CREATE EXTERNAL SCHEMA` inside an explicit transaction fails with SQLSTATE `0A000`, and `DROP SCHEMA` with `25001`, because the schema registration is not part of the PostgreSQL transaction.
- `DROP EXTERNAL DATABASE` and dropping several schemas in one statement are outside this implementation.
### Streaming materialized views
A streaming materialized view reads one stream of a Kinesis external schema, and `REFRESH` loads what the
@@ -23,6 +23,8 @@ public class ExternalMetadataWriter {
private static final Logger LOG = Logger.getLogger(ExternalMetadataWriter.class);
/** The {@code eskind} that SVV_EXTERNAL_SCHEMAS gives a schema over an Amazon Kinesis data stream. */
private static final int KINESIS_SCHEMA_KIND = 9;
/** The {@code eskind} that SVV_EXTERNAL_SCHEMAS gives a schema over an Amazon MSK cluster. */
private static final int MSK_SCHEMA_KIND = 10;
private final GlueService glueService;
private final ObjectMapper objectMapper;
@@ -45,6 +47,10 @@ public class ExternalMetadataWriter {
run(backend, refreshKinesisSql(binding), false);
}
public void refreshMsk(BackendSql backend, MskSchemaBinding binding) {
run(backend, refreshMskSql(binding), false);
}
public void purge(BackendSql backend, String schemaName) {
run(backend, purgeSql(schemaName), true);
}
@@ -66,18 +72,37 @@ public class ExternalMetadataWriter {
}
/**
* A schema over a Kinesis stream lists as kind 9 with no tables. Its stream is read only through a
* materialized view, and Redshift documents no external database name for it, so that column stays empty.
* A schema over a Kinesis stream lists as kind 9 with no tables.
*/
String refreshKinesisSql(KinesisSchemaBinding binding) {
return refreshStreamingSql(binding.schemaName(), KINESIS_SCHEMA_KIND,
Map.of("IAM_ROLE", binding.iamRoleArn()));
}
/**
* A schema over an Amazon MSK cluster lists as kind 10 with no tables.
*/
String refreshMskSql(MskSchemaBinding binding) {
Map<String, Object> options = row(
"IAM_ROLE", binding.iamRoleArn(),
"AUTHENTICATION", binding.authentication(),
"CLUSTER_ARN", binding.clusterArn());
return refreshStreamingSql(binding.schemaName(), MSK_SCHEMA_KIND, options);
}
/**
* Streaming external schemas list with no tables: their streams or topics are read only through a
* streaming materialized view, and Redshift documents no external database name for them.
*/
private String refreshStreamingSql(String schemaName, int kind, Map<String, ?> options) {
Map<String, Object> payload = row(
"eskind", KINESIS_SCHEMA_KIND,
"eskind", kind,
"databasename", "",
"esoptions", json(Map.of("IAM_ROLE", binding.iamRoleArn())),
"esoptions", json(options),
"tables", List.of(),
"columns", List.of(),
"partitions", List.of());
return "SELECT floci_internal.refresh_external_catalog(" + literal(binding.schemaName()) + ", "
return "SELECT floci_internal.refresh_external_catalog(" + literal(schemaName) + ", "
+ literal(json(payload)) + "::jsonb)";
}
@@ -118,7 +118,7 @@ public final class ExternalReferenceScanner {
/**
* The first external table or schema an {@code INSERT}, {@code UPDATE}, {@code DELETE}, {@code MERGE},
* {@code TRUNCATE}, {@code COPY}, {@code SELECT INTO}, {@code CREATE TABLE}, {@code CREATE VIEW}, {@code CREATE INDEX},
* {@code ALTER TABLE} or {@code DROP} anywhere in
* {@code ALTER TABLE}, {@code ALTER SCHEMA ... RENAME TO} or {@code DROP} anywhere in
* {@code sql} changes: every statement of a batch and every data-modifying CTE is checked, not only
* the first write. The external DDL Floci implements is parsed before this is reached.
*/
@@ -132,6 +132,10 @@ public final class ExternalReferenceScanner {
if (moved.isPresent()) {
return moved;
}
Optional<Reference> renamed = renamedExternalSchema(tokens, i, schemaNames);
if (renamed.isPresent()) {
return renamed;
}
Optional<Reference> truncated = truncatedTarget(tokens, i, schemaNames);
if (truncated.isPresent()) {
return truncated;
@@ -178,6 +182,32 @@ public final class ExternalReferenceScanner {
return Optional.empty();
}
/** {@code ALTER SCHEMA a RENAME TO b}: renaming an external schema would leave its binding stale. */
private static Optional<Reference> renamedExternalSchema(List<Token> tokens, int i, Set<String> schemaNames) {
if (!keywordAt(tokens, i, "alter") || !keywordAt(tokens, i + 1, "schema")) {
return Optional.empty();
}
int source = i + 2;
if (source >= tokens.size() || !tokens.get(source).isChain()) {
return Optional.empty();
}
if (!keywordAt(tokens, source + 1, "rename") || !keywordAt(tokens, source + 2, "to")) {
return Optional.empty();
}
Word from = tokens.get(source).chain().getFirst();
if (schemaNames.contains(from.value())) {
return Optional.of(new Reference(from.value(), ""));
}
int target = source + 3;
if (target < tokens.size() && tokens.get(target).isChain()) {
Word to = tokens.get(target).chain().getFirst();
if (schemaNames.contains(to.value())) {
return Optional.of(new Reference(to.value(), ""));
}
}
return Optional.empty();
}
/** {@code DROP TABLE a, b} and {@code DROP SCHEMA a, b}: any name of the list may be an external one. */
private static Optional<Reference> droppedTarget(List<Token> tokens, int i, Set<String> schemaNames) {
if (!keywordAt(tokens, i, "drop")) {
@@ -7,17 +7,11 @@ public record ExternalSchemaBinding(String accountId, String clusterKey, String
String schemaName, String glueDatabase, String iamRoleArn)
implements SchemaBinding {
public ExternalSchemaBinding {
require(accountId, "accountId");
require(clusterKey, "clusterKey");
require(databaseName, "databaseName");
require(schemaName, "schemaName");
require(glueDatabase, "glueDatabase");
require(iamRoleArn, "iamRoleArn");
}
private static void require(String value, String field) {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException(field + " is required");
}
SchemaBinding.require(accountId, "accountId");
SchemaBinding.require(clusterKey, "clusterKey");
SchemaBinding.require(databaseName, "databaseName");
SchemaBinding.require(schemaName, "schemaName");
SchemaBinding.require(glueDatabase, "glueDatabase");
SchemaBinding.require(iamRoleArn, "iamRoleArn");
}
}
@@ -6,9 +6,9 @@ import java.util.List;
import java.util.Map;
public sealed interface ExternalStatement permits ExternalStatement.CreateSchema, ExternalStatement.CreateKinesisSchema,
ExternalStatement.CreateTable, ExternalStatement.AddPartitions, ExternalStatement.DropSchema,
ExternalStatement.DropTable, ExternalStatement.CreateStreamingView, ExternalStatement.RefreshView,
ExternalStatement.DropView {
ExternalStatement.CreateMskSchema, ExternalStatement.CreateTable, ExternalStatement.AddPartitions,
ExternalStatement.DropSchema, ExternalStatement.DropTable, ExternalStatement.CreateStreamingView,
ExternalStatement.RefreshView, ExternalStatement.DropView {
/** 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));
@@ -24,6 +24,8 @@ public sealed interface ExternalStatement permits ExternalStatement.CreateSchema
/** {@code region} is null when the statement names none, which leaves the cluster's own Region. */
record CreateKinesisSchema(String schemaName, String region, String iamRoleArn,
boolean ifNotExists) implements ExternalStatement { }
record CreateMskSchema(String schemaName, String iamRoleArn, String authentication,
String clusterArn, boolean ifNotExists) implements ExternalStatement { }
record CreateTable(String schemaName, String tableName, List<ColumnDefinition> columns,
List<ColumnDefinition> partitionColumns, TableFormat format, String location,
String delimiter, String serde, Map<String, String> properties,
@@ -20,6 +20,8 @@ public class ExternalStatementParser {
private static final Pattern CREATE_EXTERNAL = Pattern.compile("(?is)^\\s*CREATE\\s+EXTERNAL\\b.*");
private static final Pattern SERDE_PROPERTIES = Pattern.compile("(?is)WITH\\s+SERDEPROPERTIES\\s*\\(");
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_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*$");
@@ -59,6 +61,10 @@ public class ExternalStatementParser {
}
// comments are separators here; the view's query is stored and sent again on every refresh
String viewText = withoutComments(text);
Matcher msk = CREATE_MSK_SCHEMA_HEAD.matcher(viewText);
if (msk.matches()) {
return Optional.of(parseMskSchema(identifier(msk.group(2)), msk.group(1) != null, msk.group(3)));
}
Matcher createView = CREATE_VIEW.matcher(viewText);
if (createView.matches()) {
if (hasStatementSeparator(createView.group(4))) {
@@ -185,6 +191,129 @@ public class ExternalStatementParser {
return arn;
}
private static ExternalStatement.CreateMskSchema parseMskSchema(String schemaName, boolean ifNotExists,
String tail) {
String iamRoleArn = null;
String authentication = null;
String clusterArn = null;
int pos = 0;
int length = tail.length();
while (true) {
pos = skipWhitespace(tail, pos);
if (pos >= length) {
break;
}
int keyEnd = readKeywordEnd(tail, pos);
String keyword = tail.substring(pos, keyEnd).toUpperCase(Locale.ROOT);
pos = skipWhitespace(tail, keyEnd);
switch (keyword) {
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 "AUTHENTICATION" -> {
if (authentication != null) {
throw new SpectrumSqlException("42601", "Duplicate AUTHENTICATION clause");
}
TokenSlice slice = readValueToken(tail, pos, "AUTHENTICATION");
pos = slice.end();
String mode = slice.text().trim();
if (mode.equalsIgnoreCase("iam")) {
authentication = "IAM";
} else if (mode.equalsIgnoreCase("none")) {
authentication = "NONE";
} else if (mode.equalsIgnoreCase("mtls")) {
throw new SpectrumSqlException("0A000", "AUTHENTICATION mtls is not supported");
} else {
throw new SpectrumSqlException("42601", "AUTHENTICATION must be iam, none, or mtls");
}
}
case "CLUSTER_ARN" -> {
if (clusterArn != null) {
throw new SpectrumSqlException("42601", "Duplicate CLUSTER_ARN clause");
}
TokenSlice slice = readValueToken(tail, pos, "CLUSTER_ARN");
pos = slice.end();
clusterArn = requireQuotedLiteral(slice.text(), "CLUSTER_ARN must be a single quoted cluster ARN");
}
case "URI", "AUTHENTICATION_ARN", "SECRET_ARN" ->
throw new SpectrumSqlException("0A000", keyword + " is not supported for MSK external schemas");
default -> throw new SpectrumSqlException("42601",
"Unexpected clause in CREATE EXTERNAL SCHEMA FROM MSK: " + keyword);
}
}
if (iamRoleArn == null) {
throw new SpectrumSqlException("42601", "CREATE EXTERNAL SCHEMA FROM MSK requires IAM_ROLE");
}
if (authentication == null) {
throw new SpectrumSqlException("42601", "CREATE EXTERNAL SCHEMA FROM MSK requires AUTHENTICATION");
}
if (clusterArn == null) {
throw new SpectrumSqlException("42601", "CREATE EXTERNAL SCHEMA FROM MSK requires CLUSTER_ARN");
}
return new ExternalStatement.CreateMskSchema(schemaName, iamRoleArn, authentication,
clusterArn, ifNotExists);
}
private record TokenSlice(String text, int end) { }
private static int skipWhitespace(String text, int pos) {
while (pos < text.length() && Character.isWhitespace(text.charAt(pos))) {
pos++;
}
return pos;
}
private static int readKeywordEnd(String text, int pos) {
int index = pos;
while (index < text.length() && !Character.isWhitespace(text.charAt(index))) {
index++;
}
return index;
}
private static TokenSlice readValueToken(String text, int pos, String clause) {
if (pos >= text.length()) {
throw new SpectrumSqlException("42601", "Missing value for " + clause);
}
if (text.charAt(pos) == '\'') {
int index = pos + 1;
while (index < text.length()) {
if (text.charAt(index) == '\'') {
if (index + 1 < text.length() && text.charAt(index + 1) == '\'') {
index += 2;
} else {
return new TokenSlice(text.substring(pos, index + 1), index + 1);
}
} else {
index++;
}
}
throw new SpectrumSqlException("42601", "Unterminated string literal for " + clause);
}
int end = pos;
while (end < text.length() && !Character.isWhitespace(text.charAt(end))) {
end++;
}
return new TokenSlice(text.substring(pos, end), end);
}
private static String requireQuotedLiteral(String token, String message) {
String trimmed = token.trim();
if (!QUOTED_LITERAL.matcher(trimmed).matches()) {
throw new SpectrumSqlException("42601", message);
}
String value = unquote(trimmed);
if (value.isBlank()) {
throw new SpectrumSqlException("42601", message);
}
return value;
}
private static String stripLeadingComments(String sql) {
String text = sql.trim();
while (true) {
@@ -12,16 +12,10 @@ public record KinesisSchemaBinding(String accountId, String clusterKey, String d
String schemaName, String region, String iamRoleArn)
implements SchemaBinding {
public KinesisSchemaBinding {
require(accountId, "accountId");
require(clusterKey, "clusterKey");
require(databaseName, "databaseName");
require(schemaName, "schemaName");
require(iamRoleArn, "iamRoleArn");
}
private static void require(String value, String field) {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException(field + " is required");
}
SchemaBinding.require(accountId, "accountId");
SchemaBinding.require(clusterKey, "clusterKey");
SchemaBinding.require(databaseName, "databaseName");
SchemaBinding.require(schemaName, "schemaName");
SchemaBinding.require(iamRoleArn, "iamRoleArn");
}
}
@@ -18,14 +18,14 @@ public record KinesisViewBinding(String accountId, String clusterKey, String dat
private static final char KEY_SEPARATOR = '\u001f';
public KinesisViewBinding {
require(accountId, "accountId");
require(clusterKey, "clusterKey");
require(databaseName, "databaseName");
require(viewSchema, "viewSchema");
require(viewName, "viewName");
require(streamSchema, "streamSchema");
require(streamName, "streamName");
require(select, "select");
SchemaBinding.require(accountId, "accountId");
SchemaBinding.require(clusterKey, "clusterKey");
SchemaBinding.require(databaseName, "databaseName");
SchemaBinding.require(viewSchema, "viewSchema");
SchemaBinding.require(viewName, "viewName");
SchemaBinding.require(streamSchema, "streamSchema");
SchemaBinding.require(streamName, "streamName");
SchemaBinding.require(select, "select");
checkpoints = checkpoints == null ? Map.of() : Map.copyOf(checkpoints);
}
@@ -50,10 +50,4 @@ public record KinesisViewBinding(String accountId, String clusterKey, String dat
return new KinesisViewBinding(accountId, clusterKey, databaseName, viewSchema, viewName, streamSchema,
streamName, select, updated);
}
private static void require(String value, String field) {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException(field + " is required");
}
}
}
@@ -0,0 +1,26 @@
package io.floci.aws.services.redshift.spectrum;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* An external schema over Amazon MSK. It is kept apart from {@link ExternalSchemaBinding} because it
* has no Glue database, and the Spectrum read path treats every binding of that type as one.
*/
@RegisterForReflection
public record MskSchemaBinding(String accountId, String clusterKey, String databaseName,
String schemaName, String iamRoleArn,
String authentication, String clusterArn)
implements SchemaBinding {
public MskSchemaBinding {
SchemaBinding.require(accountId, "accountId");
SchemaBinding.require(clusterKey, "clusterKey");
SchemaBinding.require(databaseName, "databaseName");
SchemaBinding.require(schemaName, "schemaName");
SchemaBinding.require(iamRoleArn, "iamRoleArn");
SchemaBinding.require(authentication, "authentication");
if (!"IAM".equals(authentication) && !"NONE".equals(authentication)) {
throw new IllegalArgumentException("authentication must be IAM or NONE");
}
SchemaBinding.require(clusterArn, "clusterArn");
}
}
@@ -0,0 +1,20 @@
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;
@ApplicationScoped
public class MskSchemaRegistry extends SchemaBindingRegistry<MskSchemaBinding> {
@Inject
public MskSchemaRegistry(StorageFactory storageFactory) {
super(storageFactory.<MskSchemaBinding>create("redshift", "redshift-msk-schemas.json",
new TypeReference<>() { }));
}
MskSchemaRegistry(AccountAwareStorageBackend<MskSchemaBinding> bindings) {
super(bindings);
}
}
@@ -14,4 +14,10 @@ interface SchemaBinding {
default String bindingName() {
return schemaName();
}
static void require(String value, String field) {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException(field + " is required");
}
}
}
@@ -40,6 +40,7 @@ public class SpectrumQueryPreparation {
Pattern.CASE_INSENSITIVE);
private final ExternalCatalogRegistry registry;
private final KinesisSchemaRegistry kinesisSchemas;
private final MskSchemaRegistry mskSchemas;
private final KinesisStreamingViews views;
private final ExternalTableMaterializer materializer;
private final ExternalStatementParser parser;
@@ -65,11 +66,11 @@ public class SpectrumQueryPreparation {
@Inject
public SpectrumQueryPreparation(ExternalCatalogRegistry registry, KinesisSchemaRegistry kinesisSchemas,
ExternalTableMaterializer materializer, ExternalStatementParser parser,
GlueService glue, ExternalMetadataWriter metadata,
MskSchemaRegistry mskSchemas, ExternalTableMaterializer materializer,
ExternalStatementParser parser, GlueService glue, ExternalMetadataWriter metadata,
ExternalCatalogLocks catalogLocks, KinesisStreamingViews views,
Instance<RedshiftService> redshift) {
this(registry, kinesisSchemas, materializer, parser, glue, metadata, catalogLocks, views,
this(registry, kinesisSchemas, mskSchemas, materializer, parser, glue, metadata, catalogLocks, views,
(accountId, clusterIdentifier) -> redshift.get().clusterRegion(accountId, clusterIdentifier).orElse(null));
}
@@ -84,7 +85,9 @@ public class SpectrumQueryPreparation {
ExternalTableMaterializer materializer, ExternalStatementParser parser,
GlueService glue, ExternalMetadataWriter metadata, ExternalCatalogLocks catalogLocks,
BiFunction<String, String, String> clusterRegion) {
this(registry, kinesisSchemas, materializer, parser, glue, metadata, catalogLocks,
this(registry, kinesisSchemas,
new MskSchemaRegistry(AccountAwareStorageBackend.<MskSchemaBinding>inMemory("000000000000")),
materializer, parser, glue, metadata, catalogLocks,
new KinesisStreamingViews(new KinesisViewRegistry(
AccountAwareStorageBackend.<KinesisViewBinding>inMemory("000000000000")),
null, null, null, Clock.systemUTC()), clusterRegion);
@@ -94,10 +97,21 @@ public class SpectrumQueryPreparation {
ExternalTableMaterializer materializer, ExternalStatementParser parser,
GlueService glue, ExternalMetadataWriter metadata, ExternalCatalogLocks catalogLocks,
KinesisStreamingViews views, BiFunction<String, String, String> clusterRegion) {
this(registry, kinesisSchemas,
new MskSchemaRegistry(AccountAwareStorageBackend.<MskSchemaBinding>inMemory("000000000000")),
materializer, parser, glue, metadata, catalogLocks, views, clusterRegion);
}
SpectrumQueryPreparation(ExternalCatalogRegistry registry, KinesisSchemaRegistry kinesisSchemas,
MskSchemaRegistry mskSchemas, ExternalTableMaterializer materializer,
ExternalStatementParser parser, GlueService glue, ExternalMetadataWriter metadata,
ExternalCatalogLocks catalogLocks, KinesisStreamingViews views,
BiFunction<String, String, String> clusterRegion) {
this.views = views;
this.clusterRegion = clusterRegion;
this.registry = registry;
this.kinesisSchemas = kinesisSchemas;
this.mskSchemas = mskSchemas;
this.materializer = materializer;
this.parser = parser;
this.glue = glue;
@@ -141,11 +155,14 @@ public class SpectrumQueryPreparation {
}
public boolean referencesExternal(String sql, SpectrumSession session) {
Set<String> schemas = bindings(session).keySet();
Set<String> kinesisSchemaNames = kinesisBindings(session).keySet();
Set<String> schemas = bindingsOf(registry, session).keySet();
Set<String> kinesisSchemaNames = bindingsOf(kinesisSchemas, session).keySet();
Set<String> mskSchemaNames = bindingsOf(mskSchemas, session).keySet();
return !ExternalReferenceScanner.scan(sql, schemas).isEmpty()
|| !ExternalReferenceScanner.scan(sql, kinesisSchemaNames).isEmpty()
|| ExternalReferenceScanner.writeTarget(sql, externalSchemaNames(schemas, kinesisSchemaNames)).isPresent();
|| !ExternalReferenceScanner.scan(sql, mskSchemaNames).isEmpty()
|| ExternalReferenceScanner.writeTarget(sql,
externalSchemaNames(schemas, kinesisSchemaNames, mskSchemaNames)).isPresent();
}
public boolean handlesDdl(String sql, SpectrumSession session) {
@@ -153,12 +170,19 @@ public class SpectrumQueryPreparation {
return switch (statement) {
case ExternalStatement.CreateSchema ignored -> true;
case ExternalStatement.CreateKinesisSchema ignored -> true;
case ExternalStatement.CreateTable table -> session.inTransaction() || bindings(session).containsKey(table.schemaName());
case ExternalStatement.AddPartitions partitions -> bindings(session).containsKey(partitions.schemaName());
case ExternalStatement.DropTable table -> bindings(session).containsKey(table.schemaName());
case ExternalStatement.DropSchema schema -> bindings(session).containsKey(schema.schemaName())
|| kinesisBindings(session).containsKey(schema.schemaName());
case ExternalStatement.CreateStreamingView view -> streamSource(view.select(), session).isPresent();
case ExternalStatement.CreateMskSchema ignored -> true;
case ExternalStatement.CreateTable table -> session.inTransaction()
|| bindingsOf(registry, session).containsKey(table.schemaName())
|| bindingsOf(kinesisSchemas, session).containsKey(table.schemaName())
|| bindingsOf(mskSchemas, session).containsKey(table.schemaName());
case ExternalStatement.AddPartitions partitions ->
bindingsOf(registry, session).containsKey(partitions.schemaName());
case ExternalStatement.DropTable table -> bindingsOf(registry, session).containsKey(table.schemaName());
case ExternalStatement.DropSchema schema -> bindingsOf(registry, session).containsKey(schema.schemaName())
|| bindingsOf(kinesisSchemas, session).containsKey(schema.schemaName())
|| bindingsOf(mskSchemas, session).containsKey(schema.schemaName());
case ExternalStatement.CreateStreamingView view -> streamSource(view.select(), session).isPresent()
|| !ExternalReferenceScanner.scan(view.select(), bindingsOf(mskSchemas, session).keySet()).isEmpty();
case ExternalStatement.RefreshView view ->
views.find(session, view.viewSchema(), view.viewName()).isPresent();
case ExternalStatement.DropView view ->
@@ -187,18 +211,34 @@ public class SpectrumQueryPreparation {
if (statement.orElse(null) instanceof ExternalStatement.CreateKinesisSchema schema) {
return createKinesisSchema(schema, session, backend);
}
Map<String, KinesisSchemaBinding> kinesis = kinesisBindings(session);
if (statement.orElse(null) instanceof ExternalStatement.CreateMskSchema schema) {
return createMskSchema(schema, session, backend);
}
Map<String, KinesisSchemaBinding> kinesis = bindingsOf(kinesisSchemas, session);
Map<String, MskSchemaBinding> msk = bindingsOf(mskSchemas, session);
if (statement.orElse(null) instanceof ExternalStatement.DropSchema schema
&& kinesis.containsKey(schema.schemaName())) {
rejectTransaction(session);
dropKinesisSchema(schema, kinesis.get(schema.schemaName()), session, backend);
dropStreamingSchema(schema, kinesis.get(schema.schemaName()), kinesisSchemas,
views.overSchema(session, schema.schemaName()), session, backend);
return true;
}
if (statement.orElse(null) instanceof ExternalStatement.CreateStreamingView view
&& streamSource(view.select(), session).isPresent()) {
createStreamingView(view, kinesis, session, backend);
if (statement.orElse(null) instanceof ExternalStatement.DropSchema schema
&& msk.containsKey(schema.schemaName())) {
rejectTransaction(session);
dropStreamingSchema(schema, msk.get(schema.schemaName()), mskSchemas, List.of(), session, backend);
return true;
}
if (statement.orElse(null) instanceof ExternalStatement.CreateStreamingView view) {
if (!ExternalReferenceScanner.scan(view.select(), msk.keySet()).isEmpty()) {
throw new SpectrumSqlException("0A000",
"Streaming materialized views over MSK external schemas are not supported");
}
if (!ExternalReferenceScanner.scan(view.select(), kinesis.keySet()).isEmpty()) {
createStreamingView(view, kinesis, session, backend);
return true;
}
}
if (statement.orElse(null) instanceof ExternalStatement.RefreshView refresh) {
Optional<KinesisViewBinding> view = views.find(session, refresh.viewSchema(), refresh.viewName());
if (view.isPresent()) {
@@ -214,11 +254,16 @@ public class SpectrumQueryPreparation {
return true;
}
}
Map<String, ExternalSchemaBinding> bindings = bindings(session);
Map<String, ExternalSchemaBinding> bindings = bindingsOf(registry, session);
if (statement.orElse(null) instanceof ExternalStatement.CreateTable && session.inTransaction()) {
// Legacy-catalog tables are saved immediately too, so a rollback would leave them behind.
throw new SpectrumSqlException("25001", "CREATE EXTERNAL TABLE cannot run inside a transaction block");
}
if (statement.orElse(null) instanceof ExternalStatement.CreateTable table
&& (kinesis.containsKey(table.schemaName()) || msk.containsKey(table.schemaName()))) {
throw new SpectrumSqlException("0A000", "CREATE EXTERNAL TABLE is not supported in streaming external schema \""
+ table.schemaName() + "\"");
}
if (statement.orElse(null) instanceof ExternalStatement.CreateTable table && bindings.containsKey(table.schemaName())) {
ExternalSchemaBinding binding = bindings.get(table.schemaName());
try (ExternalCatalogLocks.Guard ignored = catalogLocks.write(binding)) {
@@ -255,8 +300,14 @@ public class SpectrumQueryPreparation {
throw new SpectrumSqlException("0A000", "\"" + stream.schema() + "." + stream.table()
+ "\" is in a Kinesis external schema, whose streams are only read through a streaming materialized view");
}
Set<ExternalReferenceScanner.Reference> topics = ExternalReferenceScanner.scan(sql, msk.keySet());
if (!topics.isEmpty()) {
ExternalReferenceScanner.Reference topic = topics.iterator().next();
throw new SpectrumSqlException("0A000", "\"" + topic.schema() + "." + topic.table()
+ "\" is in an MSK external schema, whose topics are only read through a streaming materialized view");
}
Optional<ExternalReferenceScanner.Reference> write = ExternalReferenceScanner.writeTarget(sql,
externalSchemaNames(bindings.keySet(), kinesis.keySet()));
externalSchemaNames(bindings.keySet(), kinesis.keySet(), msk.keySet()));
if (write.isPresent()) {
throw new SpectrumSqlException("0A000", "Writes to external relation \""
+ write.get().schema() + "." + write.get().table() + "\" are not supported");
@@ -280,9 +331,11 @@ public class SpectrumQueryPreparation {
return false;
}
private static Set<String> externalSchemaNames(Set<String> glueSchemas, Set<String> kinesisSchemas) {
private static Set<String> externalSchemaNames(Set<String> glueSchemas, Set<String> kinesisSchemas,
Set<String> mskSchemas) {
Set<String> names = new HashSet<>(glueSchemas);
names.addAll(kinesisSchemas);
names.addAll(mskSchemas);
return names;
}
@@ -403,7 +456,7 @@ public class SpectrumQueryPreparation {
}
private void requireCurrentBinding(SpectrumSession session, ExternalSchemaBinding binding) {
if (!binding.equals(bindings(session).get(binding.schemaName()))) {
if (!binding.equals(bindingsOf(registry, session).get(binding.schemaName()))) {
throw new SpectrumSqlException("42P01", "External schema binding changed; retry the statement");
}
}
@@ -458,10 +511,28 @@ public class SpectrumQueryPreparation {
return true;
}
/** A name is taken when either kind of external schema already holds it. */
private boolean createMskSchema(ExternalStatement.CreateMskSchema schema, SpectrumSession session,
BackendSql backend) {
if (session.inTransaction()) {
throw new SpectrumSqlException("0A000", "CREATE EXTERNAL SCHEMA inside a transaction is not supported");
}
if (schemaExists(session, schema.schemaName())) {
return existingSchemaOutcome(schema.schemaName(), schema.ifNotExists());
}
MskSchemaBinding binding = new MskSchemaBinding(session.accountId(), session.clusterKey(),
session.databaseName(), schema.schemaName(), schema.iamRoleArn(),
schema.authentication(), schema.clusterArn());
createBoundSchema(backend, schema.schemaName(), schema.ifNotExists(),
() -> metadata.refreshMsk(backend, binding), () -> mskSchemas.bind(binding));
return true;
}
/** 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()
|| kinesisSchemas.find(session.accountId(), session.clusterKey(), session.databaseName(),
schemaName).isPresent()
|| mskSchemas.find(session.accountId(), session.clusterKey(), session.databaseName(),
schemaName).isPresent();
}
@@ -499,11 +570,12 @@ public class SpectrumQueryPreparation {
}
}
private void dropKinesisSchema(ExternalStatement.DropSchema statement, KinesisSchemaBinding binding,
SpectrumSession session, BackendSql backend) {
private <B extends SchemaBinding> void dropStreamingSchema(ExternalStatement.DropSchema statement, B binding,
SchemaBindingRegistry<B> schemaRegistry,
List<KinesisViewBinding> dependents,
SpectrumSession session, BackendSql backend) {
requireSchemaOwner(backend, binding.schemaName());
// CASCADE takes the streaming views that read the schema with it; RESTRICT stops on their staging tables.
List<KinesisViewBinding> dependents = views.overSchema(session, binding.schemaName());
StringBuilder dropViews = new StringBuilder();
if (statement.cascade()) {
for (KinesisViewBinding dependent : dependents) {
@@ -518,20 +590,20 @@ public class SpectrumQueryPreparation {
dependents.forEach(views::unbindIfCurrent);
}
// a concurrent drop and re-create of the name may have bound a newer schema meanwhile
if (binding.equals(kinesisSchemas.find(session.accountId(), session.clusterKey(), session.databaseName(),
if (binding.equals(schemaRegistry.find(session.accountId(), session.clusterKey(), session.databaseName(),
binding.schemaName()).orElse(null))) {
kinesisSchemas.unbind(session.accountId(), session.clusterKey(), session.databaseName(),
schemaRegistry.unbind(session.accountId(), session.clusterKey(), session.databaseName(),
binding.schemaName());
}
}
private Optional<ExternalReferenceScanner.Reference> streamSource(String select, SpectrumSession session) {
return ExternalReferenceScanner.scan(select, kinesisBindings(session).keySet()).stream().findFirst();
return ExternalReferenceScanner.scan(select, bindingsOf(kinesisSchemas, session).keySet()).stream().findFirst();
}
private void createStreamingView(ExternalStatement.CreateStreamingView view,
Map<String, KinesisSchemaBinding> kinesis, SpectrumSession session,
BackendSql backend) {
Map<String, KinesisSchemaBinding> kinesis,
SpectrumSession session, BackendSql backend) {
if (session.inTransaction()) {
throw new SpectrumSqlException("0A000",
"CREATE MATERIALIZED VIEW over a stream inside a transaction is not supported");
@@ -570,18 +642,10 @@ public class SpectrumQueryPreparation {
views.refresh(view, schema, catalogRegion(session), backend);
}
private Map<String, KinesisSchemaBinding> kinesisBindings(SpectrumSession session) {
Map<String, KinesisSchemaBinding> bindings = new LinkedHashMap<>();
for (KinesisSchemaBinding binding : kinesisSchemas.list(session.accountId(), session.clusterKey(),
session.databaseName())) {
bindings.put(binding.schemaName(), binding);
}
return bindings;
}
private Map<String, ExternalSchemaBinding> bindings(SpectrumSession session) {
Map<String, ExternalSchemaBinding> bindings = new LinkedHashMap<>();
for (ExternalSchemaBinding binding : registry.list(session.accountId(), session.clusterKey(), session.databaseName())) {
private <B extends SchemaBinding> Map<String, B> bindingsOf(SchemaBindingRegistry<B> schemaRegistry,
SpectrumSession session) {
Map<String, B> bindings = new LinkedHashMap<>();
for (B binding : schemaRegistry.list(session.accountId(), session.clusterKey(), session.databaseName())) {
bindings.put(binding.schemaName(), binding);
}
return bindings;
@@ -590,6 +654,7 @@ public class SpectrumQueryPreparation {
public void forgetRuntime(String accountId, String clusterKey) {
registry.removeCluster(accountId, clusterKey);
kinesisSchemas.removeCluster(accountId, clusterKey);
mskSchemas.removeCluster(accountId, clusterKey);
views.forgetCluster(accountId, clusterKey);
materializer.forgetCluster(clusterKey);
}
@@ -0,0 +1,125 @@
package io.floci.aws.services.redshift;
import io.floci.aws.services.redshift.model.Cluster;
import io.floci.aws.services.redshift.spectrum.MskSchemaRegistry;
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.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 external schemas over Amazon MSK through a real cluster connection. */
@QuarkusTest
class RedshiftMskSchemaIntegrationTest {
private static final String ACCOUNT = "000000000000";
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/MskSchemaItRole";
private static final String CLUSTER_ARN = "arn:aws:kafka:us-east-1:000000000000:cluster/orders/abc-123";
@Inject
RedshiftService redshiftService;
@Inject
MskSchemaRegistry mskSchemas;
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) {
return mskSchemas.find(ACCOUNT, ACCOUNT + ":" + clusterId, "dev", schema).isPresent();
}
private static boolean exists(Statement statement, String sql) throws SQLException {
try (ResultSet rows = statement.executeQuery(sql)) {
return rows.next();
}
}
@Test
@Timeout(120)
void createsListsAndDropsAnMskSchema() throws Exception {
clusterId = "it-msk-" + 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 EXTERNAL SCHEMA msk FROM MSK IAM_ROLE '" + ROLE_ARN
+ "' AUTHENTICATION iam CLUSTER_ARN '" + CLUSTER_ARN + "'");
assertTrue(bound("msk"));
assertTrue(exists(statement, "SELECT 1 FROM pg_namespace WHERE nspname = 'msk'"));
try (ResultSet rows = statement.executeQuery(
"SELECT eskind, esoptions FROM svv_external_schemas WHERE schemaname = 'msk'")) {
assertTrue(rows.next());
assertEquals(10, rows.getInt("eskind"));
String options = rows.getString("esoptions");
assertTrue(options.contains(ROLE_ARN));
assertTrue(options.contains(CLUSTER_ARN));
assertTrue(options.contains("IAM"));
assertFalse(rows.next());
}
SQLException duplicate = assertThrows(SQLException.class, () -> statement.execute(
"CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE '" + ROLE_ARN
+ "' AUTHENTICATION iam CLUSTER_ARN '" + CLUSTER_ARN + "'"));
assertEquals("42P06", duplicate.getSQLState());
statement.execute("CREATE EXTERNAL SCHEMA IF NOT EXISTS msk FROM MSK IAM_ROLE '" + ROLE_ARN
+ "' AUTHENTICATION iam CLUSTER_ARN '" + CLUSTER_ARN + "'");
SQLException read = assertThrows(SQLException.class, () -> statement.execute("SELECT * FROM msk.orders"));
assertEquals("0A000", read.getSQLState());
statement.execute("DROP SCHEMA msk");
assertFalse(bound("msk"));
assertFalse(exists(statement, "SELECT 1 FROM pg_namespace WHERE nspname = 'msk'"));
assertFalse(exists(statement, "SELECT 1 FROM svv_external_schemas WHERE schemaname = 'msk'"));
}
}
@Test
@Timeout(120)
void refusesToCreateTheSchemaInsideATransaction() throws Exception {
clusterId = "it-msk-" + 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 EXTERNAL SCHEMA msk FROM MSK IAM_ROLE '" + ROLE_ARN
+ "' AUTHENTICATION iam CLUSTER_ARN '" + CLUSTER_ARN + "'"));
assertEquals("0A000", rejected.getSQLState());
} finally {
connection.rollback();
connection.setAutoCommit(true);
}
assertFalse(bound("msk"));
assertFalse(exists(statement, "SELECT 1 FROM pg_namespace WHERE nspname = 'msk'"));
}
}
}
@@ -70,6 +70,27 @@ class ExternalMetadataWriterTest {
assertThat(sql, containsString("\"tables\":[]"));
}
@Test
void mskSchemaListsAsKindTenWithItsOptionsAndNoTables() throws Exception {
String clusterArn = "arn:aws:kafka:us-east-1:000000000000:cluster/orders/abc-123";
MskSchemaBinding msk = new MskSchemaBinding("000000000000", "000000000000:c", "dev", "msk",
"arn:aws:iam::000000000000:role/R", "IAM", clusterArn);
String sql = writer.refreshMskSql(msk);
JsonNode payload = refreshPayload("msk", sql);
JsonNode options = new ObjectMapper().readTree(payload.path("esoptions").asText());
assertEquals(10, payload.path("eskind").asInt());
assertEquals("", payload.path("databasename").asText());
assertEquals("arn:aws:iam::000000000000:role/R", options.path("IAM_ROLE").asText());
assertEquals("IAM", options.path("AUTHENTICATION").asText());
assertEquals(clusterArn, options.path("CLUSTER_ARN").asText());
assertThat(options.has("PARTITION"), equalTo(false));
assertEquals(0, payload.path("tables").size());
assertEquals(0, payload.path("columns").size());
assertEquals(0, payload.path("partitions").size());
}
@Test
void glueSchemaPayloadLeavesTheKindToTheViewDefault() {
String sql = writer.refreshSql(BINDING, List.of(), Map.of());
@@ -219,7 +240,11 @@ class ExternalMetadataWriterTest {
}
private JsonNode refreshPayload(String sql) throws Exception {
String prefix = "SELECT floci_internal.refresh_external_catalog(E'analytics', E'";
return refreshPayload("analytics", sql);
}
private JsonNode refreshPayload(String schemaName, String sql) throws Exception {
String prefix = "SELECT floci_internal.refresh_external_catalog(E'" + schemaName + "', E'";
String payloadEnd = "'::jsonb)";
String escapedJson = sql.substring(prefix.length(), sql.lastIndexOf(payloadEnd));
return new ObjectMapper().readTree(escapedJson.replace("''", "'").replace("\\\\", "\\"));
@@ -117,6 +117,20 @@ class ExternalReferenceScannerTest {
equalTo(Optional.of(new Reference("analytics", ""))));
}
@Test
void detectsRenamingAnExternalSchemaOrRenamingOntoOne() {
assertThat(ExternalReferenceScanner.writeTarget("ALTER SCHEMA analytics RENAME TO other", SCHEMAS),
equalTo(Optional.of(new Reference("analytics", ""))));
assertThat(ExternalReferenceScanner.writeTarget("ALTER SCHEMA \"Mixed\" RENAME TO other", SCHEMAS),
equalTo(Optional.of(new Reference("Mixed", ""))));
assertThat(ExternalReferenceScanner.writeTarget("ALTER SCHEMA local_schema RENAME TO analytics", SCHEMAS),
equalTo(Optional.of(new Reference("analytics", ""))));
assertThat(ExternalReferenceScanner.writeTarget("ALTER SCHEMA local_schema RENAME TO other", SCHEMAS),
equalTo(Optional.empty()));
assertThat(ExternalReferenceScanner.writeTarget("ALTER SCHEMA analytics OWNER TO admin", SCHEMAS),
equalTo(Optional.empty()));
}
@Test
void ddlOnNativeObjectsIsNotAnExternalWrite() {
assertThat(ExternalReferenceScanner.writeTarget("DROP TABLE public.a, public.b", SCHEMAS), equalTo(Optional.empty()));
@@ -61,6 +61,89 @@ class ExternalStatementParserTest {
.orElseThrow() instanceof ExternalStatement.CreateSchema, equalTo(false));
}
@Test
void parsesCreateExternalSchemaFromMsk() {
String clusterArn = "arn:aws:kafka:us-east-1:000000000000:cluster/orders/abc-123";
ExternalStatement.CreateMskSchema schema = (ExternalStatement.CreateMskSchema) parser.parse(
"CREATE EXTERNAL SCHEMA Msk FROM MSK IAM_ROLE 'arn:aws:iam::000000000000:role/R' "
+ "AUTHENTICATION iam CLUSTER_ARN '" + clusterArn + "';").orElseThrow();
assertThat(schema.schemaName(), equalTo("msk"));
assertThat(schema.iamRoleArn(), equalTo("arn:aws:iam::000000000000:role/R"));
assertThat(schema.authentication(), equalTo("IAM"));
assertThat(schema.clusterArn(), equalTo(clusterArn));
assertThat(schema.ifNotExists(), equalTo(false));
}
@Test
void parsesMskSchemaWithIfNotExistsAuthNoneAndReorderedClauses() {
String clusterArn = "arn:aws-us-gov:kafka:us-gov-west-1:000000000000:cluster/orders/abc-123";
ExternalStatement.CreateMskSchema schema = (ExternalStatement.CreateMskSchema) parser.parse(
"create external schema if not exists \"Msk\"\nfrom msk\n"
+ "cluster_arn '" + clusterArn + "'\n"
+ "authentication none\n"
+ "iam_role 'arn:aws-us-gov:iam::000000000000:role/R'").orElseThrow();
assertThat(schema.schemaName(), equalTo("Msk"));
assertThat(schema.authentication(), equalTo("NONE"));
assertThat(schema.clusterArn(), equalTo(clusterArn));
assertThat(schema.ifNotExists(), equalTo(true));
}
@Test
void parsesMskSchemaWithCommentsAndEscapedQuotes() {
ExternalStatement.CreateMskSchema schema = (ExternalStatement.CreateMskSchema) parser.parse(
"-- leading comment\nCREATE EXTERNAL SCHEMA msk FROM MSK /* inline */\n"
+ "IAM_ROLE 'arn:aws-us-gov:iam::000000000000:role/O''Brien'\n"
+ "AUTHENTICATION IAM\n"
+ "CLUSTER_ARN 'arn:aws-us-gov:kafka:us-gov-west-1:000000000000:cluster/c''1/1' /* tail */;")
.orElseThrow();
assertThat(schema.iamRoleArn(), equalTo("arn:aws-us-gov:iam::000000000000:role/O'Brien"));
assertThat(schema.clusterArn(), equalTo("arn:aws-us-gov:kafka:us-gov-west-1:000000000000:cluster/c'1/1"));
}
@Test
void rejectsUnsupportedMskClausesAndOptions() {
String role = "'arn:aws:iam::000000000000:role/R'";
String cluster = "'arn:aws:kafka:us-east-1:000000000000:cluster/c/1'";
for (String sql : List.of(
"CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE default AUTHENTICATION iam CLUSTER_ARN " + cluster,
"CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE " + role + " AUTHENTICATION mtls CLUSTER_ARN " + cluster,
"CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE " + role + " AUTHENTICATION iam URI 'localhost:9092'",
"CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE " + role + " AUTHENTICATION iam AUTHENTICATION_ARN 'arn:aws:acm:us-east-1:000000000000:certificate/1' CLUSTER_ARN " + cluster,
"CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE " + role + " AUTHENTICATION iam SECRET_ARN 'arn:aws:secretsmanager:us-east-1:000000000000:secret:s' CLUSTER_ARN " + cluster,
"CREATE EXTERNAL SCHEMA kfk FROM KAFKA IAM_ROLE " + role + " AUTHENTICATION none URI 'localhost:9092'")) {
SpectrumSqlException error = assertThrows(SpectrumSqlException.class, () -> parser.parse(sql));
assertThat(sql, error.sqlState(), equalTo("0A000"));
}
}
@Test
void rejectsMalformedOrIncompleteMskSchemas() {
String role = "'arn:aws:iam::000000000000:role/R'";
String cluster = "'arn:aws:kafka:us-east-1:000000000000:cluster/c/1'";
for (String sql : List.of(
"CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE " + role + " AUTHENTICATION iam",
"CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE " + role + " CLUSTER_ARN " + cluster,
"CREATE EXTERNAL SCHEMA msk FROM MSK AUTHENTICATION iam CLUSTER_ARN " + cluster,
"CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE '' AUTHENTICATION iam CLUSTER_ARN " + cluster,
"CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE " + role + " AUTHENTICATION iam CLUSTER_ARN ''",
"CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE " + role + " AUTHENTICATION iam CLUSTER_ARN",
"CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE " + role + " AUTHENTICATION iam CLUSTER_ARN unquoted",
"CREATE EXTERNAL SCHEMA msk FROM MSK PARTITION 'aws' IAM_ROLE " + role + " AUTHENTICATION iam CLUSTER_ARN " + cluster,
"CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE " + role + " AUTHENTICATION scram CLUSTER_ARN " + cluster,
"CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE " + role + " AUTHENTICATION iam AUTHENTICATION none CLUSTER_ARN " + cluster,
"CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE " + role + " IAM_ROLE " + role + " AUTHENTICATION iam CLUSTER_ARN " + cluster,
"CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE " + role + " AUTHENTICATION iam CLUSTER_ARN " + cluster + " CLUSTER_ARN " + cluster,
"CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE " + role + " AUTHENTICATION iam CLUSTER_ARN " + cluster + " EXTRA 'x'",
"CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE " + role + " AUTHENTICATION iam CLUSTER_ARN " + cluster + " URI2 'x'",
"CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE " + role + " AUTHENTICATION iam CLUSTER_ARN " + cluster + " URI=localhost:9092",
"CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE2 " + role + " AUTHENTICATION iam CLUSTER_ARN " + cluster,
"CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE " + role + " AUTHENTICATION iam CLUSTER_ARN " + cluster + "; DROP TABLE x",
"CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE " + role + " AUTHENTICATION iam CLUSTER_ARN 'unterminated")) {
SpectrumSqlException error = assertThrows(SpectrumSqlException.class, () -> parser.parse(sql));
assertThat(sql, error.sqlState(), equalTo("42601"));
}
}
@Test
void parsesCreateTableWithNestedTypesAndFormat() {
ExternalStatement.CreateTable table = (ExternalStatement.CreateTable) parser.parse(
@@ -0,0 +1,119 @@
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 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 MskSchemaRegistryTest {
private static final String ACCOUNT = "000000000000";
private static final String ROLE = "arn:aws:iam::000000000000:role/R";
private static final String CLUSTER = "arn:aws:kafka:us-east-1:000000000000:cluster/orders/abc-123";
private MskSchemaRegistry registry;
@BeforeEach
@SuppressWarnings("unchecked")
void setUp() {
StorageFactory factory = mock(StorageFactory.class);
when(factory.create(eq("redshift"), eq("redshift-msk-schemas.json"), any(TypeReference.class)))
.thenReturn(new AccountAwareStorageBackend<MskSchemaBinding>(new InMemoryStorage<>(), null, ACCOUNT));
registry = new MskSchemaRegistry(factory);
}
private static MskSchemaBinding binding(String cluster, String database, String schema) {
return new MskSchemaBinding(ACCOUNT, cluster, database, schema, ROLE, "IAM", CLUSTER);
}
@Test
void bindsFindsListsAndUnbinds() {
registry.bind(binding("c1", "dev", "b"));
registry.bind(binding("c1", "dev", "a"));
MskSchemaBinding found = registry.find(ACCOUNT, "c1", "dev", "a").orElseThrow();
assertThat(found.iamRoleArn(), equalTo(ROLE));
assertThat(found.authentication(), equalTo("IAM"));
assertThat(found.clusterArn(), equalTo(CLUSTER));
assertThat(registry.list(ACCOUNT, "c1", "dev").stream().map(MskSchemaBinding::schemaName).toList(),
contains("a", "b"));
registry.unbind(ACCOUNT, "c1", "dev", "a");
assertThat(registry.find(ACCOUNT, "c1", "dev", "a").isPresent(), equalTo(false));
assertThat(registry.list(ACCOUNT, "c1", "dev").size(), equalTo(1));
}
@Test
void rejectsADuplicateSchemaInTheSameDatabase() {
registry.bind(binding("c1", "dev", "msk"));
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
() -> registry.bind(binding("c1", "dev", "msk")));
assertThat(error.sqlState(), equalTo("42P06"));
}
@Test
void keepsClustersAndDatabasesApart() {
registry.bind(binding("c1", "dev", "msk"));
registry.bind(binding("c1", "other", "msk"));
registry.bind(binding("c2", "dev", "msk"));
assertThat(registry.list(ACCOUNT, "c1", "dev").size(), equalTo(1));
assertThat(registry.list(ACCOUNT, "c1", "other").size(), equalTo(1));
assertThat(registry.list(ACCOUNT, "c3", "dev"), empty());
}
@Test
void doesNotMixUpComponentsThatContainTheSeparator() {
registry.bind(new MskSchemaBinding(ACCOUNT, "c|1", "dev", "msk", ROLE, "IAM", CLUSTER));
assertThat(registry.find(ACCOUNT, "c", "1|dev", "msk").isPresent(), equalTo(false));
assertThat(registry.find(ACCOUNT, "c|1", "dev", "msk").isPresent(), equalTo(true));
}
@Test
void removesEverySchemaOfAClusterAndKeepsTheOthers() {
registry.bind(binding("c1", "dev", "a"));
registry.bind(binding("c1", "other", "b"));
registry.bind(binding("c2", "dev", "c"));
registry.removeCluster(ACCOUNT, "c1");
assertThat(registry.list(ACCOUNT, "c1", "dev"), empty());
assertThat(registry.list(ACCOUNT, "c1", "other"), empty());
assertThat(registry.list(ACCOUNT, "c2", "dev").size(), equalTo(1));
}
@Test
void clearForgetsEverything() {
registry.bind(binding("c1", "dev", "a"));
registry.clear();
assertThat(registry.list(ACCOUNT, "c1", "dev"), empty());
}
@Test
void validatesRequiredFieldsAndAuthenticationMode() {
assertThrows(IllegalArgumentException.class,
() -> new MskSchemaBinding(ACCOUNT, "c1", "dev", "msk", " ", "IAM", CLUSTER));
assertThrows(IllegalArgumentException.class,
() -> new MskSchemaBinding(ACCOUNT, "c1", "dev", "", ROLE, "IAM", CLUSTER));
assertThrows(IllegalArgumentException.class,
() -> new MskSchemaBinding(ACCOUNT, "c1", "dev", "msk", ROLE, "IAM", " "));
assertThrows(IllegalArgumentException.class,
() -> new MskSchemaBinding(ACCOUNT, "c1", "dev", "msk", ROLE, "MTLS", CLUSTER));
}
}
@@ -0,0 +1,356 @@
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 io.floci.aws.services.kinesis.KinesisService;
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.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class SpectrumMskSchemaPreparationTest {
private static final String ACCOUNT = "000000000000";
private static final String ROLE = "arn:aws:iam::000000000000:role/R";
private static final String CLUSTER = "arn:aws:kafka:us-east-1:000000000000:cluster/orders/abc-123";
private static final SpectrumSession SESSION = new SpectrumSession(ACCOUNT, ACCOUNT + ":c", "dev", List.of(), false);
private static final String CREATE = "CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE '" + ROLE
+ "' AUTHENTICATION iam CLUSTER_ARN '" + CLUSTER + "'";
private ExternalCatalogRegistry glueSchemas;
private KinesisSchemaRegistry kinesisSchemas;
private MskSchemaRegistry mskSchemas;
private KinesisService kinesisService;
private ExternalTableMaterializer materializer;
private BackendSql backend;
private SpectrumQueryPreparation preparation;
@BeforeEach
void setUp() {
glueSchemas = mock(ExternalCatalogRegistry.class);
kinesisSchemas = new KinesisSchemaRegistry(AccountAwareStorageBackend.<KinesisSchemaBinding>inMemory(ACCOUNT));
mskSchemas = new MskSchemaRegistry(AccountAwareStorageBackend.<MskSchemaBinding>inMemory(ACCOUNT));
kinesisService = mock(KinesisService.class);
materializer = mock(ExternalTableMaterializer.class);
backend = mock(BackendSql.class);
when(backend.permitsCachePublication()).thenReturn(true);
ExternalMetadataWriter metadata = new ExternalMetadataWriter(mock(GlueService.class), new ObjectMapper());
KinesisStreamingViews views = new KinesisStreamingViews(
new KinesisViewRegistry(AccountAwareStorageBackend.<KinesisViewBinding>inMemory(ACCOUNT)),
kinesisService, null, null, Clock.systemUTC());
preparation = new SpectrumQueryPreparation(glueSchemas, kinesisSchemas, mskSchemas, materializer,
new ExternalStatementParser(), mock(GlueService.class), metadata, new ExternalCatalogLocks(),
views, (accountId, clusterIdentifier) -> null);
}
private Optional<MskSchemaBinding> bound(String schema) {
return mskSchemas.find(ACCOUNT, SESSION.clusterKey(), "dev", schema);
}
@Test
void createsTheLocalSchemaListsItAsKindTenAndRemembersTheBinding() {
assertThat(preparation.handlesDdl(CREATE, SESSION), equalTo(true));
assertThat(preparation.commandTag(CREATE), equalTo("CREATE EXTERNAL"));
assertThat(preparation.prepare(CREATE, SESSION, backend), equalTo(true));
verify(backend).execute("CREATE SCHEMA \"msk\"");
verify(backend).execute(argThat(sql -> sql.contains("refresh_external_catalog(E'msk'")
&& sql.contains("\"eskind\":10") && sql.contains(CLUSTER)));
MskSchemaBinding binding = bound("msk").orElseThrow();
assertThat(binding.iamRoleArn(), equalTo(ROLE));
assertThat(binding.authentication(), equalTo("IAM"));
assertThat(binding.clusterArn(), equalTo(CLUSTER));
}
@Test
void keepsTheAuthModeTheStatementNames() {
preparation.prepare("CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE '" + ROLE
+ "' AUTHENTICATION none CLUSTER_ARN '" + CLUSTER + "'", SESSION, backend);
MskSchemaBinding binding = bound("msk").orElseThrow();
assertThat(binding.authentication(), equalTo("NONE"));
}
@Test
void doesNotBindUntilTheStatementCommits() {
when(backend.permitsCachePublication()).thenReturn(false);
preparation.prepare(CREATE, SESSION, backend);
assertThat(bound("msk").isPresent(), equalTo(false));
preparation.finishCycle(backend, true);
assertThat(bound("msk").isPresent(), equalTo(true));
}
@Test
void forgetsAPendingSchemaWhenTheTransactionRollsBack() {
when(backend.permitsCachePublication()).thenReturn(false);
preparation.prepare(CREATE, SESSION, backend);
preparation.finishCycle(backend);
preparation.finishCycle(backend, true);
assertThat(bound("msk").isPresent(), equalTo(false));
}
@Test
void rejectsADuplicateSchemaUnlessItIsIfNotExists() {
preparation.prepare(CREATE, SESSION, backend);
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
() -> preparation.prepare(CREATE, SESSION, backend));
assertThat(error.sqlState(), equalTo("42P06"));
assertThat(preparation.prepare("CREATE EXTERNAL SCHEMA IF NOT EXISTS msk FROM MSK IAM_ROLE '" + ROLE
+ "' AUTHENTICATION iam CLUSTER_ARN '" + CLUSTER + "'", SESSION, backend), equalTo(true));
}
@Test
void rejectsANameThatAGlueOrKinesisSchemaAlreadyUses() {
when(glueSchemas.find(ACCOUNT, SESSION.clusterKey(), "dev", "msk")).thenReturn(Optional.of(
new ExternalSchemaBinding(ACCOUNT, SESSION.clusterKey(), "dev", "msk", "lake", ROLE)));
SpectrumSqlException glueCollision = assertThrows(SpectrumSqlException.class,
() -> preparation.prepare(CREATE, SESSION, backend));
assertThat(glueCollision.sqlState(), equalTo("42P06"));
verifyNoInteractions(backend);
kinesisSchemas.bind(new KinesisSchemaBinding(ACCOUNT, SESSION.clusterKey(), "dev", "kds", null, ROLE));
SpectrumSqlException kinesisCollision = assertThrows(SpectrumSqlException.class,
() -> preparation.prepare("CREATE EXTERNAL SCHEMA kds FROM MSK IAM_ROLE '" + ROLE
+ "' AUTHENTICATION iam CLUSTER_ARN '" + CLUSTER + "'", SESSION, backend));
assertThat(kinesisCollision.sqlState(), equalTo("42P06"));
verifyNoInteractions(backend);
}
@Test
void glueAndKinesisSchemasCannotTakeTheNameOfAnMskSchema() {
GlueService glue = mock(GlueService.class);
KinesisStreamingViews views = new KinesisStreamingViews(
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()),
new ExternalCatalogLocks(), views, (accountId, clusterIdentifier) -> null);
preparation.prepare(CREATE, SESSION, backend);
SpectrumSqlException glueError = assertThrows(SpectrumSqlException.class, () -> withGlue.prepare(
"CREATE EXTERNAL SCHEMA msk FROM DATA CATALOG DATABASE 'lake' IAM_ROLE '" + ROLE
+ "' CREATE EXTERNAL DATABASE IF NOT EXISTS", SESSION, backend));
assertThat(glueError.sqlState(), equalTo("42P06"));
verifyNoInteractions(glue);
assertThat(withGlue.prepare("CREATE EXTERNAL SCHEMA IF NOT EXISTS msk FROM DATA CATALOG DATABASE 'lake' "
+ "IAM_ROLE '" + ROLE + "'", SESSION, backend), equalTo(true));
verifyNoInteractions(glue);
SpectrumSqlException kinesisError = assertThrows(SpectrumSqlException.class, () -> withGlue.prepare(
"CREATE EXTERNAL SCHEMA msk FROM KINESIS IAM_ROLE '" + ROLE + "'", SESSION, backend));
assertThat(kinesisError.sqlState(), equalTo("42P06"));
}
@Test
void refusesToCreateTheSchemaInsideATransaction() {
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("0A000"));
verifyNoInteractions(backend);
assertThat(bound("msk").isPresent(), equalTo(false));
}
@Test
void removesTheLocalSchemaWhenItsMetadataCannotBeWritten() {
doThrow(new SpectrumReadException("XX000", "metadata write failed")).when(backend)
.execute(argThat(sql -> sql.contains("refresh_external_catalog")));
assertThrows(SpectrumReadException.class, () -> preparation.prepare(CREATE, SESSION, backend));
verify(backend).execute("DROP SCHEMA \"msk\" CASCADE");
assertThat(bound("msk").isPresent(), equalTo(false));
}
@Test
void dropsTheSchemaItsMetadataAndItsBinding() {
preparation.prepare(CREATE, SESSION, backend);
String drop = "DROP SCHEMA msk";
assertThat(preparation.handlesDdl(drop, SESSION), equalTo(true));
assertThat(preparation.prepare(drop, SESSION, backend), equalTo(true));
verify(backend).execute(argThat(sql -> sql.startsWith("DROP SCHEMA \"msk\" RESTRICT; ")
&& sql.contains("purge_external_schema(E'msk')")));
assertThat(bound("msk").isPresent(), equalTo(false));
}
@Test
void dropsWithCascadeWhenAsked() {
preparation.prepare(CREATE, SESSION, backend);
preparation.prepare("DROP SCHEMA IF EXISTS msk CASCADE", SESSION, backend);
verify(backend).execute(argThat(sql -> sql.startsWith("DROP SCHEMA IF EXISTS \"msk\" CASCADE; ")));
}
@Test
void refusesToDropTheSchemaInsideATransaction() {
preparation.prepare(CREATE, SESSION, backend);
SpectrumSession transaction = new SpectrumSession(ACCOUNT, SESSION.clusterKey(), "dev", List.of(), true);
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
() -> preparation.prepare("DROP SCHEMA msk", transaction, backend));
assertThat(error.sqlState(), equalTo("25001"));
assertThat(bound("msk").isPresent(), equalTo(true));
}
@Test
void keepsTheBindingWhenDropFailsTheSchemaOwnerCheck() {
preparation.prepare(CREATE, SESSION, backend);
doThrow(new SpectrumReadException("42501", "Must be owner of external schema")).when(backend)
.execute(argThat(sql -> sql.startsWith("DO ")));
SpectrumReadException error = assertThrows(SpectrumReadException.class,
() -> preparation.prepare("DROP SCHEMA msk", SESSION, backend));
assertThat(error.sqlState(), equalTo("42501"));
assertThat(bound("msk").isPresent(), equalTo(true));
}
@Test
void refusesCreateExternalTableAndStreamingMaterializedViewsOverAnMskSchema() {
preparation.prepare(CREATE, SESSION, backend);
String createTable = "CREATE EXTERNAL TABLE msk.orders (id INT) STORED AS TEXTFILE LOCATION 's3://bucket/orders/'";
assertThat(preparation.handlesDdl(createTable, SESSION), equalTo(true));
SpectrumSqlException tableError = assertThrows(SpectrumSqlException.class,
() -> preparation.prepare(createTable, SESSION, backend));
assertThat(tableError.sqlState(), equalTo("0A000"));
assertThat(tableError.getMessage(), containsString("CREATE EXTERNAL TABLE"));
String createMv = "CREATE MATERIALIZED VIEW mv AS SELECT * FROM msk.orders";
assertThat(preparation.handlesDdl(createMv, SESSION), equalTo(true));
SpectrumSqlException mvError = assertThrows(SpectrumSqlException.class,
() -> preparation.prepare(createMv, SESSION, backend));
assertThat(mvError.sqlState(), equalTo("0A000"));
assertThat(mvError.getMessage(), containsString("Streaming materialized views over MSK"));
}
@Test
void refusesAMixedKinesisAndMskMaterializedViewBeforeTouchingKinesisOrTheBackend() {
preparation.prepare(CREATE, SESSION, backend);
kinesisSchemas.bind(new KinesisSchemaBinding(ACCOUNT, SESSION.clusterKey(), "dev", "kds", null, ROLE));
clearInvocations(backend);
String mixed = "CREATE MATERIALIZED VIEW mv AS SELECT * FROM kds.events WHERE EXISTS (SELECT 1 FROM msk.orders)";
assertThat(preparation.handlesDdl(mixed, SESSION), equalTo(true));
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
() -> preparation.prepare(mixed, SESSION, backend));
assertThat(error.sqlState(), equalTo("0A000"));
assertThat(error.getMessage(), containsString("Streaming materialized views over MSK"));
verifyNoInteractions(kinesisService, backend);
}
@Test
void refusesRenamingAnMskSchemaAndLeavesItsBindingIntact() {
preparation.prepare(CREATE, SESSION, backend);
String rename = "ALTER SCHEMA msk RENAME TO other";
assertThat(preparation.referencesExternal(rename, SESSION), equalTo(true));
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
() -> preparation.prepare(rename, SESSION, backend));
assertThat(error.sqlState(), equalTo("0A000"));
verify(backend, never()).execute(rename);
assertThat(bound("msk").isPresent(), equalTo(true));
}
@Test
void refusesToReadATopicOutsideAMaterializedView() {
preparation.prepare(CREATE, SESSION, backend);
String read = "SELECT * FROM msk.orders";
assertThat(preparation.referencesExternal(read, SESSION), equalTo(true));
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
() -> preparation.prepare(read, SESSION, backend));
assertThat(error.sqlState(), equalTo("0A000"));
assertThat(error.getMessage(), containsString("msk.orders"));
assertThat(error.getMessage(), containsString("MSK external schema"));
verify(materializer, never()).ensureCurrent(any(), any(), any(), anyString(), anyString(), any());
}
@Test
void refusesEveryStatementThatNamesARelationOfTheSchemaAsASourceOrWriteTarget() {
preparation.prepare(CREATE, SESSION, backend);
for (String sql : List.of("INSERT INTO msk.orders VALUES (1)", "UPDATE msk.orders SET id = 2",
"SELECT * FROM msk.orders JOIN public.b ON true", "CREATE TABLE msk.t (id int)",
"ALTER TABLE t SET SCHEMA msk", "DROP SCHEMA other, msk")) {
assertThat(sql, preparation.referencesExternal(sql, SESSION), equalTo(true));
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
() -> preparation.prepare(sql, SESSION, backend));
assertThat(sql, error.sqlState(), equalTo("0A000"));
}
assertThat(bound("msk").isPresent(), equalTo(true));
}
@Test
void leavesAnUnboundLocalSchemaAloneUnderIfNotExists() {
doThrow(new SpectrumReadException("42P06", "schema \"msk\" already exists")).when(backend)
.execute("CREATE SCHEMA \"msk\"");
assertThat(preparation.prepare("CREATE EXTERNAL SCHEMA IF NOT EXISTS msk FROM MSK IAM_ROLE '" + ROLE
+ "' AUTHENTICATION iam CLUSTER_ARN '" + CLUSTER + "'", SESSION, backend), equalTo(true));
assertThat(bound("msk").isPresent(), equalTo(false));
SpectrumReadException error = assertThrows(SpectrumReadException.class,
() -> preparation.prepare(CREATE, SESSION, backend));
assertThat(error.sqlState(), equalTo("42P06"));
}
@Test
void aDropDoesNotUnbindASchemaThatWasRecreatedMeanwhile() {
preparation.prepare(CREATE, SESSION, backend);
MskSchemaBinding newer = new MskSchemaBinding(ACCOUNT, SESSION.clusterKey(), "dev", "msk",
"arn:aws:iam::000000000000:role/Other", "NONE", CLUSTER);
doAnswer(invocation -> {
mskSchemas.unbind(ACCOUNT, SESSION.clusterKey(), "dev", "msk");
mskSchemas.bind(newer);
return null;
}).when(backend).execute(argThat(sql -> sql.startsWith("DROP SCHEMA \"msk\"")));
preparation.prepare("DROP SCHEMA msk", SESSION, backend);
assertThat(bound("msk").orElseThrow(), equalTo(newer));
}
@Test
void forgetsTheSchemasOfARemovedCluster() {
preparation.prepare(CREATE, SESSION, backend);
preparation.forgetRuntime(ACCOUNT, SESSION.clusterKey());
assertThat(bound("msk").isPresent(), equalTo(false));
}
}