feat(redshift): add external schemas over Kinesis Data Streams (#8457)

This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-15 20:01:10 -04:00
1 parent cf4e1101a9
commit bcca1bb8d3
17 files changed
+966 -111

No files matched your search

@@ -1,80 +1,13 @@
package io.floci.aws.services.redshift.spectrum;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.core.common.Resettable;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import jakarta.enterprise.context.ApplicationScoped;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
@ApplicationScoped
public class ExternalCatalogRegistry implements Resettable {
private static final char SEPARATOR = '|';
private final AccountAwareStorageBackend<ExternalSchemaBinding> bindings;
public class ExternalCatalogRegistry extends SchemaBindingRegistry<ExternalSchemaBinding> {
public ExternalCatalogRegistry(StorageFactory storageFactory) {
bindings = storageFactory.create("redshift", "redshift-external-schemas.json", new TypeReference<>() { });
}
public synchronized void bind(ExternalSchemaBinding binding) {
String key = key(binding.clusterKey(), binding.databaseName(), binding.schemaName());
if (bindings.getForAccount(binding.accountId(), key).isPresent()) {
throw new SpectrumSqlException("42P06", "schema \"" + binding.schemaName() + "\" already exists");
}
bindings.putForAccount(binding.accountId(), key, binding);
bindings.flush();
}
public Optional<ExternalSchemaBinding> find(String accountId, String clusterKey, String databaseName, String schemaName) {
return bindings.getForAccount(accountId, key(clusterKey, databaseName, schemaName));
}
public List<ExternalSchemaBinding> list(String accountId, String clusterKey, String databaseName) {
String prefix = prefix(clusterKey, databaseName);
return bindings.scanForAccount(accountId, key -> key.startsWith(prefix)).stream()
.sorted(Comparator.comparing(ExternalSchemaBinding::schemaName)).toList();
}
public synchronized void unbind(String accountId, String clusterKey, String databaseName, String schemaName) {
bindings.deleteForAccount(accountId, key(clusterKey, databaseName, schemaName));
bindings.flush();
}
public synchronized void removeCluster(String accountId, String clusterKey) {
String prefix = prefix(clusterKey);
for (String key : bindings.keysForAccount(accountId)) {
if (key.startsWith(prefix)) {
bindings.deleteForAccount(accountId, key);
}
}
bindings.flush();
}
@Override
public synchronized void clear() {
bindings.clear();
bindings.flush();
}
private static String key(String clusterKey, String databaseName, String schemaName) {
return prefix(clusterKey, databaseName) + encode(schemaName);
}
private static String prefix(String clusterKey, String databaseName) {
return prefix(clusterKey) + encode(databaseName) + SEPARATOR;
}
private static String prefix(String clusterKey) {
return encode(clusterKey) + SEPARATOR;
}
/** Percent-encodes a component so a quoted identifier containing the separator cannot collide with another key. */
private static String encode(String component) {
return URLEncoder.encode(component, StandardCharsets.UTF_8);
super(storageFactory.<ExternalSchemaBinding>create("redshift", "redshift-external-schemas.json",
new TypeReference<>() { }));
}
}
@@ -21,6 +21,8 @@ import java.util.Map;
@ApplicationScoped
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;
private final GlueService glueService;
private final ObjectMapper objectMapper;
@@ -39,6 +41,10 @@ public class ExternalMetadataWriter {
run(backend, refreshSql(binding, tables, partitions), false);
}
public void refreshKinesis(BackendSql backend, KinesisSchemaBinding binding) {
run(backend, refreshKinesisSql(binding), false);
}
public void purge(BackendSql backend, String schemaName) {
run(backend, purgeSql(schemaName), true);
}
@@ -59,6 +65,22 @@ public class ExternalMetadataWriter {
return "SELECT floci_internal.purge_external_schema(" + literal(schemaName) + ")";
}
/**
* 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.
*/
String refreshKinesisSql(KinesisSchemaBinding binding) {
Map<String, Object> payload = row(
"eskind", KINESIS_SCHEMA_KIND,
"databasename", "",
"esoptions", json(Map.of("IAM_ROLE", binding.iamRoleArn())),
"tables", List.of(),
"columns", List.of(),
"partitions", List.of());
return "SELECT floci_internal.refresh_external_catalog(" + literal(binding.schemaName()) + ", "
+ literal(json(payload)) + "::jsonb)";
}
String refreshSql(ExternalSchemaBinding binding, List<Table> tables,
Map<String, List<Partition>> partitionsByTable) {
List<Map<String, Object>> tableRows = new ArrayList<>();
@@ -4,7 +4,8 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public record ExternalSchemaBinding(String accountId, String clusterKey, String databaseName,
String schemaName, String glueDatabase, String iamRoleArn) {
String schemaName, String glueDatabase, String iamRoleArn)
implements SchemaBinding {
public ExternalSchemaBinding {
require(accountId, "accountId");
require(clusterKey, "clusterKey");
@@ -5,8 +5,9 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public sealed interface ExternalStatement permits ExternalStatement.CreateSchema, ExternalStatement.CreateTable,
ExternalStatement.AddPartitions, ExternalStatement.DropSchema, ExternalStatement.DropTable {
public sealed interface ExternalStatement permits ExternalStatement.CreateSchema, ExternalStatement.CreateKinesisSchema,
ExternalStatement.CreateTable, ExternalStatement.AddPartitions, ExternalStatement.DropSchema,
ExternalStatement.DropTable {
/** 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));
@@ -19,6 +20,9 @@ public sealed interface ExternalStatement permits ExternalStatement.CreateSchema
}
record CreateSchema(String schemaName, String glueDatabase, String iamRoleArn, boolean createDatabaseIfNotExists,
boolean ifNotExists) implements ExternalStatement { }
/** {@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 CreateTable(String schemaName, String tableName, List<ColumnDefinition> columns,
List<ColumnDefinition> partitionColumns, TableFormat format, String location,
String delimiter, String serde, Map<String, String> properties,
@@ -14,6 +14,7 @@ import java.util.regex.Pattern;
@ApplicationScoped
public class ExternalStatementParser {
private static final Pattern CREATE_SCHEMA = Pattern.compile("(?is)^\\s*CREATE\\s+EXTERNAL\\s+SCHEMA\\s+(IF\\s+NOT\\s+EXISTS\\s+)?(.+?)\\s+FROM\\s+DATA\\s+CATALOG\\s+DATABASE\\s+'((?:''|[^'])*)'(?:\\s+REGION\\s+'(?:''|[^'])*')?\\s+IAM_ROLE\\s+(.+?)(\\s+CREATE\\s+EXTERNAL\\s+DATABASE\\s+IF\\s+NOT\\s+EXISTS)?\\s*;?\\s*$");
private static final Pattern CREATE_KINESIS_SCHEMA = Pattern.compile("(?is)^\\s*CREATE\\s+EXTERNAL\\s+SCHEMA\\s+(IF\\s+NOT\\s+EXISTS\\s+)?(.+?)\\s+FROM\\s+KINESIS(?:\\s+REGION\\s+'((?:''|[^'])*)')?\\s+IAM_ROLE\\s+(.+?)\\s*;?\\s*$");
private static final Pattern CREATE_EXTERNAL_TABLE = Pattern.compile("(?is)^\\s*CREATE\\s+EXTERNAL\\s+TABLE\\b.*");
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*\\(");
@@ -41,17 +42,17 @@ public class ExternalStatementParser {
String text = stripLeadingComments(sql);
Matcher schema = CREATE_SCHEMA.matcher(text);
if (schema.matches()) {
String role = schema.group(4).trim();
if (role.equalsIgnoreCase("default")) {
throw new SpectrumSqlException("0A000", "IAM_ROLE DEFAULT is not supported");
}
if (!QUOTED_LITERAL.matcher(role).matches()) {
throw new SpectrumSqlException("42601", "IAM_ROLE must be a single quoted role ARN");
}
return Optional.of(new ExternalStatement.CreateSchema(identifier(schema.group(2)),
schema.group(3).replace("''", "'"), unquote(role), schema.group(5) != null,
schema.group(3).replace("''", "'"), roleArn(schema.group(4)), schema.group(5) != null,
schema.group(1) != null));
}
Matcher kinesis = CREATE_KINESIS_SCHEMA.matcher(text);
if (kinesis.matches()) {
String region = kinesis.group(3);
return Optional.of(new ExternalStatement.CreateKinesisSchema(identifier(kinesis.group(2)),
region == null ? null : region.replace("''", "'"), roleArn(kinesis.group(4)),
kinesis.group(1) != null));
}
if (CREATE_EXTERNAL_TABLE.matcher(text).matches()) {
return Optional.of(parseTable(text));
}
@@ -123,6 +124,21 @@ public class ExternalStatementParser {
format, location, delimiter, serde, properties, serdeProperties(tail));
}
private static String roleArn(String clause) {
String role = clause.trim();
if (role.equalsIgnoreCase("default")) {
throw new SpectrumSqlException("0A000", "IAM_ROLE DEFAULT is not supported");
}
if (!QUOTED_LITERAL.matcher(role).matches()) {
throw new SpectrumSqlException("42601", "IAM_ROLE must be a single quoted role ARN");
}
String arn = unquote(role);
if (arn.isBlank()) {
throw new SpectrumSqlException("42601", "IAM_ROLE must be a single quoted role ARN");
}
return arn;
}
private static String stripLeadingComments(String sql) {
String text = sql.trim();
while (true) {
@@ -0,0 +1,27 @@
package io.floci.aws.services.redshift.spectrum;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* An external schema over Kinesis Data Streams. 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.
* {@code region} is null when the schema names none, which leaves the cluster's own Region.
*/
@RegisterForReflection
public record KinesisSchemaBinding(String accountId, String clusterKey, String databaseName,
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");
}
}
}
@@ -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 KinesisSchemaRegistry extends SchemaBindingRegistry<KinesisSchemaBinding> {
@Inject
public KinesisSchemaRegistry(StorageFactory storageFactory) {
super(storageFactory.<KinesisSchemaBinding>create("redshift", "redshift-kinesis-schemas.json",
new TypeReference<>() { }));
}
KinesisSchemaRegistry(AccountAwareStorageBackend<KinesisSchemaBinding> bindings) {
super(bindings);
}
}
@@ -0,0 +1,12 @@
package io.floci.aws.services.redshift.spectrum;
/** What every external schema binding records about where its schema lives. */
interface SchemaBinding {
String accountId();
String clusterKey();
String databaseName();
String schemaName();
}
@@ -0,0 +1,82 @@
package io.floci.aws.services.redshift.spectrum;
import io.floci.aws.core.common.Resettable;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
/** Stores the bindings of one kind of external schema, keyed by cluster, database and schema name. */
abstract class SchemaBindingRegistry<B extends SchemaBinding> implements Resettable {
private static final char SEPARATOR = '|';
private final AccountAwareStorageBackend<B> bindings;
/** Lets CDI proxy the application-scoped subclasses; the proxy never reads the field. */
SchemaBindingRegistry() {
this.bindings = null;
}
SchemaBindingRegistry(AccountAwareStorageBackend<B> bindings) {
this.bindings = bindings;
}
public synchronized void bind(B binding) {
String key = key(binding.clusterKey(), binding.databaseName(), binding.schemaName());
if (bindings.getForAccount(binding.accountId(), key).isPresent()) {
throw new SpectrumSqlException("42P06", "schema \"" + binding.schemaName() + "\" already exists");
}
bindings.putForAccount(binding.accountId(), key, binding);
bindings.flush();
}
public Optional<B> find(String accountId, String clusterKey, String databaseName, String schemaName) {
return bindings.getForAccount(accountId, key(clusterKey, databaseName, schemaName));
}
public List<B> list(String accountId, String clusterKey, String databaseName) {
String prefix = prefix(clusterKey, databaseName);
return bindings.scanForAccount(accountId, key -> key.startsWith(prefix)).stream()
.sorted(Comparator.comparing(SchemaBinding::schemaName)).toList();
}
public synchronized void unbind(String accountId, String clusterKey, String databaseName, String schemaName) {
bindings.deleteForAccount(accountId, key(clusterKey, databaseName, schemaName));
bindings.flush();
}
public synchronized void removeCluster(String accountId, String clusterKey) {
String prefix = prefix(clusterKey);
for (String key : bindings.keysForAccount(accountId)) {
if (key.startsWith(prefix)) {
bindings.deleteForAccount(accountId, key);
}
}
bindings.flush();
}
@Override
public synchronized void clear() {
bindings.clear();
bindings.flush();
}
private static String key(String clusterKey, String databaseName, String schemaName) {
return prefix(clusterKey, databaseName) + encode(schemaName);
}
private static String prefix(String clusterKey, String databaseName) {
return prefix(clusterKey) + encode(databaseName) + SEPARATOR;
}
private static String prefix(String clusterKey) {
return encode(clusterKey) + SEPARATOR;
}
/** Percent-encodes a component so a quoted identifier containing the separator cannot collide with another key. */
private static String encode(String component) {
return URLEncoder.encode(component, StandardCharsets.UTF_8);
}
}
@@ -3,6 +3,7 @@ package io.floci.aws.services.redshift.spectrum;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.PostgresWire;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.services.glue.GlueService;
import io.floci.aws.services.glue.model.Database;
import io.floci.aws.services.glue.model.Partition;
@@ -27,7 +28,9 @@ import java.util.function.BiFunction;
@ApplicationScoped
public class SpectrumQueryPreparation {
private static final Logger LOG = Logger.getLogger(SpectrumQueryPreparation.class);
private static final String DUPLICATE_SCHEMA = "42P06";
private final ExternalCatalogRegistry registry;
private final KinesisSchemaRegistry kinesisSchemas;
private final ExternalTableMaterializer materializer;
private final ExternalStatementParser parser;
private final GlueService glue;
@@ -35,7 +38,8 @@ public class SpectrumQueryPreparation {
private final ExternalCatalogLocks catalogLocks;
/** The Region of an account's cluster, by its identifier; null when it isn't known. */
private final BiFunction<String, String, String> clusterRegion;
private final Map<BackendSql, List<ExternalSchemaBinding>> pendingBindings = new ConcurrentHashMap<>();
/** What to bind once the statement that created each schema has committed, by backend. */
private final Map<BackendSql, List<Runnable>> pendingBindings = new ConcurrentHashMap<>();
public SpectrumQueryPreparation(ExternalCatalogRegistry registry, ExternalTableMaterializer materializer,
ExternalStatementParser parser, GlueService glue, ExternalMetadataWriter metadata) {
@@ -45,22 +49,33 @@ public class SpectrumQueryPreparation {
public SpectrumQueryPreparation(ExternalCatalogRegistry registry, ExternalTableMaterializer materializer,
ExternalStatementParser parser, GlueService glue, ExternalMetadataWriter metadata,
ExternalCatalogLocks catalogLocks) {
this(registry, materializer, parser, glue, metadata, catalogLocks, (accountId, clusterIdentifier) -> null);
this(registry, new KinesisSchemaRegistry(AccountAwareStorageBackend.<KinesisSchemaBinding>inMemory("000000000000")),
materializer, parser, glue, metadata, catalogLocks, (accountId, clusterIdentifier) -> null);
}
@Inject
public SpectrumQueryPreparation(ExternalCatalogRegistry registry, ExternalTableMaterializer materializer,
ExternalStatementParser parser, GlueService glue, ExternalMetadataWriter metadata,
public SpectrumQueryPreparation(ExternalCatalogRegistry registry, KinesisSchemaRegistry kinesisSchemas,
ExternalTableMaterializer materializer, ExternalStatementParser parser,
GlueService glue, ExternalMetadataWriter metadata,
ExternalCatalogLocks catalogLocks, Instance<RedshiftService> redshift) {
this(registry, materializer, parser, glue, metadata, catalogLocks,
this(registry, kinesisSchemas, materializer, parser, glue, metadata, catalogLocks,
(accountId, clusterIdentifier) -> redshift.get().clusterRegion(accountId, clusterIdentifier).orElse(null));
}
SpectrumQueryPreparation(ExternalCatalogRegistry registry, ExternalTableMaterializer materializer,
ExternalStatementParser parser, GlueService glue, ExternalMetadataWriter metadata,
ExternalCatalogLocks catalogLocks, BiFunction<String, String, String> clusterRegion) {
this(registry, new KinesisSchemaRegistry(AccountAwareStorageBackend.<KinesisSchemaBinding>inMemory("000000000000")),
materializer, parser, glue, metadata, catalogLocks, clusterRegion);
}
SpectrumQueryPreparation(ExternalCatalogRegistry registry, KinesisSchemaRegistry kinesisSchemas,
ExternalTableMaterializer materializer, ExternalStatementParser parser,
GlueService glue, ExternalMetadataWriter metadata, ExternalCatalogLocks catalogLocks,
BiFunction<String, String, String> clusterRegion) {
this.clusterRegion = clusterRegion;
this.registry = registry;
this.kinesisSchemas = kinesisSchemas;
this.materializer = materializer;
this.parser = parser;
this.glue = glue;
@@ -104,18 +119,22 @@ public class SpectrumQueryPreparation {
public boolean referencesExternal(String sql, SpectrumSession session) {
Set<String> schemas = bindings(session).keySet();
Set<String> kinesisSchemaNames = kinesisBindings(session).keySet();
return !ExternalReferenceScanner.scan(sql, schemas).isEmpty()
|| ExternalReferenceScanner.writeTarget(sql, schemas).isPresent();
|| !ExternalReferenceScanner.scan(sql, kinesisSchemaNames).isEmpty()
|| ExternalReferenceScanner.writeTarget(sql, externalSchemaNames(schemas, kinesisSchemaNames)).isPresent();
}
public boolean handlesDdl(String sql, SpectrumSession session) {
ExternalStatement statement = parser.parse(sql).orElse(null);
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());
case ExternalStatement.DropSchema schema -> bindings(session).containsKey(schema.schemaName())
|| kinesisBindings(session).containsKey(schema.schemaName());
case null -> false;
};
}
@@ -134,6 +153,16 @@ public class SpectrumQueryPreparation {
if (statement.orElse(null) instanceof ExternalStatement.CreateSchema schema) {
return createSchema(schema, session, backend);
}
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.DropSchema schema
&& kinesis.containsKey(schema.schemaName())) {
rejectTransaction(session);
dropKinesisSchema(schema, kinesis.get(schema.schemaName()), session, backend);
return true;
}
Map<String, ExternalSchemaBinding> bindings = bindings(session);
if (statement.orElse(null) instanceof ExternalStatement.CreateTable && session.inTransaction()) {
// Legacy-catalog tables are saved immediately too, so a rollback would leave them behind.
@@ -166,7 +195,17 @@ public class SpectrumQueryPreparation {
}
case null, default -> { }
}
Optional<ExternalReferenceScanner.Reference> write = ExternalReferenceScanner.writeTarget(sql, bindings.keySet());
// A stream is read through a materialized view, so a plain statement on a relation of the schema is
// refused rather than left to fail as a missing table in PostgreSQL. The scanner does not tell a stream
// from any other relation, and Redshift keeps no user tables in such a schema.
Set<ExternalReferenceScanner.Reference> streams = ExternalReferenceScanner.scan(sql, kinesis.keySet());
if (!streams.isEmpty()) {
ExternalReferenceScanner.Reference stream = streams.iterator().next();
throw new SpectrumSqlException("0A000", "\"" + stream.schema() + "." + stream.table()
+ "\" is in a Kinesis external schema, whose streams are only read through a streaming materialized view");
}
Optional<ExternalReferenceScanner.Reference> write = ExternalReferenceScanner.writeTarget(sql,
externalSchemaNames(bindings.keySet(), kinesis.keySet()));
if (write.isPresent()) {
throw new SpectrumSqlException("0A000", "Writes to external relation \""
+ write.get().schema() + "." + write.get().table() + "\" are not supported");
@@ -190,6 +229,12 @@ public class SpectrumQueryPreparation {
return false;
}
private static Set<String> externalSchemaNames(Set<String> glueSchemas, Set<String> kinesisSchemas) {
Set<String> names = new HashSet<>(glueSchemas);
names.addAll(kinesisSchemas);
return names;
}
private static void rejectTransaction(SpectrumSession session) {
if (session.inTransaction()) {
throw new SpectrumSqlException("25001", "External catalog changes cannot run inside a transaction block");
@@ -323,13 +368,8 @@ public class SpectrumQueryPreparation {
if (session.inTransaction()) {
throw new SpectrumSqlException("0A000", "CREATE EXTERNAL SCHEMA inside a transaction is not supported");
}
Optional<ExternalSchemaBinding> existing = registry.find(session.accountId(), session.clusterKey(),
session.databaseName(), schema.schemaName());
if (existing.isPresent()) {
if (schema.ifNotExists()) {
return true;
}
throw new SpectrumSqlException("42P06", "schema \"" + schema.schemaName() + "\" already exists");
if (schemaExists(session, schema.schemaName())) {
return existingSchemaOutcome(schema.schemaName(), schema.ifNotExists());
}
try {
glue.getDatabase(schema.glueDatabase());
@@ -347,19 +387,89 @@ public class SpectrumQueryPreparation {
}
ExternalSchemaBinding binding = new ExternalSchemaBinding(session.accountId(), session.clusterKey(),
session.databaseName(), schema.schemaName(), schema.glueDatabase(), schema.iamRoleArn());
backend.execute("CREATE SCHEMA " + ExternalTableMaterializer.quote(schema.schemaName()));
createBoundSchema(backend, schema.schemaName(), schema.ifNotExists(),
() -> metadata.refresh(backend, session.accountId(), binding), () -> registry.bind(binding));
return true;
}
private boolean createKinesisSchema(ExternalStatement.CreateKinesisSchema 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());
}
KinesisSchemaBinding binding = new KinesisSchemaBinding(session.accountId(), session.clusterKey(),
session.databaseName(), schema.schemaName(), schema.region(), schema.iamRoleArn());
createBoundSchema(backend, schema.schemaName(), schema.ifNotExists(),
() -> metadata.refreshKinesis(backend, binding), () -> kinesisSchemas.bind(binding));
return true;
}
/** A name is taken when either 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();
}
private static boolean existingSchemaOutcome(String schemaName, boolean ifNotExists) {
if (ifNotExists) {
return true;
}
throw new SpectrumSqlException("42P06", "schema \"" + schemaName + "\" already exists");
}
/**
* Creates the local schema, publishes its metadata, and binds it once committed; removes it again on failure.
* A local schema of that name that no binding owns is left alone under IF NOT EXISTS.
*/
private void createBoundSchema(BackendSql backend, String schemaName, boolean ifNotExists,
Runnable refreshMetadata, Runnable bind) {
try {
metadata.refresh(backend, session.accountId(), binding);
bindWhenCommitted(backend, binding);
} catch (RuntimeException exception) {
try {
backend.execute("DROP SCHEMA " + ExternalTableMaterializer.quote(schema.schemaName()) + " CASCADE");
} catch (RuntimeException cleanupFailure) {
LOG.warnv(cleanupFailure, "Could not clean up failed external schema {0}", schema.schemaName());
backend.execute("CREATE SCHEMA " + ExternalTableMaterializer.quote(schemaName));
} catch (SpectrumReadException exception) {
if (ifNotExists && DUPLICATE_SCHEMA.equals(exception.sqlState())) {
return;
}
throw exception;
}
return true;
try {
refreshMetadata.run();
bindWhenCommitted(backend, bind);
} catch (RuntimeException exception) {
try {
backend.execute("DROP SCHEMA " + ExternalTableMaterializer.quote(schemaName) + " CASCADE");
} catch (RuntimeException cleanupFailure) {
LOG.warnv(cleanupFailure, "Could not clean up failed external schema {0}", schemaName);
}
throw exception;
}
}
private void dropKinesisSchema(ExternalStatement.DropSchema statement, KinesisSchemaBinding binding,
SpectrumSession session, BackendSql backend) {
requireSchemaOwner(backend, binding.schemaName());
// One implicit PostgreSQL transaction keeps the local schema and its SVV metadata in sync.
backend.execute("DROP SCHEMA " + (statement.ifExists() ? "IF EXISTS " : "")
+ ExternalTableMaterializer.quote(binding.schemaName()) + (statement.cascade() ? " CASCADE" : " RESTRICT")
+ "; " + metadata.purgeSql(binding.schemaName()));
// 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(),
binding.schemaName()).orElse(null))) {
kinesisSchemas.unbind(session.accountId(), session.clusterKey(), session.databaseName(),
binding.schemaName());
}
}
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) {
@@ -372,6 +482,7 @@ public class SpectrumQueryPreparation {
public void forgetRuntime(String accountId, String clusterKey) {
registry.removeCluster(accountId, clusterKey);
kinesisSchemas.removeCluster(accountId, clusterKey);
materializer.forgetCluster(clusterKey);
}
@@ -383,12 +494,12 @@ public class SpectrumQueryPreparation {
* A backend that shares the client's transaction can still roll the schema back, so the binding is held
* until {@link #finishCycle(BackendSql, boolean)} sees the commit. Any other backend has committed already.
*/
private void bindWhenCommitted(BackendSql backend, ExternalSchemaBinding binding) {
private void bindWhenCommitted(BackendSql backend, Runnable bind) {
if (backend.permitsCachePublication()) {
registry.bind(binding);
bind.run();
return;
}
pendingBindings.computeIfAbsent(backend, ignored -> new CopyOnWriteArrayList<>()).add(binding);
pendingBindings.computeIfAbsent(backend, ignored -> new CopyOnWriteArrayList<>()).add(bind);
}
/** The transaction rolled back: drop everything staged for it. */
@@ -398,9 +509,9 @@ public class SpectrumQueryPreparation {
}
public void finishCycle(BackendSql backend, boolean committed) {
List<ExternalSchemaBinding> completed = pendingBindings.remove(backend);
List<Runnable> completed = pendingBindings.remove(backend);
if (committed && completed != null) {
completed.forEach(registry::bind);
completed.forEach(Runnable::run);
}
materializer.finishCycle(backend, committed);
}