mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(redshift): add external schemas over Kinesis Data Streams (#8457)
This commit is contained in:
1 parent
cf4e1101a9
commit
bcca1bb8d3
17 files changed
+966
-111
No files matched your search
@@ -1007,6 +1007,36 @@ Glue and PostgreSQL updates do not form a distributed transaction: an infrastruc
|
||||
one store changes can require retrying the command. The legacy Phase 1 catalog does not gain these
|
||||
lifecycle operations.
|
||||
|
||||
### External schemas over Kinesis Data Streams
|
||||
|
||||
Streaming ingestion from Kinesis Data Streams starts with an external schema that maps to the streaming
|
||||
source. This part adds that schema; the streaming materialized view and `REFRESH` that read from it are
|
||||
not implemented yet.
|
||||
|
||||
```sql
|
||||
CREATE EXTERNAL SCHEMA [IF NOT EXISTS] kds
|
||||
FROM KINESIS
|
||||
[REGION 'us-west-2']
|
||||
IAM_ROLE 'arn:aws:iam::123456789012:role/StreamRole';
|
||||
```
|
||||
|
||||
`CREATE EXTERNAL SCHEMA` creates a local PostgreSQL schema, remembers the role and the optional Region, and
|
||||
lists the schema in `svv_external_schemas` with `eskind` 9 and the role in `esoptions`. Without `REGION` the
|
||||
schema uses the cluster's own Region. `DROP SCHEMA [IF EXISTS] kds [CASCADE | RESTRICT]` removes the local
|
||||
schema, its metadata row and its registration; `RESTRICT` is the default, so a schema that holds objects is
|
||||
kept, as in Redshift.
|
||||
|
||||
- `IAM_ROLE DEFAULT` is not supported. Name the role ARN in a single-quoted literal.
|
||||
- The role is not checked when the schema is created. Nothing reads the stream yet, so no Kinesis permission
|
||||
is evaluated.
|
||||
- A statement that names a relation of the schema as a source (`SELECT * FROM kds.my_stream`,
|
||||
`INSERT INTO kds.t`, `UPDATE kds.t`) is refused with SQLSTATE `0A000`. Redshift reads a stream through a
|
||||
streaming materialized view, and keeps no user tables in such a schema.
|
||||
- `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.
|
||||
|
||||
### COPY from S3
|
||||
|
||||
`COPY <table> [(<columns>)] FROM 's3://<bucket>/<keyOrPrefix>' [options]` sent over the Simple
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
+140
-29
@@ -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);
|
||||
}
|
||||
|
||||
@@ -396,7 +396,7 @@ RETURNS void LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, pg_temp
|
||||
$$;
|
||||
|
||||
CREATE OR REPLACE VIEW pg_catalog.svv_external_schemas AS
|
||||
SELECT n.oid AS esoid, 1::smallint AS eskind, n.nspname AS schemaname,
|
||||
SELECT n.oid AS esoid, COALESCE((c.payload->>'eskind')::smallint, 1::smallint) AS eskind, n.nspname AS schemaname,
|
||||
n.nspowner::integer AS esowner, c.payload->>'databasename' AS databasename,
|
||||
c.payload->>'esoptions' AS esoptions
|
||||
FROM floci_internal.external_catalog c
|
||||
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
package io.floci.aws.services.redshift;
|
||||
|
||||
import io.floci.aws.services.redshift.model.Cluster;
|
||||
import io.floci.aws.services.redshift.spectrum.KinesisSchemaRegistry;
|
||||
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 Kinesis through a real cluster connection. */
|
||||
@QuarkusTest
|
||||
class RedshiftKinesisSchemaIntegrationTest {
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/KinesisSchemaItRole";
|
||||
|
||||
@Inject
|
||||
RedshiftService redshiftService;
|
||||
|
||||
@Inject
|
||||
KinesisSchemaRegistry kinesisSchemas;
|
||||
|
||||
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 kinesisSchemas.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 createsListsAndDropsAKinesisSchema() throws Exception {
|
||||
clusterId = "it-kds-" + 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 kds FROM KINESIS REGION 'us-west-2' IAM_ROLE '" + ROLE_ARN + "'");
|
||||
|
||||
assertTrue(bound("kds"));
|
||||
assertTrue(exists(statement, "SELECT 1 FROM pg_namespace WHERE nspname = 'kds'"));
|
||||
try (ResultSet rows = statement.executeQuery(
|
||||
"SELECT eskind, esoptions FROM svv_external_schemas WHERE schemaname = 'kds'")) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals(9, rows.getInt("eskind"));
|
||||
assertTrue(rows.getString("esoptions").contains(ROLE_ARN));
|
||||
assertFalse(rows.next());
|
||||
}
|
||||
|
||||
SQLException duplicate = assertThrows(SQLException.class, () -> statement.execute(
|
||||
"CREATE EXTERNAL SCHEMA kds FROM KINESIS IAM_ROLE '" + ROLE_ARN + "'"));
|
||||
assertEquals("42P06", duplicate.getSQLState());
|
||||
statement.execute("CREATE EXTERNAL SCHEMA IF NOT EXISTS kds FROM KINESIS IAM_ROLE '" + ROLE_ARN + "'");
|
||||
|
||||
SQLException read = assertThrows(SQLException.class, () -> statement.execute("SELECT * FROM kds.my_stream"));
|
||||
assertEquals("0A000", read.getSQLState());
|
||||
|
||||
statement.execute("DROP SCHEMA kds");
|
||||
|
||||
assertFalse(bound("kds"));
|
||||
assertFalse(exists(statement, "SELECT 1 FROM pg_namespace WHERE nspname = 'kds'"));
|
||||
assertFalse(exists(statement, "SELECT 1 FROM svv_external_schemas WHERE schemaname = 'kds'"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(120)
|
||||
void refusesToCreateTheSchemaInsideATransaction() throws Exception {
|
||||
clusterId = "it-kds-" + 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 kds FROM KINESIS IAM_ROLE '" + ROLE_ARN + "'"));
|
||||
assertEquals("0A000", rejected.getSQLState());
|
||||
} finally {
|
||||
connection.rollback();
|
||||
connection.setAutoCommit(true);
|
||||
}
|
||||
assertFalse(bound("kds"));
|
||||
assertFalse(exists(statement, "SELECT 1 FROM pg_namespace WHERE nspname = 'kds'"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -56,6 +56,27 @@ class ExternalMetadataWriterTest {
|
||||
assertThat(sql.contains("INSERT INTO floci_internal."), equalTo(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void kinesisSchemaListsAsKindNineWithItsRoleAndNoTables() {
|
||||
KinesisSchemaBinding kinesis = new KinesisSchemaBinding("000000000000", "000000000000:c", "dev", "kds",
|
||||
"us-west-2", "arn:aws:iam::000000000000:role/R");
|
||||
|
||||
String sql = writer.refreshKinesisSql(kinesis);
|
||||
|
||||
assertThat(sql, containsString("SELECT floci_internal.refresh_external_catalog(E'kds'"));
|
||||
assertThat(sql, containsString("\"eskind\":9"));
|
||||
assertThat(sql, containsString("\"databasename\":\"\""));
|
||||
assertThat(sql, containsString("IAM_ROLE"));
|
||||
assertThat(sql, containsString("\"tables\":[]"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void glueSchemaPayloadLeavesTheKindToTheViewDefault() {
|
||||
String sql = writer.refreshSql(BINDING, List.of(), Map.of());
|
||||
|
||||
assertThat(sql.contains("eskind"), equalTo(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void refreshSqlUsesPartitionStorageSettings() throws Exception {
|
||||
StorageDescriptor tableDescriptor = new StorageDescriptor();
|
||||
|
||||
+41
@@ -6,6 +6,7 @@ import java.util.List;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class ExternalStatementParserTest {
|
||||
@@ -20,6 +21,46 @@ class ExternalStatementParserTest {
|
||||
assertThat(schema.createDatabaseIfNotExists(), equalTo(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parsesCreateExternalSchemaFromKinesis() {
|
||||
ExternalStatement.CreateKinesisSchema schema = (ExternalStatement.CreateKinesisSchema) parser.parse(
|
||||
"CREATE EXTERNAL SCHEMA Kds FROM KINESIS IAM_ROLE 'arn:aws:iam::000000000000:role/R';").orElseThrow();
|
||||
assertThat(schema.schemaName(), equalTo("kds"));
|
||||
assertThat(schema.iamRoleArn(), equalTo("arn:aws:iam::000000000000:role/R"));
|
||||
assertThat(schema.region(), nullValue());
|
||||
assertThat(schema.ifNotExists(), equalTo(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parsesKinesisSchemaWithRegionAndIfNotExists() {
|
||||
ExternalStatement.CreateKinesisSchema schema = (ExternalStatement.CreateKinesisSchema) parser.parse(
|
||||
"create external schema if not exists \"Kds\"\nfrom kinesis\nregion 'us-west-2'\n"
|
||||
+ "iam_role 'arn:aws:iam::000000000000:role/R'").orElseThrow();
|
||||
assertThat(schema.schemaName(), equalTo("Kds"));
|
||||
assertThat(schema.region(), equalTo("us-west-2"));
|
||||
assertThat(schema.ifNotExists(), equalTo(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsTheDefaultRoleOfAKinesisSchema() {
|
||||
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
|
||||
() -> parser.parse("CREATE EXTERNAL SCHEMA kds FROM KINESIS IAM_ROLE default"));
|
||||
assertThat(error.sqlState(), equalTo("0A000"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsAKinesisSchemaWithoutAQuotedRole() {
|
||||
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
|
||||
() -> parser.parse("CREATE EXTERNAL SCHEMA kds FROM KINESIS IAM_ROLE arn:aws:iam::000000000000:role/R"));
|
||||
assertThat(error.sqlState(), equalTo("42601"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotTreatAKinesisSchemaAsADataCatalogSchema() {
|
||||
assertThat(parser.parse("CREATE EXTERNAL SCHEMA kds FROM KINESIS IAM_ROLE 'arn:aws:iam::000000000000:role/R'")
|
||||
.orElseThrow() instanceof ExternalStatement.CreateSchema, equalTo(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parsesCreateTableWithNestedTypesAndFormat() {
|
||||
ExternalStatement.CreateTable table = (ExternalStatement.CreateTable) parser.parse(
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
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.hamcrest.Matchers.nullValue;
|
||||
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 KinesisSchemaRegistryTest {
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String ROLE = "arn:aws:iam::000000000000:role/R";
|
||||
private KinesisSchemaRegistry registry;
|
||||
|
||||
@BeforeEach
|
||||
@SuppressWarnings("unchecked")
|
||||
void setUp() {
|
||||
StorageFactory factory = mock(StorageFactory.class);
|
||||
when(factory.create(eq("redshift"), eq("redshift-kinesis-schemas.json"), any(TypeReference.class)))
|
||||
.thenReturn(new AccountAwareStorageBackend<KinesisSchemaBinding>(new InMemoryStorage<>(), null, ACCOUNT));
|
||||
registry = new KinesisSchemaRegistry(factory);
|
||||
}
|
||||
|
||||
private static KinesisSchemaBinding binding(String cluster, String database, String schema) {
|
||||
return new KinesisSchemaBinding(ACCOUNT, cluster, database, schema, null, ROLE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void bindsFindsListsAndUnbinds() {
|
||||
registry.bind(binding("c1", "dev", "b"));
|
||||
registry.bind(binding("c1", "dev", "a"));
|
||||
|
||||
assertThat(registry.find(ACCOUNT, "c1", "dev", "a").orElseThrow().iamRoleArn(), equalTo(ROLE));
|
||||
assertThat(registry.list(ACCOUNT, "c1", "dev").stream().map(KinesisSchemaBinding::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", "kds"));
|
||||
|
||||
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
|
||||
() -> registry.bind(binding("c1", "dev", "kds")));
|
||||
|
||||
assertThat(error.sqlState(), equalTo("42P06"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void keepsClustersAndDatabasesApart() {
|
||||
registry.bind(binding("c1", "dev", "kds"));
|
||||
registry.bind(binding("c1", "other", "kds"));
|
||||
registry.bind(binding("c2", "dev", "kds"));
|
||||
|
||||
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 KinesisSchemaBinding(ACCOUNT, "c|1", "dev", "kds", null, ROLE));
|
||||
|
||||
assertThat(registry.find(ACCOUNT, "c", "1|dev", "kds").isPresent(), equalTo(false));
|
||||
assertThat(registry.find(ACCOUNT, "c|1", "dev", "kds").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 keepsTheRegionOfASchemaThatNamesOne() {
|
||||
registry.bind(new KinesisSchemaBinding(ACCOUNT, "c1", "dev", "kds", "us-west-2", ROLE));
|
||||
registry.bind(binding("c1", "dev", "local"));
|
||||
|
||||
assertThat(registry.find(ACCOUNT, "c1", "dev", "kds").orElseThrow().region(), equalTo("us-west-2"));
|
||||
assertThat(registry.find(ACCOUNT, "c1", "dev", "local").orElseThrow().region(), nullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void requiresTheRoleAndTheIdentifyingFields() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> new KinesisSchemaBinding(ACCOUNT, "c1", "dev", "kds", null, " "));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> new KinesisSchemaBinding(ACCOUNT, "c1", "dev", "", null, ROLE));
|
||||
}
|
||||
}
|
||||
+297
@@ -0,0 +1,297 @@
|
||||
package io.floci.aws.services.redshift.spectrum;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.services.glue.GlueService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.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.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 SpectrumKinesisSchemaPreparationTest {
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String ROLE = "arn:aws:iam::000000000000:role/R";
|
||||
private static final SpectrumSession SESSION = new SpectrumSession(ACCOUNT, ACCOUNT + ":c", "dev", List.of(), false);
|
||||
private static final String CREATE = "CREATE EXTERNAL SCHEMA kds FROM KINESIS IAM_ROLE '" + ROLE + "'";
|
||||
private ExternalCatalogRegistry glueSchemas;
|
||||
private KinesisSchemaRegistry kinesisSchemas;
|
||||
private ExternalTableMaterializer materializer;
|
||||
private BackendSql backend;
|
||||
private SpectrumQueryPreparation preparation;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
glueSchemas = mock(ExternalCatalogRegistry.class);
|
||||
kinesisSchemas = new KinesisSchemaRegistry(AccountAwareStorageBackend.<KinesisSchemaBinding>inMemory(ACCOUNT));
|
||||
materializer = mock(ExternalTableMaterializer.class);
|
||||
backend = mock(BackendSql.class);
|
||||
when(backend.permitsCachePublication()).thenReturn(true);
|
||||
ExternalMetadataWriter metadata = new ExternalMetadataWriter(mock(GlueService.class), new ObjectMapper());
|
||||
preparation = new SpectrumQueryPreparation(glueSchemas, kinesisSchemas, materializer,
|
||||
new ExternalStatementParser(), mock(GlueService.class), metadata, new ExternalCatalogLocks(),
|
||||
(accountId, clusterIdentifier) -> null);
|
||||
}
|
||||
|
||||
private Optional<KinesisSchemaBinding> bound(String schema) {
|
||||
return kinesisSchemas.find(ACCOUNT, SESSION.clusterKey(), "dev", schema);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createsTheLocalSchemaListsItAsKindNineAndRemembersTheBinding() {
|
||||
assertThat(preparation.handlesDdl(CREATE, SESSION), equalTo(true));
|
||||
assertThat(preparation.prepare(CREATE, SESSION, backend), equalTo(true));
|
||||
|
||||
verify(backend).execute("CREATE SCHEMA \"kds\"");
|
||||
verify(backend).execute(argThat(sql -> sql.contains("refresh_external_catalog(E'kds'")
|
||||
&& sql.contains("\"eskind\":9")));
|
||||
KinesisSchemaBinding binding = bound("kds").orElseThrow();
|
||||
assertThat(binding.iamRoleArn(), equalTo(ROLE));
|
||||
assertThat(binding.region(), equalTo(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void keepsTheRegionTheStatementNames() {
|
||||
preparation.prepare("CREATE EXTERNAL SCHEMA kds FROM KINESIS REGION 'us-west-2' IAM_ROLE '" + ROLE + "'",
|
||||
SESSION, backend);
|
||||
|
||||
assertThat(bound("kds").orElseThrow().region(), equalTo("us-west-2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotBindUntilTheStatementCommits() {
|
||||
when(backend.permitsCachePublication()).thenReturn(false);
|
||||
|
||||
preparation.prepare(CREATE, SESSION, backend);
|
||||
assertThat(bound("kds").isPresent(), equalTo(false));
|
||||
|
||||
preparation.finishCycle(backend, true);
|
||||
assertThat(bound("kds").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("kds").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 kds FROM KINESIS IAM_ROLE '" + ROLE + "'",
|
||||
SESSION, backend), equalTo(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsANameThatAGlueSchemaAlreadyUses() {
|
||||
when(glueSchemas.find(ACCOUNT, SESSION.clusterKey(), "dev", "kds")).thenReturn(Optional.of(
|
||||
new ExternalSchemaBinding(ACCOUNT, SESSION.clusterKey(), "dev", "kds", "lake", ROLE)));
|
||||
|
||||
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
|
||||
() -> preparation.prepare(CREATE, SESSION, backend));
|
||||
|
||||
assertThat(error.sqlState(), equalTo("42P06"));
|
||||
verifyNoInteractions(backend);
|
||||
}
|
||||
|
||||
@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("kds").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 \"kds\" CASCADE");
|
||||
assertThat(bound("kds").isPresent(), equalTo(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dropsTheSchemaItsMetadataAndItsBinding() {
|
||||
preparation.prepare(CREATE, SESSION, backend);
|
||||
String drop = "DROP SCHEMA kds";
|
||||
|
||||
assertThat(preparation.handlesDdl(drop, SESSION), equalTo(true));
|
||||
assertThat(preparation.prepare(drop, SESSION, backend), equalTo(true));
|
||||
|
||||
verify(backend).execute(argThat(sql -> sql.startsWith("DROP SCHEMA \"kds\" RESTRICT; ")
|
||||
&& sql.contains("purge_external_schema(E'kds')")));
|
||||
assertThat(bound("kds").isPresent(), equalTo(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dropsWithCascadeWhenAsked() {
|
||||
preparation.prepare(CREATE, SESSION, backend);
|
||||
|
||||
preparation.prepare("DROP SCHEMA IF EXISTS kds CASCADE", SESSION, backend);
|
||||
|
||||
verify(backend).execute(argThat(sql -> sql.startsWith("DROP SCHEMA IF EXISTS \"kds\" CASCADE; ")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void leavesTheDropOfAnUnknownSchemaToPostgreSql() {
|
||||
assertThat(preparation.handlesDdl("DROP SCHEMA other", SESSION), equalTo(false));
|
||||
}
|
||||
|
||||
@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 kds", transaction, backend));
|
||||
|
||||
assertThat(error.sqlState(), equalTo("25001"));
|
||||
assertThat(bound("kds").isPresent(), equalTo(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesToReadAStreamOutsideAMaterializedView() {
|
||||
preparation.prepare(CREATE, SESSION, backend);
|
||||
String read = "SELECT * FROM kds.my_stream";
|
||||
|
||||
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("kds.my_stream"));
|
||||
assertThat(error.getMessage(), containsString("streaming materialized view"));
|
||||
verify(materializer, never()).ensureCurrent(any(), any(), any(), anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesEveryStatementThatNamesARelationOfTheSchemaAsASource() {
|
||||
preparation.prepare(CREATE, SESSION, backend);
|
||||
|
||||
for (String sql : List.of("INSERT INTO kds.derived VALUES (1)", "UPDATE kds.derived SET id = 2",
|
||||
"SELECT * FROM kds.a JOIN public.b ON true")) {
|
||||
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
|
||||
() -> preparation.prepare(sql, SESSION, backend));
|
||||
assertThat(sql, error.sqlState(), equalTo("0A000"));
|
||||
assertThat(sql, error.getMessage(), containsString("Kinesis external schema"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesStatementsThatWouldPutARelationIntoTheSchemaOrDropItAmongOthers() {
|
||||
preparation.prepare(CREATE, SESSION, backend);
|
||||
|
||||
for (String sql : List.of("CREATE TABLE kds.t (id int)", "ALTER TABLE t SET SCHEMA kds",
|
||||
"DROP SCHEMA other, kds")) {
|
||||
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("kds").isPresent(), equalTo(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void leavesAnUnboundLocalSchemaAloneUnderIfNotExists() {
|
||||
doThrow(new SpectrumReadException("42P06", "schema \"kds\" already exists")).when(backend)
|
||||
.execute("CREATE SCHEMA \"kds\"");
|
||||
|
||||
assertThat(preparation.prepare("CREATE EXTERNAL SCHEMA IF NOT EXISTS kds FROM KINESIS IAM_ROLE '" + ROLE + "'",
|
||||
SESSION, backend), equalTo(true));
|
||||
|
||||
assertThat(bound("kds").isPresent(), equalTo(false));
|
||||
SpectrumReadException error = assertThrows(SpectrumReadException.class, () -> preparation.prepare(CREATE, SESSION, backend));
|
||||
assertThat(error.sqlState(), equalTo("42P06"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsAnEmptyRoleWithASyntaxError() {
|
||||
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
|
||||
() -> preparation.prepare("CREATE EXTERNAL SCHEMA kds FROM KINESIS IAM_ROLE ''", SESSION, backend));
|
||||
|
||||
assertThat(error.sqlState(), equalTo("42601"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGlueSchemaCannotTakeTheNameOfAKinesisSchemaAndLeavesGlueUntouched() {
|
||||
GlueService glue = mock(GlueService.class);
|
||||
SpectrumQueryPreparation withGlue = new SpectrumQueryPreparation(glueSchemas, kinesisSchemas, materializer,
|
||||
new ExternalStatementParser(), glue, new ExternalMetadataWriter(glue, new ObjectMapper()),
|
||||
new ExternalCatalogLocks(), (accountId, clusterIdentifier) -> null);
|
||||
preparation.prepare(CREATE, SESSION, backend);
|
||||
|
||||
SpectrumSqlException error = assertThrows(SpectrumSqlException.class, () -> withGlue.prepare(
|
||||
"CREATE EXTERNAL SCHEMA kds FROM DATA CATALOG DATABASE 'lake' IAM_ROLE '" + ROLE
|
||||
+ "' CREATE EXTERNAL DATABASE IF NOT EXISTS", SESSION, backend));
|
||||
|
||||
assertThat(error.sqlState(), equalTo("42P06"));
|
||||
verifyNoInteractions(glue);
|
||||
assertThat(withGlue.prepare("CREATE EXTERNAL SCHEMA IF NOT EXISTS kds FROM DATA CATALOG DATABASE 'lake' "
|
||||
+ "IAM_ROLE '" + ROLE + "'", SESSION, backend), equalTo(true));
|
||||
verifyNoInteractions(glue);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDropDoesNotUnbindASchemaThatWasRecreatedMeanwhile() {
|
||||
preparation.prepare(CREATE, SESSION, backend);
|
||||
KinesisSchemaBinding newer = new KinesisSchemaBinding(ACCOUNT, SESSION.clusterKey(), "dev", "kds", null,
|
||||
"arn:aws:iam::000000000000:role/Other");
|
||||
doAnswer(invocation -> {
|
||||
kinesisSchemas.unbind(ACCOUNT, SESSION.clusterKey(), "dev", "kds");
|
||||
kinesisSchemas.bind(newer);
|
||||
return null;
|
||||
}).when(backend).execute(argThat(sql -> sql.startsWith("DROP SCHEMA \"kds\"")));
|
||||
|
||||
preparation.prepare("DROP SCHEMA kds", SESSION, backend);
|
||||
|
||||
assertThat(bound("kds").orElseThrow(), equalTo(newer));
|
||||
}
|
||||
|
||||
@Test
|
||||
void leavesQueriesThatDoNotTouchAStreamSchemaAlone() {
|
||||
preparation.prepare(CREATE, SESSION, backend);
|
||||
|
||||
assertThat(preparation.referencesExternal("SELECT * FROM public.orders", SESSION), equalTo(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void forgetsTheSchemasOfARemovedCluster() {
|
||||
preparation.prepare(CREATE, SESSION, backend);
|
||||
|
||||
preparation.forgetRuntime(ACCOUNT, SESSION.clusterKey());
|
||||
|
||||
assertThat(bound("kds").isPresent(), equalTo(false));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user