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

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