diff --git a/docs/services/redshift.md b/docs/services/redshift.md index 3604539adf..699dea17a1 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -1043,8 +1043,8 @@ 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. +source. A streaming materialized view over a stream of that schema, and `REFRESH`, read it; see +[Streaming materialized views](#streaming-materialized-views). ```sql CREATE EXTERNAL SCHEMA [IF NOT EXISTS] kds @@ -1060,8 +1060,7 @@ schema, its metadata row and its registration; `RESTRICT` is the default, so a s 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. +- The role is not checked when the schema is created. It is checked when a view over the schema is refreshed. - 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. @@ -1069,6 +1068,50 @@ kept, as in Redshift. with `25001`, because the schema registration is not part of the PostgreSQL transaction. - `DROP EXTERNAL DATABASE` and dropping several schemas in one statement are outside this implementation. - Schemas over Amazon MSK or Kafka are not supported. +- `DROP SCHEMA ... CASCADE` also drops the streaming views that read the schema. + +### Streaming materialized views + +A streaming materialized view reads one stream of a Kinesis external schema, and `REFRESH` loads what the +stream holds since the last refresh. + +```sql +CREATE MATERIALIZED VIEW my_view [AUTO REFRESH NO] AS +SELECT approximate_arrival_timestamp, partition_key, shard_id, sequence_number, refresh_time, + JSON_PARSE(FROM_VARBYTE(kinesis_data, 'utf-8')) AS doc +FROM kds.my_stream; + +REFRESH MATERIALIZED VIEW my_view; +DROP MATERIALIZED VIEW [IF EXISTS] my_view [CASCADE | RESTRICT]; +``` + +The stream's relation has the columns Redshift documents: `approximate_arrival_timestamp`, `partition_key`, +`shard_id`, `sequence_number`, `refresh_time` and `kinesis_data` (`varbyte`). The view is a PostgreSQL table +that `SELECT` fills; an unqualified name is created in `public`. Records are read through Floci's own Kinesis +service, never through Firehose or S3. + +- **Refresh:** the first refresh reads each shard from its trim horizon. Every later one starts after the + last record of the shard that a refresh loaded. A batch is loaded, run through the view's `SELECT` and + committed as one statement, and the shard's position is saved only after that commit, so it never runs ahead + of the data. A crash between the commit and the save re-reads that last batch. `TRUNCATE` or `DELETE` on the + view does not move the position, as on Redshift. +- **Errors:** a failure in the view's own expressions (a cast, a calculation) fails the refresh and leaves the + position where it was, as on Redshift. +- **IAM:** each refresh checks the schema's role against `kinesis:DescribeStreamSummary`, + `GetShardIterator`, `GetRecords`, `ListShards` and `DescribeStream` on the stream and `kinesis:ListStreams`, + with trust for `redshift.amazonaws.com`, when IAM enforcement is on. `CREATE MATERIALIZED VIEW` fails with + `42P01` when the stream does not exist. +- **Not supported:** `AUTO REFRESH YES` is refused with `0A000`; refresh the view yourself. Shard splits and + merges, `ALTER MATERIALIZED VIEW`, and PartiQL navigation into `SUPER` values are not implemented. + A `JOIN` in the view is refused with `0A000`, as on Redshift; a comma join (`FROM a, b`) is not detected. + Grouping and aggregation (`GROUP BY`, `HAVING`, `DISTINCT`, and aggregate functions such as `COUNT` or `MAX`) + are refused with `0A000` too, because each refresh batch is inserted on its own and would leave a partial row + per batch. Aggregate over the view with a query instead. +- `CREATE MATERIALIZED VIEW` over a stream fails with `0A000` inside a transaction block, and `DROP MATERIALIZED VIEW` + and `REFRESH MATERIALIZED VIEW` of a streaming view with `25001`. +- Floci keeps a staging table named after the stream in the external schema. Do not query it. It is dropped with + the last view that reads the stream, so `DROP SCHEMA` without `CASCADE` works once every view is dropped. +- Refreshes of the views over one stream run one at a time. ### COPY from S3 diff --git a/src/main/java/io/floci/aws/core/common/SqlParameterParser.java b/src/main/java/io/floci/aws/core/common/SqlParameterParser.java index 7a54a672b9..aecd7945d6 100644 --- a/src/main/java/io/floci/aws/core/common/SqlParameterParser.java +++ b/src/main/java/io/floci/aws/core/common/SqlParameterParser.java @@ -240,6 +240,49 @@ public final class SqlParameterParser { return false; } + /** + * {@code sql} with each comment replaced by a single space, applying the same literal, + * identifier, comment, and dollar-quote skipping as {@link #parse}, so a comment marker + * inside any of those is kept. A line comment's terminating newline is kept. + */ + public static String stripComments(String sql, Options options) { + StringBuilder out = new StringBuilder(sql.length()); + int len = sql.length(); + int i = 0; + while (i < len) { + char c = sql.charAt(i); + + if (startsLineComment(sql, i, options)) { + int end = sql.indexOf('\n', i); + i = end < 0 ? len : end; + out.append(' '); + continue; + } + + if (c == '/' && i + 1 < len && sql.charAt(i + 1) == '*') { + i = skipBlockComment(sql, i, !options.mysqlComments()); + out.append(' '); + continue; + } + + int end = i; + if (c == '\'' || c == '"' || (options.allowBackticks() && c == '`')) { + end = skipQuoted(sql, i, c, options); + } else if (c == '$') { + end = skipDollarQuoted(sql, i); + } + if (end > i) { + out.append(sql, i, end); + i = end; + continue; + } + + out.append(c); + i++; + } + return out.toString(); + } + private static boolean startsLineComment(String sql, int start, Options options) { boolean mysql = options.mysqlComments(); if (mysql && sql.charAt(start) == '#') { diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalStatement.java b/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalStatement.java index 170087ac77..d512a83376 100644 --- a/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalStatement.java +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalStatement.java @@ -7,7 +7,8 @@ import java.util.Map; public sealed interface ExternalStatement permits ExternalStatement.CreateSchema, ExternalStatement.CreateKinesisSchema, ExternalStatement.CreateTable, ExternalStatement.AddPartitions, ExternalStatement.DropSchema, - ExternalStatement.DropTable { + ExternalStatement.DropTable, ExternalStatement.CreateStreamingView, ExternalStatement.RefreshView, + ExternalStatement.DropView { /** Read-only copy that keeps statement order, so Glue payloads are stable across runs. */ private static Map ordered(Map source) { return Collections.unmodifiableMap(new LinkedHashMap<>(source)); @@ -47,4 +48,12 @@ public sealed interface ExternalStatement permits ExternalStatement.CreateSchema /** {@code cascade} is true only when the statement said CASCADE; RESTRICT is the default, as in PostgreSQL and Redshift. */ record DropSchema(String schemaName, boolean ifExists, boolean cascade) implements ExternalStatement { } record DropTable(String schemaName, String tableName, boolean ifExists, boolean cascade) implements ExternalStatement { } + /** + * {@code CREATE MATERIALIZED VIEW ... AS SELECT ...}; whether it reads a stream is for the schema bindings to + * say. {@code viewSchema} is null when the name is unqualified. {@code select} is the query as written. + */ + record CreateStreamingView(String viewSchema, String viewName, boolean autoRefresh, + String select) implements ExternalStatement { } + record RefreshView(String viewSchema, String viewName) implements ExternalStatement { } + record DropView(String viewSchema, String viewName, boolean ifExists, boolean cascade) implements ExternalStatement { } } diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalStatementParser.java b/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalStatementParser.java index 4a27991132..ab4f5fb9d6 100644 --- a/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalStatementParser.java +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalStatementParser.java @@ -1,5 +1,6 @@ package io.floci.aws.services.redshift.spectrum; +import io.floci.aws.core.common.SqlParameterParser; import jakarta.enterprise.context.ApplicationScoped; import java.util.ArrayList; @@ -20,6 +21,9 @@ public class ExternalStatementParser { private static final Pattern SERDE_PROPERTIES = Pattern.compile("(?is)WITH\\s+SERDEPROPERTIES\\s*\\("); private static final String NAME = "(\"(?:\"\"|[^\"])+\"|[^.;,\\s\"()]+)"; private static final Pattern CREATE_TABLE_HEAD = Pattern.compile("(?is)^\\s*CREATE\\s+EXTERNAL\\s+TABLE\\s+" + NAME + "\\s*\\.\\s*" + NAME + "\\s*\\("); + private static final Pattern CREATE_VIEW = Pattern.compile("(?is)^\\s*CREATE\\s+MATERIALIZED\\s+VIEW\\s+" + NAME + "(?:\\s*\\.\\s*" + NAME + ")?\\s+(?:BACKUP\\s+(?:YES|NO)\\s+)?(?:AUTO\\s+REFRESH\\s+(YES|NO)\\s+)?AS\\s+((?:SELECT|WITH)\\b.*?)\\s*;?\\s*$"); + private static final Pattern REFRESH_VIEW = Pattern.compile("(?is)^\\s*REFRESH\\s+MATERIALIZED\\s+VIEW\\s+" + NAME + "(?:\\s*\\.\\s*" + NAME + ")?\\s*;?\\s*$"); + private static final Pattern DROP_VIEW = Pattern.compile("(?is)^\\s*DROP\\s+MATERIALIZED\\s+VIEW\\s+(IF\\s+EXISTS\\s+)?" + NAME + "(?:\\s*\\.\\s*" + NAME + ")?(?:\\s+(CASCADE|RESTRICT))?\\s*;?\\s*$"); private static final Pattern DROP_TABLE = Pattern.compile("(?is)^\\s*DROP\\s+TABLE\\s+(IF\\s+EXISTS\\s+)?" + NAME + "\\.\\s*" + NAME + "(?:\\s+(CASCADE|RESTRICT))?\\s*;?\\s*$"); private static final Pattern DROP_SCHEMA = Pattern.compile("(?is)^\\s*DROP\\s+SCHEMA\\s+(IF\\s+EXISTS\\s+)?" + NAME + "(?:\\s+(CASCADE|RESTRICT))?\\s*;?\\s*$"); private static final Pattern TABLE_PROPERTIES = Pattern.compile("(?is)(?:TBLPROPERTIES|TABLE\\s+PROPERTIES)\\s*\\("); @@ -53,6 +57,29 @@ public class ExternalStatementParser { region == null ? null : region.replace("''", "'"), roleArn(kinesis.group(4)), kinesis.group(1) != null)); } + // comments are separators here; the view's query is stored and sent again on every refresh + String viewText = withoutComments(text); + Matcher createView = CREATE_VIEW.matcher(viewText); + if (createView.matches()) { + if (hasStatementSeparator(createView.group(4))) { + throw new SpectrumSqlException("42601", + "A materialized view query must be a single statement"); + } + return Optional.of(new ExternalStatement.CreateStreamingView(qualifier(createView.group(1), createView.group(2)), + objectName(createView.group(1), createView.group(2)), "YES".equalsIgnoreCase(createView.group(3)), + createView.group(4).replaceFirst("[\\s;]+$", ""))); + } + Matcher refreshView = REFRESH_VIEW.matcher(viewText); + if (refreshView.matches()) { + return Optional.of(new ExternalStatement.RefreshView(qualifier(refreshView.group(1), refreshView.group(2)), + objectName(refreshView.group(1), refreshView.group(2)))); + } + Matcher dropView = DROP_VIEW.matcher(viewText); + if (dropView.matches()) { + return Optional.of(new ExternalStatement.DropView(qualifier(dropView.group(2), dropView.group(3)), + objectName(dropView.group(2), dropView.group(3)), dropView.group(1) != null, + "CASCADE".equalsIgnoreCase(dropView.group(4)))); + } if (CREATE_EXTERNAL_TABLE.matcher(text).matches()) { return Optional.of(parseTable(text)); } @@ -124,6 +151,25 @@ public class ExternalStatementParser { format, location, delimiter, serde, properties, serdeProperties(tail)); } + /** The SQL with each comment outside a quoted string or identifier replaced by a space. */ + static String withoutComments(String sql) { + return SqlParameterParser.stripComments(sql, SqlParameterParser.Options.REDSHIFT); + } + + /** True when a statement follows a {@code ;} that sits outside a quoted string or identifier. */ + static boolean hasStatementSeparator(String sql) { + return SqlParameterParser.isMultiStatement(sql, SqlParameterParser.Options.REDSHIFT); + } + + /** The schema of {@code first.second}, null for a bare name. */ + private static String qualifier(String first, String second) { + return second == null ? null : identifier(first); + } + + private static String objectName(String first, String second) { + return identifier(second == null ? first : second); + } + private static String roleArn(String clause) { String role = clause.trim(); if (role.equalsIgnoreCase("default")) { diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/KinesisStreamingViews.java b/src/main/java/io/floci/aws/services/redshift/spectrum/KinesisStreamingViews.java new file mode 100644 index 0000000000..fe1a49d7b6 --- /dev/null +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/KinesisStreamingViews.java @@ -0,0 +1,285 @@ +package io.floci.aws.services.redshift.spectrum; + +import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.core.common.PostgresWire; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.ServicePrincipals; +import io.floci.aws.services.iam.ServiceRoleAuthorizer; +import io.floci.aws.services.iam.ServiceRoleAuthorizer.Permission; +import io.floci.aws.services.kinesis.KinesisService; +import io.floci.aws.services.kinesis.model.KinesisRecord; +import io.floci.aws.services.kinesis.model.KinesisShard; +import io.floci.aws.services.kinesis.model.KinesisStream; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Streaming materialized views over Kinesis Data Streams. A view is a PostgreSQL table, and the stream's relation + * of its external schema is a staging table of the stream's metadata columns plus {@code kinesis_data}. A refresh + * reads each shard from its checkpoint, loads a batch of records into the staging table, runs the view's query + * over it into the view and empties the staging table again, as one statement string, which PostgreSQL runs as a + * single implicit transaction. A checkpoint is saved only once that statement has committed, so it never runs + * ahead of the data; a crash between the commit and the save re-reads the last batch. + */ +@ApplicationScoped +public class KinesisStreamingViews { + + /** The schema an unqualified view name is created in. */ + static final String DEFAULT_VIEW_SCHEMA = "public"; + + private static final String REDSHIFT_PRINCIPAL = ServicePrincipals.of("redshift"); + private static final List READ_ACTIONS = List.of("kinesis:DescribeStreamSummary", + "kinesis:GetShardIterator", "kinesis:GetRecords", "kinesis:ListShards", "kinesis:DescribeStream"); + private static final int PAGE_LIMIT = 1000; + private static final int BATCH_BYTES = 4 * 1024 * 1024; + private static final DateTimeFormatter TIMESTAMP = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS"); + + private final KinesisViewRegistry registry; + private final KinesisService kinesis; + private final ServiceRoleAuthorizer authorizer; + private final RegionResolver regionResolver; + private final Clock clock; + private final Map streamLocks = new ConcurrentHashMap<>(); + + @Inject + public KinesisStreamingViews(KinesisViewRegistry registry, KinesisService kinesis, + ServiceRoleAuthorizer authorizer, RegionResolver regionResolver, Clock clock) { + this.registry = registry; + this.kinesis = kinesis; + this.authorizer = authorizer; + this.regionResolver = regionResolver; + this.clock = clock; + } + + public Optional find(SpectrumSession session, String viewSchema, String viewName) { + return registry.find(session.accountId(), session.clusterKey(), session.databaseName(), + KinesisViewBinding.nameOf(schemaOrDefault(viewSchema), viewName)); + } + + /** The views that read a stream of {@code streamSchema}. */ + public List overSchema(SpectrumSession session, String streamSchema) { + return registry.list(session.accountId(), session.clusterKey(), session.databaseName()).stream() + .filter(view -> view.streamSchema().equals(streamSchema)).toList(); + } + + public void forgetCluster(String accountId, String clusterKey) { + registry.removeCluster(accountId, clusterKey); + } + + public void unbind(KinesisViewBinding view) { + registry.unbind(view.accountId(), view.clusterKey(), view.databaseName(), view.bindingName()); + } + + /** Unbinds a view captured earlier, unless a view of the same name over another stream has replaced it. */ + public void unbindIfCurrent(KinesisViewBinding captured) { + synchronized (streamLock(captured.accountId(), captured.clusterKey(), captured.databaseName(), + captured.streamSchema(), captured.streamName())) { + registry.find(captured.accountId(), captured.clusterKey(), captured.databaseName(), + captured.bindingName()).filter(current -> readsSameStream(current, captured)) + .ifPresent(this::unbind); + } + } + + private static boolean readsSameStream(KinesisViewBinding first, KinesisViewBinding second) { + return first.streamSchema().equals(second.streamSchema()) && first.streamName().equals(second.streamName()); + } + + /** The SQL that drops a view's table, for the statement that drops a schema it reads from. */ + static String dropSql(KinesisViewBinding view, boolean ifExists, boolean cascade) { + return "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + table(view.viewSchema(), view.viewName()) + + (cascade ? " CASCADE" : " RESTRICT"); + } + + /** + * Drops a view's table and its binding, and the stream's staging table once no other view reads the stream. + * Without that, a plain DROP SCHEMA of the stream's schema would keep failing on the leftover table. + */ + public void drop(KinesisViewBinding named, boolean ifExists, boolean cascade, BackendSql backend) { + synchronized (streamLock(named.accountId(), named.clusterKey(), named.databaseName(), named.streamSchema(), + named.streamName())) { + // the binding read before the lock may be gone or replaced by a view of the same name since + Optional registered = registry.find(named.accountId(), named.clusterKey(), + named.databaseName(), named.bindingName()); + if (registered.isEmpty() || !readsSameStream(registered.get(), named)) { + if (ifExists) { + return; + } + throw new SpectrumSqlException("42P01", "materialized view \"" + named.viewSchema() + "." + + named.viewName() + "\" does not exist"); + } + KinesisViewBinding view = registered.get(); + boolean lastReader = registry.list(view.accountId(), view.clusterKey(), view.databaseName()).stream() + .noneMatch(other -> !other.bindingName().equals(view.bindingName()) + && other.streamSchema().equals(view.streamSchema()) + && other.streamName().equals(view.streamName())); + String sql = dropSql(view, ifExists, cascade); + if (lastReader) { + sql += "; DROP TABLE IF EXISTS " + table(view.streamSchema(), view.streamName()); + } + backend.execute(sql); + unbind(view); + } + } + + public void create(ExternalStatement.CreateStreamingView statement, String streamName, + KinesisSchemaBinding schema, SpectrumSession session, String clusterRegion, + BackendSql backend) { + String viewSchema = schemaOrDefault(statement.viewSchema()); + synchronized (streamLock(session.accountId(), session.clusterKey(), session.databaseName(), + schema.schemaName(), streamName)) { + if (find(session, viewSchema, statement.viewName()).isPresent()) { + throw new SpectrumSqlException("42P07", "relation \"" + viewSchema + "." + statement.viewName() + + "\" already exists"); + } + // Redshift reads the stream's shards when the view is created, so a missing stream fails here + kinesis.describeStreamForAccount(session.accountId(), streamName, region(schema, clusterRegion)); + backend.execute("CREATE TABLE IF NOT EXISTS " + table(schema.schemaName(), streamName) + + " (approximate_arrival_timestamp timestamp, partition_key varchar(256), shard_id char(20), " + + "sequence_number varchar(128), refresh_time timestamp, kinesis_data pg_catalog.varbyte); " + + "CREATE TABLE " + table(viewSchema, statement.viewName()) + " AS " + statement.select() + + " WITH NO DATA"); + registry.bind(new KinesisViewBinding(session.accountId(), session.clusterKey(), session.databaseName(), + viewSchema, statement.viewName(), schema.schemaName(), streamName, statement.select(), Map.of())); + } + } + + /** Loads what the stream holds past each shard's checkpoint into the view; returns the records loaded. */ + public long refresh(KinesisViewBinding view, KinesisSchemaBinding schema, String clusterRegion, + BackendSql backend) { + // refreshes of the views over one stream share its staging table, so they run one at a time + synchronized (streamLock(view.accountId(), view.clusterKey(), view.databaseName(), view.streamSchema(), + view.streamName())) { + // the binding read before the lock may be stale: a refresh ahead of this one moved the checkpoints + KinesisViewBinding latest = registry.find(view.accountId(), view.clusterKey(), view.databaseName(), + view.bindingName()).orElseThrow(() -> new SpectrumSqlException("42P01", + "relation \"" + view.viewSchema() + "." + view.viewName() + "\" does not exist")); + return refreshLocked(latest, schema, clusterRegion, backend); + } + } + + private Object streamLock(String accountId, String clusterKey, String database, String streamSchema, + String streamName) { + return streamLocks.computeIfAbsent(String.join("\u001f", accountId, clusterKey, database, streamSchema, + streamName), key -> new Object()); + } + + private long refreshLocked(KinesisViewBinding view, KinesisSchemaBinding schema, String clusterRegion, + BackendSql backend) { + String region = region(schema, clusterRegion); + requireAuthorized(view, schema, region); + KinesisStream stream = kinesis.describeStreamForAccount(view.accountId(), view.streamName(), region); + Instant refreshTime = clock.instant(); + KinesisViewBinding current = view; + long loaded = 0; + for (KinesisShard shard : stream.getShards()) { + String shardId = shard.getShardId(); + String checkpoint = current.checkpoints().get(shardId); + String iterator = checkpoint == null + ? kinesis.getShardIteratorForAccount(view.accountId(), view.streamName(), shardId, + "TRIM_HORIZON", null, region) + : kinesis.getShardIteratorForAccount(view.accountId(), view.streamName(), shardId, + "AFTER_SEQUENCE_NUMBER", checkpoint, region); + while (iterator != null) { + Map page = kinesis.getRecordsForAccount(view.accountId(), iterator, PAGE_LIMIT, region); + @SuppressWarnings("unchecked") + List records = (List) page.get("Records"); + iterator = (String) page.get("NextShardIterator"); + if (records == null || records.isEmpty()) { + break; + } + for (List batch : batches(records)) { + backend.execute(loadSql(view, shardId, batch, refreshTime)); + current = current.withCheckpoint(shardId, batch.getLast().getSequenceNumber()); + registry.replace(current); + loaded += batch.size(); + } + } + } + return loaded; + } + + private void requireAuthorized(KinesisViewBinding view, KinesisSchemaBinding schema, String region) { + String streamArn = new AwsArnUtils.Arn(regionResolver.partitionForRegion(region), "kinesis", region, + view.accountId(), "stream/" + view.streamName()).toString(); + List permissions = new ArrayList<>(); + for (String action : READ_ACTIONS) { + permissions.add(new Permission(action, streamArn)); + } + permissions.add(new Permission("kinesis:ListStreams", "*")); + Optional refusal = authorizer.refusal(schema.iamRoleArn(), view.accountId(), REDSHIFT_PRINCIPAL, + null, permissions); + if (refusal.isPresent()) { + throw new SpectrumSqlException("42501", refusal.get()); + } + } + + private String region(KinesisSchemaBinding schema, String clusterRegion) { + if (schema.region() != null) { + return schema.region(); + } + return clusterRegion != null ? clusterRegion : regionResolver.getDefaultRegion(); + } + + /** Splits a page so no statement carries more than about {@value #BATCH_BYTES} bytes of record data. */ + private static List> batches(List records) { + List> batches = new ArrayList<>(); + List batch = new ArrayList<>(); + long bytes = 0; + for (KinesisRecord record : records) { + long size = record.getData() == null ? 0 : record.getData().length; + if (!batch.isEmpty() && bytes + size > BATCH_BYTES) { + batches.add(batch); + batch = new ArrayList<>(); + bytes = 0; + } + batch.add(record); + bytes += size; + } + batches.add(batch); + return batches; + } + + private static String loadSql(KinesisViewBinding view, String shardId, List batch, + Instant refreshTime) { + String staging = table(view.streamSchema(), view.streamName()); + StringBuilder rows = new StringBuilder(); + for (KinesisRecord record : batch) { + if (!rows.isEmpty()) { + rows.append(", "); + } + byte[] data = record.getData() == null ? new byte[0] : record.getData(); + rows.append('(').append(timestamp(record.getApproximateArrivalTimestamp())).append(", ") + .append(PostgresWire.quoteLiteral(record.getPartitionKey())).append(", ") + .append(PostgresWire.quoteLiteral(shardId)).append(", ") + .append(PostgresWire.quoteLiteral(record.getSequenceNumber())).append(", ") + .append(timestamp(refreshTime)).append(", decode('").append(HexFormat.of().formatHex(data)) + .append("', 'hex')::pg_catalog.varbyte)"); + } + return "INSERT INTO " + staging + " VALUES " + rows + "; INSERT INTO " + + table(view.viewSchema(), view.viewName()) + " " + view.select() + "; TRUNCATE " + staging; + } + + private static String timestamp(Instant instant) { + return instant == null ? "NULL::timestamp" + : "TIMESTAMP '" + TIMESTAMP.format(instant.atOffset(ZoneOffset.UTC)) + "'"; + } + + private static String schemaOrDefault(String schema) { + return schema == null ? DEFAULT_VIEW_SCHEMA : schema; + } + + private static String table(String schema, String name) { + return ExternalTableMaterializer.quote(schema) + "." + ExternalTableMaterializer.quote(name); + } +} diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/KinesisViewBinding.java b/src/main/java/io/floci/aws/services/redshift/spectrum/KinesisViewBinding.java new file mode 100644 index 0000000000..dfb9b73673 --- /dev/null +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/KinesisViewBinding.java @@ -0,0 +1,59 @@ +package io.floci.aws.services.redshift.spectrum; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * A streaming materialized view over a Kinesis stream. {@code select} is the view's query as written, which + * reads the stream's relation of the external schema; {@code checkpoints} holds, per shard, the sequence number + * of the last record a committed refresh loaded, so the next refresh starts after it. + */ +@RegisterForReflection +public record KinesisViewBinding(String accountId, String clusterKey, String databaseName, String viewSchema, + String viewName, String streamSchema, String streamName, String select, + Map checkpoints) implements SchemaBinding { + /** Separates the schema from the view in the registry key; a quoted identifier cannot be told apart otherwise. */ + private static final char KEY_SEPARATOR = '\u001f'; + + public KinesisViewBinding { + require(accountId, "accountId"); + require(clusterKey, "clusterKey"); + require(databaseName, "databaseName"); + require(viewSchema, "viewSchema"); + require(viewName, "viewName"); + require(streamSchema, "streamSchema"); + require(streamName, "streamName"); + require(select, "select"); + checkpoints = checkpoints == null ? Map.of() : Map.copyOf(checkpoints); + } + + @Override + public String schemaName() { + return viewSchema; + } + + @Override + public String bindingName() { + return nameOf(viewSchema, viewName); + } + + /** The registry name of the view {@code viewName} of {@code viewSchema}. */ + static String nameOf(String viewSchema, String viewName) { + return viewSchema + KEY_SEPARATOR + viewName; + } + + public KinesisViewBinding withCheckpoint(String shardId, String sequenceNumber) { + Map updated = new LinkedHashMap<>(checkpoints); + updated.put(shardId, sequenceNumber); + return new KinesisViewBinding(accountId, clusterKey, databaseName, viewSchema, viewName, streamSchema, + streamName, select, updated); + } + + private static void require(String value, String field) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(field + " is required"); + } + } +} diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/KinesisViewRegistry.java b/src/main/java/io/floci/aws/services/redshift/spectrum/KinesisViewRegistry.java new file mode 100644 index 0000000000..4bc3255c34 --- /dev/null +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/KinesisViewRegistry.java @@ -0,0 +1,22 @@ +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; + +/** The streaming materialized views over Kinesis streams, keyed by cluster, database, schema and view name. */ +@ApplicationScoped +public class KinesisViewRegistry extends SchemaBindingRegistry { + + @Inject + public KinesisViewRegistry(StorageFactory storageFactory) { + super(storageFactory.create("redshift", "redshift-kinesis-views.json", + new TypeReference<>() { })); + } + + KinesisViewRegistry(AccountAwareStorageBackend bindings) { + super(bindings); + } +} diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/SchemaBinding.java b/src/main/java/io/floci/aws/services/redshift/spectrum/SchemaBinding.java index d0746b6841..eea04de81e 100644 --- a/src/main/java/io/floci/aws/services/redshift/spectrum/SchemaBinding.java +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/SchemaBinding.java @@ -9,4 +9,9 @@ interface SchemaBinding { String databaseName(); String schemaName(); + + /** The name the registry keys the binding by; a binding of something inside a schema names it too. */ + default String bindingName() { + return schemaName(); + } } diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/SchemaBindingRegistry.java b/src/main/java/io/floci/aws/services/redshift/spectrum/SchemaBindingRegistry.java index 7898b09933..a13b03c4d3 100644 --- a/src/main/java/io/floci/aws/services/redshift/spectrum/SchemaBindingRegistry.java +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/SchemaBindingRegistry.java @@ -24,7 +24,7 @@ abstract class SchemaBindingRegistry implements Resetta } public synchronized void bind(B binding) { - String key = key(binding.clusterKey(), binding.databaseName(), binding.schemaName()); + String key = key(binding.clusterKey(), binding.databaseName(), binding.bindingName()); if (bindings.getForAccount(binding.accountId(), key).isPresent()) { throw new SpectrumSqlException("42P06", "schema \"" + binding.schemaName() + "\" already exists"); } @@ -32,6 +32,12 @@ abstract class SchemaBindingRegistry implements Resetta bindings.flush(); } + public synchronized void replace(B binding) { + bindings.putForAccount(binding.accountId(), + key(binding.clusterKey(), binding.databaseName(), binding.bindingName()), binding); + bindings.flush(); + } + public Optional find(String accountId, String clusterKey, String databaseName, String schemaName) { return bindings.getForAccount(accountId, key(clusterKey, databaseName, schemaName)); } diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumQueryPreparation.java b/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumQueryPreparation.java index b7f4fc8098..3809413987 100644 --- a/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumQueryPreparation.java +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumQueryPreparation.java @@ -14,6 +14,7 @@ import jakarta.enterprise.inject.Instance; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.time.Clock; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashMap; @@ -24,13 +25,22 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.BiFunction; +import java.util.regex.Pattern; @ApplicationScoped public class SpectrumQueryPreparation { private static final Logger LOG = Logger.getLogger(SpectrumQueryPreparation.class); private static final String DUPLICATE_SCHEMA = "42P06"; + private static final Pattern JOIN = Pattern.compile("\\bJOIN\\b", Pattern.CASE_INSENSITIVE); + // Each batch is inserted on its own, so a view that groups or aggregates would keep a partial row per batch. + private static final Pattern AGGREGATE = Pattern.compile( + "\\b(?:GROUP\\s+BY|HAVING|DISTINCT)\\b|\\b(?:COUNT|SUM|AVG|MIN|MAX|MEDIAN|LISTAGG|STDDEV\\w*|VAR_\\w+|VARIANCE" + + "|BOOL_AND|BOOL_OR|ARRAY_AGG|APPROXIMATE|PERCENTILE_\\w+)\\s*\\(", + Pattern.CASE_INSENSITIVE); + private static final Pattern STRING_LITERAL = Pattern.compile("'(?:[^']|'')*'|\"(?:[^\"]|\"\")*\""); private final ExternalCatalogRegistry registry; private final KinesisSchemaRegistry kinesisSchemas; + private final KinesisStreamingViews views; private final ExternalTableMaterializer materializer; private final ExternalStatementParser parser; private final GlueService glue; @@ -57,8 +67,9 @@ public class SpectrumQueryPreparation { public SpectrumQueryPreparation(ExternalCatalogRegistry registry, KinesisSchemaRegistry kinesisSchemas, ExternalTableMaterializer materializer, ExternalStatementParser parser, GlueService glue, ExternalMetadataWriter metadata, - ExternalCatalogLocks catalogLocks, Instance redshift) { - this(registry, kinesisSchemas, materializer, parser, glue, metadata, catalogLocks, + ExternalCatalogLocks catalogLocks, KinesisStreamingViews views, + Instance redshift) { + this(registry, kinesisSchemas, materializer, parser, glue, metadata, catalogLocks, views, (accountId, clusterIdentifier) -> redshift.get().clusterRegion(accountId, clusterIdentifier).orElse(null)); } @@ -73,6 +84,17 @@ public class SpectrumQueryPreparation { ExternalTableMaterializer materializer, ExternalStatementParser parser, GlueService glue, ExternalMetadataWriter metadata, ExternalCatalogLocks catalogLocks, BiFunction clusterRegion) { + this(registry, kinesisSchemas, materializer, parser, glue, metadata, catalogLocks, + new KinesisStreamingViews(new KinesisViewRegistry( + AccountAwareStorageBackend.inMemory("000000000000")), + null, null, null, Clock.systemUTC()), clusterRegion); + } + + SpectrumQueryPreparation(ExternalCatalogRegistry registry, KinesisSchemaRegistry kinesisSchemas, + ExternalTableMaterializer materializer, ExternalStatementParser parser, + GlueService glue, ExternalMetadataWriter metadata, ExternalCatalogLocks catalogLocks, + KinesisStreamingViews views, BiFunction clusterRegion) { + this.views = views; this.clusterRegion = clusterRegion; this.registry = registry; this.kinesisSchemas = kinesisSchemas; @@ -109,6 +131,7 @@ public class SpectrumQueryPreparation { String state = switch (exception.getErrorCode()) { case "AlreadyExistsException" -> "42P07"; case "EntityNotFoundException" -> "42P01"; + case "ResourceNotFoundException" -> "42P01"; case "AccessDenied", "AccessDeniedException" -> "42501"; case "InvalidInputException" -> "42601"; default -> "58030"; @@ -135,6 +158,11 @@ public class SpectrumQueryPreparation { case ExternalStatement.DropTable table -> bindings(session).containsKey(table.schemaName()); case ExternalStatement.DropSchema schema -> bindings(session).containsKey(schema.schemaName()) || kinesisBindings(session).containsKey(schema.schemaName()); + case ExternalStatement.CreateStreamingView view -> streamSource(view.select(), session).isPresent(); + case ExternalStatement.RefreshView view -> + views.find(session, view.viewSchema(), view.viewName()).isPresent(); + case ExternalStatement.DropView view -> + views.find(session, view.viewSchema(), view.viewName()).isPresent(); case null -> false; }; } @@ -144,6 +172,9 @@ public class SpectrumQueryPreparation { case ExternalStatement.AddPartitions ignored -> "ALTER TABLE"; case ExternalStatement.DropTable ignored -> "DROP TABLE"; case ExternalStatement.DropSchema ignored -> "DROP SCHEMA"; + case ExternalStatement.CreateStreamingView ignored -> "CREATE MATERIALIZED VIEW"; + case ExternalStatement.RefreshView ignored -> "REFRESH MATERIALIZED VIEW"; + case ExternalStatement.DropView ignored -> "DROP MATERIALIZED VIEW"; case null, default -> "CREATE EXTERNAL"; }; } @@ -163,6 +194,26 @@ public class SpectrumQueryPreparation { dropKinesisSchema(schema, kinesis.get(schema.schemaName()), session, backend); return true; } + if (statement.orElse(null) instanceof ExternalStatement.CreateStreamingView view + && streamSource(view.select(), session).isPresent()) { + createStreamingView(view, kinesis, session, backend); + return true; + } + if (statement.orElse(null) instanceof ExternalStatement.RefreshView refresh) { + Optional view = views.find(session, refresh.viewSchema(), refresh.viewName()); + if (view.isPresent()) { + refreshStreamingView(view.get(), kinesis, session, backend); + return true; + } + } + if (statement.orElse(null) instanceof ExternalStatement.DropView drop) { + Optional view = views.find(session, drop.viewSchema(), drop.viewName()); + if (view.isPresent()) { + rejectTransaction(session); + views.drop(view.get(), drop.ifExists(), drop.cascade(), backend); + return true; + } + } Map 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. @@ -451,10 +502,21 @@ public class SpectrumQueryPreparation { private void dropKinesisSchema(ExternalStatement.DropSchema statement, KinesisSchemaBinding binding, SpectrumSession session, BackendSql backend) { requireSchemaOwner(backend, binding.schemaName()); + // CASCADE takes the streaming views that read the schema with it; RESTRICT stops on their staging tables. + List dependents = views.overSchema(session, binding.schemaName()); + StringBuilder dropViews = new StringBuilder(); + if (statement.cascade()) { + for (KinesisViewBinding dependent : dependents) { + dropViews.append(KinesisStreamingViews.dropSql(dependent, true, true)).append("; "); + } + } // One implicit PostgreSQL transaction keeps the local schema and its SVV metadata in sync. - backend.execute("DROP SCHEMA " + (statement.ifExists() ? "IF EXISTS " : "") + backend.execute(dropViews + "DROP SCHEMA " + (statement.ifExists() ? "IF EXISTS " : "") + ExternalTableMaterializer.quote(binding.schemaName()) + (statement.cascade() ? " CASCADE" : " RESTRICT") + "; " + metadata.purgeSql(binding.schemaName())); + if (statement.cascade()) { + dependents.forEach(views::unbindIfCurrent); + } // a concurrent drop and re-create of the name may have bound a newer schema meanwhile if (binding.equals(kinesisSchemas.find(session.accountId(), session.clusterKey(), session.databaseName(), binding.schemaName()).orElse(null))) { @@ -463,6 +525,51 @@ public class SpectrumQueryPreparation { } } + private Optional streamSource(String select, SpectrumSession session) { + return ExternalReferenceScanner.scan(select, kinesisBindings(session).keySet()).stream().findFirst(); + } + + private void createStreamingView(ExternalStatement.CreateStreamingView view, + Map kinesis, SpectrumSession session, + BackendSql backend) { + if (session.inTransaction()) { + throw new SpectrumSqlException("0A000", + "CREATE MATERIALIZED VIEW over a stream inside a transaction is not supported"); + } + if (view.autoRefresh()) { + throw new SpectrumSqlException("0A000", + "AUTO REFRESH YES is not supported; refresh the view with REFRESH MATERIALIZED VIEW"); + } + String unquoted = STRING_LITERAL.matcher(view.select()).replaceAll("''"); + if (JOIN.matcher(unquoted).find()) { + throw new SpectrumSqlException("0A000", "A streaming materialized view cannot contain a JOIN"); + } + if (AGGREGATE.matcher(unquoted).find()) { + throw new SpectrumSqlException("0A000", + "A streaming materialized view cannot group or aggregate: each refresh batch is inserted on its own"); + } + Set streams = + ExternalReferenceScanner.scan(view.select(), kinesis.keySet()); + if (streams.size() != 1) { + throw new SpectrumSqlException("0A000", "A streaming materialized view reads exactly one stream"); + } + ExternalReferenceScanner.Reference stream = streams.iterator().next(); + views.create(view, stream.table(), kinesis.get(stream.schema()), session, catalogRegion(session), backend); + } + + private void refreshStreamingView(KinesisViewBinding view, Map kinesis, + SpectrumSession session, BackendSql backend) { + if (session.inTransaction()) { + throw new SpectrumSqlException("25001", + "REFRESH MATERIALIZED VIEW of a streaming view cannot run inside a transaction block"); + } + KinesisSchemaBinding schema = kinesis.get(view.streamSchema()); + if (schema == null) { + throw new SpectrumSqlException("42P01", "external schema \"" + view.streamSchema() + "\" does not exist"); + } + views.refresh(view, schema, catalogRegion(session), backend); + } + private Map kinesisBindings(SpectrumSession session) { Map bindings = new LinkedHashMap<>(); for (KinesisSchemaBinding binding : kinesisSchemas.list(session.accountId(), session.clusterKey(), @@ -483,6 +590,7 @@ public class SpectrumQueryPreparation { public void forgetRuntime(String accountId, String clusterKey) { registry.removeCluster(accountId, clusterKey); kinesisSchemas.removeCluster(accountId, clusterKey); + views.forgetCluster(accountId, clusterKey); materializer.forgetCluster(clusterKey); } diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftKinesisStreamingViewIntegrationTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftKinesisStreamingViewIntegrationTest.java new file mode 100644 index 0000000000..c319c2ce77 --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftKinesisStreamingViewIntegrationTest.java @@ -0,0 +1,126 @@ +package io.floci.aws.services.redshift; + +import io.floci.aws.services.kinesis.KinesisService; +import io.floci.aws.services.redshift.model.Cluster; +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.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static io.floci.aws.services.redshift.RedshiftConnections.waitForConnection; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** Streams a Kinesis stream into a materialized view through a real cluster connection. */ +@QuarkusTest +class RedshiftKinesisStreamingViewIntegrationTest { + private static final String ACCOUNT = "000000000000"; + private static final String REGION = "us-east-1"; + private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/KinesisViewItRole"; + + @Inject + RedshiftService redshiftService; + + @Inject + KinesisService kinesisService; + + 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 void put(String stream, String body) { + kinesisService.putRecordForAccount(ACCOUNT, stream, body.getBytes(StandardCharsets.UTF_8), "pk", REGION); + } + + private static List bodies(Statement statement) throws SQLException { + List bodies = new ArrayList<>(); + try (ResultSet rows = statement.executeQuery("SELECT body FROM events_mv ORDER BY sequence_number")) { + while (rows.next()) { + bodies.add(rows.getString(1)); + } + } + return bodies; + } + + @Test + @Timeout(180) + void refreshLoadsOnlyWhatTheStreamGainedAndKeepsItsPositionAcrossATruncate() throws Exception { + String stream = "it_stream_" + UUID.randomUUID().toString().substring(0, 8); + kinesisService.createStream(stream, 1, REGION); + put(stream, "one"); + put(stream, "two"); + clusterId = "it-mv-" + 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 '" + REGION + "' IAM_ROLE '" + ROLE_ARN + "'"); + statement.execute("CREATE MATERIALIZED VIEW events_mv AUTO REFRESH NO AS " + + "SELECT sequence_number, FROM_VARBYTE(kinesis_data, 'utf-8') AS body FROM kds." + stream); + assertEquals(List.of(), bodies(statement)); + + statement.execute("REFRESH MATERIALIZED VIEW events_mv"); + assertEquals(List.of("one", "two"), bodies(statement)); + + put(stream, "three"); + statement.execute("REFRESH MATERIALIZED VIEW events_mv"); + statement.execute("REFRESH MATERIALIZED VIEW events_mv"); + assertEquals(List.of("one", "two", "three"), bodies(statement)); + + statement.execute("TRUNCATE events_mv"); + statement.execute("REFRESH MATERIALIZED VIEW events_mv"); + assertEquals(List.of(), bodies(statement)); + put(stream, "four"); + statement.execute("REFRESH MATERIALIZED VIEW events_mv"); + assertEquals(List.of("four"), bodies(statement)); + + statement.execute("DROP MATERIALIZED VIEW events_mv"); + SQLException gone = assertThrows(SQLException.class, () -> statement.executeQuery("SELECT 1 FROM events_mv")); + assertEquals("42P01", gone.getSQLState()); + SQLException unbound = assertThrows(SQLException.class, + () -> statement.execute("REFRESH MATERIALIZED VIEW events_mv")); + assertFalse(unbound.getMessage().isBlank()); + } + } + + @Test + @Timeout(180) + void refusesAutoRefreshYesAndAViewOverAMissingStream() throws Exception { + clusterId = "it-mv-" + 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 '" + REGION + "' IAM_ROLE '" + ROLE_ARN + "'"); + + SQLException auto = assertThrows(SQLException.class, () -> statement.execute( + "CREATE MATERIALIZED VIEW v AUTO REFRESH YES AS SELECT * FROM kds.no_such_stream")); + assertEquals("0A000", auto.getSQLState()); + SQLException missing = assertThrows(SQLException.class, () -> statement.execute( + "CREATE MATERIALIZED VIEW v AS SELECT * FROM kds.no_such_stream")); + assertEquals("42P01", missing.getSQLState()); + } + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/spectrum/KinesisStreamingViewParserTest.java b/src/test/java/io/floci/aws/services/redshift/spectrum/KinesisStreamingViewParserTest.java new file mode 100644 index 0000000000..5725170646 --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/spectrum/KinesisStreamingViewParserTest.java @@ -0,0 +1,108 @@ +package io.floci.aws.services.redshift.spectrum; + +import org.junit.jupiter.api.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class KinesisStreamingViewParserTest { + private final ExternalStatementParser parser = new ExternalStatementParser(); + + @Test + void parsesAViewOverAStreamWithManualRefresh() { + ExternalStatement.CreateStreamingView view = (ExternalStatement.CreateStreamingView) parser.parse( + "CREATE MATERIALIZED VIEW my_view AUTO REFRESH NO AS SELECT * FROM kds.my_stream;").orElseThrow(); + + assertThat(view.viewSchema(), nullValue()); + assertThat(view.viewName(), equalTo("my_view")); + assertThat(view.autoRefresh(), is(false)); + assertThat(view.select(), equalTo("SELECT * FROM kds.my_stream")); + } + + @Test + void manualRefreshIsTheDefaultAndAutoRefreshYesIsRecorded() { + ExternalStatement.CreateStreamingView manual = (ExternalStatement.CreateStreamingView) parser.parse( + "create materialized view s.v as select 1 from kds.t").orElseThrow(); + ExternalStatement.CreateStreamingView auto = (ExternalStatement.CreateStreamingView) parser.parse( + "CREATE MATERIALIZED VIEW \"S\".\"V\" AUTO REFRESH YES AS SELECT 1 FROM kds.t").orElseThrow(); + + assertThat(manual.viewSchema(), equalTo("s")); + assertThat(manual.viewName(), equalTo("v")); + assertThat(manual.autoRefresh(), is(false)); + assertThat(auto.viewSchema(), equalTo("S")); + assertThat(auto.viewName(), equalTo("V")); + assertThat(auto.autoRefresh(), is(true)); + } + + @Test + void parsesRefreshAndDrop() { + ExternalStatement.RefreshView refresh = (ExternalStatement.RefreshView) parser.parse( + "REFRESH MATERIALIZED VIEW public.my_view;").orElseThrow(); + ExternalStatement.DropView drop = (ExternalStatement.DropView) parser.parse( + "DROP MATERIALIZED VIEW IF EXISTS my_view CASCADE").orElseThrow(); + + assertThat(refresh.viewSchema(), equalTo("public")); + assertThat(refresh.viewName(), equalTo("my_view")); + assertThat(drop.viewSchema(), nullValue()); + assertThat(drop.viewName(), equalTo("my_view")); + assertThat(drop.ifExists(), is(true)); + assertThat(drop.cascade(), is(true)); + } + + @Test + void aViewQueryMayStartWithACte() { + ExternalStatement.CreateStreamingView view = (ExternalStatement.CreateStreamingView) parser.parse( + "CREATE MATERIALIZED VIEW v AS WITH s AS (SELECT * FROM kds.t) SELECT * FROM s").orElseThrow(); + + assertThat(view.select(), equalTo("WITH s AS (SELECT * FROM kds.t) SELECT * FROM s")); + } + + @Test + void commentsAreSeparatorsAndDoNotReachTheStoredQuery() { + ExternalStatement.RefreshView refresh = (ExternalStatement.RefreshView) parser.parse( + "REFRESH /* a */ MATERIALIZED VIEW v /* note */ -- tail").orElseThrow(); + ExternalStatement.CreateStreamingView view = (ExternalStatement.CreateStreamingView) parser.parse( + "CREATE MATERIALIZED VIEW v AS SELECT 'a--b' AS x FROM kds.t -- trailing").orElseThrow(); + + assertThat(refresh.viewName(), equalTo("v")); + assertThat(view.select(), equalTo("SELECT 'a--b' AS x FROM kds.t")); + } + + @Test + void aSecondStatementInTheViewQueryIsRefused() { + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, () -> parser.parse( + "CREATE MATERIALIZED VIEW v AS SELECT 1 FROM kds.t; DROP TABLE public.x")); + + assertThat(error.sqlState(), equalTo("42601")); + assertThat(parser.parse("CREATE MATERIALIZED VIEW v AS SELECT ';' FROM kds.t").isPresent(), is(true)); + } + + @Test + void anEscapedQuoteInAnEscapeStringDoesNotHideASecondStatement() { + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, () -> parser.parse( + "CREATE MATERIALIZED VIEW v AS SELECT E'\\'' FROM kds.t; DROP TABLE public.x")); + ExternalStatement.CreateStreamingView view = (ExternalStatement.CreateStreamingView) parser.parse( + "CREATE MATERIALIZED VIEW v AS SELECT E'\\';' AS x FROM kds.t;").orElseThrow(); + + assertThat(error.sqlState(), equalTo("42601")); + assertThat(view.select(), equalTo("SELECT E'\\';' AS x FROM kds.t")); + } + + @Test + void aCommentMarkerAfterAnEscapedQuoteIsStillAComment() { + ExternalStatement.CreateStreamingView view = (ExternalStatement.CreateStreamingView) parser.parse( + "CREATE MATERIALIZED VIEW v AS SELECT E'\\'' AS x FROM kds.t -- ; DROP TABLE public.x").orElseThrow(); + + assertThat(view.select(), equalTo("SELECT E'\\'' AS x FROM kds.t")); + } + + @Test + void leavesOtherStatementsAlone() { + assertThat(parser.parse("CREATE MATERIALIZED VIEW v DISTSTYLE ALL AS SELECT 1").isPresent(), is(false)); + assertThat(parser.parse("REFRESH MATERIALIZED VIEW").isPresent(), is(false)); + assertThat(parser.parse("DROP VIEW v").isPresent(), is(false)); + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/spectrum/KinesisStreamingViewsTest.java b/src/test/java/io/floci/aws/services/redshift/spectrum/KinesisStreamingViewsTest.java new file mode 100644 index 0000000000..a36d37681b --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/spectrum/KinesisStreamingViewsTest.java @@ -0,0 +1,296 @@ +package io.floci.aws.services.redshift.spectrum; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.services.iam.ServiceRoleAuthorizer; +import io.floci.aws.services.kinesis.KinesisService; +import io.floci.aws.services.kinesis.model.KinesisRecord; +import io.floci.aws.services.kinesis.model.KinesisShard; +import io.floci.aws.services.kinesis.model.KinesisStream; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +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.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class KinesisStreamingViewsTest { + private static final String ACCOUNT = "000000000000"; + private static final String ROLE = "arn:aws:iam::000000000000:role/R"; + private static final String SHARD = "shardId-000000000000"; + private static final SpectrumSession SESSION = new SpectrumSession(ACCOUNT, ACCOUNT + ":c", "dev", List.of(), false); + private static final String SELECT = "SELECT sequence_number, json_parse(from_varbyte(kinesis_data, 'utf-8')) AS doc " + + "FROM kds.events"; + private static final KinesisSchemaBinding SCHEMA = + new KinesisSchemaBinding(ACCOUNT, SESSION.clusterKey(), "dev", "kds", "us-west-2", ROLE); + + private KinesisViewRegistry registry; + private KinesisService kinesis; + private ServiceRoleAuthorizer authorizer; + private BackendSql backend; + private KinesisStreamingViews views; + + @BeforeEach + void setUp() { + registry = new KinesisViewRegistry(AccountAwareStorageBackend.inMemory(ACCOUNT)); + kinesis = mock(KinesisService.class); + authorizer = mock(ServiceRoleAuthorizer.class); + when(authorizer.refusal(anyString(), anyString(), anyString(), any(), anyList())).thenReturn(Optional.empty()); + backend = mock(BackendSql.class); + views = new KinesisStreamingViews(registry, kinesis, authorizer, new RegionResolver("us-east-1", ACCOUNT), + Clock.fixed(Instant.parse("2026-11-18T10:00:00Z"), ZoneOffset.UTC)); + KinesisStream stream = new KinesisStream("events", "arn:aws:kinesis:us-west-2:" + ACCOUNT + ":stream/events"); + stream.setShards(List.of(new KinesisShard(SHARD, "0", "9", "1"))); + when(kinesis.describeStreamForAccount(ACCOUNT, "events", "us-west-2")).thenReturn(stream); + } + + private static ExternalStatement.CreateStreamingView createStatement() { + return new ExternalStatement.CreateStreamingView(null, "events_mv", false, SELECT); + } + + private KinesisViewBinding createView() { + views.create(createStatement(), "events", SCHEMA, SESSION, null, backend); + return views.find(SESSION, null, "events_mv").orElseThrow(); + } + + private static KinesisRecord record(String sequence, String data) { + return new KinesisRecord(data.getBytes(StandardCharsets.UTF_8), "pk-" + sequence, sequence, + Instant.parse("2026-11-18T09:59:00Z")); + } + + private void iteratorAfter(String sequence, String iterator) { + when(kinesis.getShardIteratorForAccount(ACCOUNT, "events", SHARD, "AFTER_SEQUENCE_NUMBER", sequence, + "us-west-2")).thenReturn(iterator); + } + + private void page(String iterator, List records, String next) { + Map page = new HashMap<>(); + page.put("Records", records); + page.put("NextShardIterator", next); + when(kinesis.getRecordsForAccount(eq(ACCOUNT), eq(iterator), anyInt(), eq("us-west-2"))).thenReturn(page); + } + + @Test + void createsTheStagingTableAndAnEmptyViewTableAndRemembersTheBinding() { + createView(); + + ArgumentCaptor sql = ArgumentCaptor.forClass(String.class); + verify(backend).execute(sql.capture()); + assertThat(sql.getValue(), startsWith("CREATE TABLE IF NOT EXISTS \"kds\".\"events\" (approximate_arrival_timestamp " + + "timestamp, partition_key varchar(256), shard_id char(20), sequence_number varchar(128), " + + "refresh_time timestamp, kinesis_data pg_catalog.varbyte); CREATE TABLE \"public\".\"events_mv\" AS ")); + assertThat(sql.getValue(), containsString(SELECT + " WITH NO DATA")); + assertThat(views.find(SESSION, "public", "events_mv").isPresent(), is(true)); + } + + @Test + void aViewNameThatIsTakenIsRefusedBeforeAnythingRuns() { + createView(); + + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> views.create(createStatement(), "events", SCHEMA, SESSION, null, backend)); + + assertThat(error.sqlState(), equalTo("42P07")); + verify(backend).execute(anyString()); + } + + @Test + void aMissingStreamFailsTheCreateAndLeavesNoBinding() { + when(kinesis.describeStreamForAccount(ACCOUNT, "events", "us-west-2")) + .thenThrow(new AwsException("ResourceNotFoundException", "Stream events not found", 400)); + + assertThrows(AwsException.class, () -> views.create(createStatement(), "events", SCHEMA, SESSION, null, backend)); + + verify(backend, never()).execute(anyString()); + assertThat(views.find(SESSION, null, "events_mv").isPresent(), is(false)); + } + + @Test + void refreshReadsFromTrimHorizonLoadsOneStatementPerBatchAndSavesTheCheckpoint() { + KinesisViewBinding view = createView(); + when(kinesis.getShardIteratorForAccount(ACCOUNT, "events", SHARD, "TRIM_HORIZON", null, "us-west-2")) + .thenReturn("it-1"); + page("it-1", List.of(record("1", "a"), record("2", "b")), "it-2"); + page("it-2", List.of(), "it-3"); + + long loaded = views.refresh(view, SCHEMA, null, backend); + + assertThat(loaded, equalTo(2L)); + ArgumentCaptor sql = ArgumentCaptor.forClass(String.class); + verify(backend, times(2)).execute(sql.capture()); + String load = sql.getAllValues().get(1); + assertThat(load, startsWith("INSERT INTO \"kds\".\"events\" VALUES (TIMESTAMP '2026-11-18 09:59:00.000000', " + + "E'pk-1', E'shardId-000000000000', E'1', TIMESTAMP '2026-11-18 10:00:00.000000', " + + "decode('61', 'hex')::pg_catalog.varbyte), (")); + assertThat(load, containsString("; INSERT INTO \"public\".\"events_mv\" " + SELECT + "; TRUNCATE \"kds\".\"events\"")); + assertThat(views.find(SESSION, null, "events_mv").orElseThrow().checkpoints(), equalTo(Map.of(SHARD, "2"))); + } + + @Test + void aSecondRefreshStartsAfterTheCheckpointAndLoadsNothingWhenTheStreamHasNoNewRecords() { + KinesisViewBinding view = createView(); + when(kinesis.getShardIteratorForAccount(ACCOUNT, "events", SHARD, "TRIM_HORIZON", null, "us-west-2")) + .thenReturn("it-1"); + page("it-1", List.of(record("1", "a")), "it-2"); + page("it-2", List.of(), "it-3"); + views.refresh(view, SCHEMA, null, backend); + iteratorAfter("1", "it-4"); + page("it-4", List.of(), "it-5"); + + long loaded = views.refresh(views.find(SESSION, null, "events_mv").orElseThrow(), SCHEMA, null, backend); + + assertThat(loaded, equalTo(0L)); + verify(backend, times(2)).execute(anyString()); + } + + @Test + void theCheckpointDoesNotMovePastABatchThatFailedToCommit() { + KinesisViewBinding view = createView(); + when(kinesis.getShardIteratorForAccount(ACCOUNT, "events", SHARD, "TRIM_HORIZON", null, "us-west-2")) + .thenReturn("it-1"); + page("it-1", List.of(record("1", "a")), "it-2"); + doThrow(new SpectrumReadException("22P02", "bad value")).when(backend) + .execute(argThat(statement -> statement.startsWith("INSERT INTO"))); + + assertThrows(SpectrumReadException.class, () -> views.refresh(view, SCHEMA, null, backend)); + + assertThat(views.find(SESSION, null, "events_mv").orElseThrow().checkpoints().isEmpty(), is(true)); + } + + @Test + void aRoleThatIsRefusedStopsTheRefreshBeforeAnyRecordIsRead() { + KinesisViewBinding view = createView(); + when(authorizer.refusal(eq(ROLE), eq(ACCOUNT), eq("redshift.amazonaws.com"), isNull(), anyList())) + .thenReturn(Optional.of("The role " + ROLE + " does not trust redshift.amazonaws.com.")); + + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> views.refresh(view, SCHEMA, null, backend)); + + assertThat(error.sqlState(), equalTo("42501")); + verify(kinesis, never()).getRecordsForAccount(anyString(), anyString(), anyInt(), anyString()); + } + + @Test + void theRefreshAsksForEveryKinesisActionOnTheStreamAndListStreams() { + KinesisViewBinding view = createView(); + when(kinesis.getShardIteratorForAccount(ACCOUNT, "events", SHARD, "TRIM_HORIZON", null, "us-west-2")) + .thenReturn("it-1"); + page("it-1", List.of(), "it-2"); + + views.refresh(view, SCHEMA, null, backend); + + @SuppressWarnings("unchecked") + ArgumentCaptor> permissions = ArgumentCaptor.forClass(List.class); + verify(authorizer).refusal(eq(ROLE), eq(ACCOUNT), eq("redshift.amazonaws.com"), isNull(), permissions.capture()); + List asked = new ArrayList<>(); + permissions.getValue().forEach(permission -> asked.add(permission.action() + " " + permission.resourceArn())); + String stream = "arn:aws:kinesis:us-west-2:" + ACCOUNT + ":stream/events"; + assertThat(asked, hasSize(6)); + assertThat(asked.contains("kinesis:GetRecords " + stream), is(true)); + assertThat(asked.contains("kinesis:ListStreams *"), is(true)); + } + + @Test + void aRefreshStartsFromTheCheckpointEvenWhenItWasGivenAStaleBinding() { + KinesisViewBinding stale = createView(); + when(kinesis.getShardIteratorForAccount(ACCOUNT, "events", SHARD, "TRIM_HORIZON", null, "us-west-2")) + .thenReturn("it-1"); + page("it-1", List.of(record("1", "a")), "it-2"); + page("it-2", List.of(), "it-3"); + views.refresh(stale, SCHEMA, null, backend); + iteratorAfter("1", "it-4"); + page("it-4", List.of(), "it-5"); + + // the binding read before the first refresh is stale; the second refresh must use the saved checkpoint + long loaded = views.refresh(stale, SCHEMA, null, backend); + + assertThat(loaded, equalTo(0L)); + verify(kinesis, times(1)).getShardIteratorForAccount(ACCOUNT, "events", SHARD, "TRIM_HORIZON", null, "us-west-2"); + } + + @Test + void aRefreshOfADroppedViewIsRefused() { + KinesisViewBinding view = createView(); + views.drop(view, false, false, backend); + + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> views.refresh(view, SCHEMA, null, backend)); + + assertThat(error.sqlState(), equalTo("42P01")); + } + + @Test + void aDropOfAViewThatIsAlreadyGoneDoesNothingWithIfExistsAndFailsWithout() { + KinesisViewBinding stale = createView(); + views.drop(stale, false, false, backend); + + views.drop(stale, true, false, backend); + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> views.drop(stale, false, false, backend)); + + assertThat(error.sqlState(), equalTo("42P01")); + verify(backend, times(2)).execute(anyString()); + } + + @Test + void aCascadeCleanupLeavesAReplacementOverAnotherStreamBound() { + KinesisViewBinding captured = createView(); + views.unbind(captured); + registry.bind(new KinesisViewBinding(ACCOUNT, SESSION.clusterKey(), "dev", "public", "events_mv", "kds", + "other", SELECT, Map.of())); + + views.unbindIfCurrent(captured); + + assertThat(views.find(SESSION, null, "events_mv").isPresent(), is(true)); + } + + @Test + void theStagingTableStaysWhileAnotherViewReadsTheStream() { + KinesisViewBinding first = createView(); + views.create(new ExternalStatement.CreateStreamingView(null, "other_mv", false, SELECT), "events", SCHEMA, + SESSION, null, backend); + + views.drop(first, false, false, backend); + + verify(backend).execute("DROP TABLE \"public\".\"events_mv\" RESTRICT"); + } + + @Test + void theViewsOfASchemaAreListedAndDropSqlNamesTheViewTable() { + KinesisViewBinding view = createView(); + + assertThat(views.overSchema(SESSION, "kds"), equalTo(List.of(view))); + assertThat(views.overSchema(SESSION, "other"), equalTo(List.of())); + assertThat(KinesisStreamingViews.dropSql(view, true, false), + equalTo("DROP TABLE IF EXISTS \"public\".\"events_mv\" RESTRICT")); + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumKinesisViewPreparationTest.java b/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumKinesisViewPreparationTest.java new file mode 100644 index 0000000000..943e61ebd6 --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumKinesisViewPreparationTest.java @@ -0,0 +1,168 @@ +package io.floci.aws.services.redshift.spectrum; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.services.glue.GlueService; +import io.floci.aws.services.iam.ServiceRoleAuthorizer; +import io.floci.aws.services.kinesis.KinesisService; +import io.floci.aws.services.kinesis.model.KinesisShard; +import io.floci.aws.services.kinesis.model.KinesisStream; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Clock; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +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.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class SpectrumKinesisViewPreparationTest { + 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 SpectrumSession IN_TRANSACTION = + new SpectrumSession(ACCOUNT, ACCOUNT + ":c", "dev", List.of(), true); + private static final String CREATE_VIEW = "CREATE MATERIALIZED VIEW events_mv AUTO REFRESH NO AS " + + "SELECT sequence_number FROM kds.events"; + private static final String REFRESH = "REFRESH MATERIALIZED VIEW events_mv"; + + private KinesisSchemaRegistry kinesisSchemas; + private KinesisService kinesis; + private BackendSql backend; + private SpectrumQueryPreparation preparation; + + @BeforeEach + void setUp() { + kinesisSchemas = new KinesisSchemaRegistry(AccountAwareStorageBackend.inMemory(ACCOUNT)); + kinesisSchemas.bind(new KinesisSchemaBinding(ACCOUNT, SESSION.clusterKey(), "dev", "kds", null, ROLE)); + kinesis = mock(KinesisService.class); + ServiceRoleAuthorizer authorizer = mock(ServiceRoleAuthorizer.class); + when(authorizer.refusal(anyString(), anyString(), anyString(), any(), anyList())).thenReturn(Optional.empty()); + KinesisStreamingViews views = new KinesisStreamingViews( + new KinesisViewRegistry(AccountAwareStorageBackend.inMemory(ACCOUNT)), kinesis, + authorizer, new RegionResolver("us-east-1", ACCOUNT), Clock.systemUTC()); + KinesisStream stream = new KinesisStream("events", "arn:aws:kinesis:us-east-1:" + ACCOUNT + ":stream/events"); + stream.setShards(List.of(new KinesisShard("shardId-000000000000", "0", "9", "1"))); + when(kinesis.describeStreamForAccount(ACCOUNT, "events", "us-east-1")).thenReturn(stream); + backend = mock(BackendSql.class); + when(backend.permitsCachePublication()).thenReturn(true); + ExternalMetadataWriter metadata = new ExternalMetadataWriter(mock(GlueService.class), new ObjectMapper()); + preparation = new SpectrumQueryPreparation(mock(ExternalCatalogRegistry.class), kinesisSchemas, + mock(ExternalTableMaterializer.class), new ExternalStatementParser(), mock(GlueService.class), metadata, + new ExternalCatalogLocks(), views, (accountId, clusterIdentifier) -> null); + } + + @Test + void aViewOverAStreamIsHandledAndAViewOverAnythingElseIsLeftToPostgres() { + assertThat(preparation.handlesDdl(CREATE_VIEW, SESSION), is(true)); + assertThat(preparation.handlesDdl("CREATE MATERIALIZED VIEW v AS SELECT 1 FROM public.t", SESSION), is(false)); + assertThat(preparation.handlesDdl(REFRESH, SESSION), is(false)); + } + + @Test + void createRefreshAndDropRunAsTheirOwnCommands() { + assertThat(preparation.prepare(CREATE_VIEW, SESSION, backend), is(true)); + assertThat(preparation.handlesDdl(REFRESH, SESSION), is(true)); + Map page = new HashMap<>(); + page.put("Records", List.of()); + page.put("NextShardIterator", null); + when(kinesis.getShardIteratorForAccount(ACCOUNT, "events", "shardId-000000000000", "TRIM_HORIZON", null, + "us-east-1")).thenReturn("it"); + when(kinesis.getRecordsForAccount(anyString(), anyString(), anyInt(), anyString())).thenReturn(page); + + assertThat(preparation.prepare(REFRESH, SESSION, backend), is(true)); + assertThat(preparation.prepare("DROP MATERIALIZED VIEW events_mv", SESSION, backend), is(true)); + + verify(backend).execute("DROP TABLE \"public\".\"events_mv\" RESTRICT; DROP TABLE IF EXISTS \"kds\".\"events\""); + assertThat(preparation.handlesDdl(REFRESH, SESSION), is(false)); + assertThat(preparation.commandTag(CREATE_VIEW), equalTo("CREATE MATERIALIZED VIEW")); + assertThat(preparation.commandTag(REFRESH), equalTo("REFRESH MATERIALIZED VIEW")); + assertThat(preparation.commandTag("DROP MATERIALIZED VIEW events_mv"), equalTo("DROP MATERIALIZED VIEW")); + } + + @Test + void autoRefreshYesAndTransactionBlocksAreRefused() { + SpectrumSqlException auto = assertThrows(SpectrumSqlException.class, () -> preparation.prepare( + "CREATE MATERIALIZED VIEW v AUTO REFRESH YES AS SELECT * FROM kds.events", SESSION, backend)); + SpectrumSqlException inTransaction = assertThrows(SpectrumSqlException.class, + () -> preparation.prepare(CREATE_VIEW, IN_TRANSACTION, backend)); + + assertThat(auto.sqlState(), equalTo("0A000")); + assertThat(auto.getMessage(), containsString("AUTO REFRESH YES")); + assertThat(inTransaction.sqlState(), equalTo("0A000")); + verify(backend, never()).execute(anyString()); + } + + @Test + void aJoinInTheViewIsRefused() { + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, () -> preparation.prepare( + "CREATE MATERIALIZED VIEW v AS SELECT * FROM kds.events e JOIN public.t ON e.shard_id = t.id", + SESSION, backend)); + + assertThat(error.sqlState(), equalTo("0A000")); + assertThat(error.getMessage(), containsString("JOIN")); + verify(backend, never()).execute(anyString()); + } + + @Test + void aGroupingOrAggregateInTheViewIsRefused() { + for (String select : new String[] { + "SELECT partition_key, count(*) FROM kds.events GROUP BY partition_key", + "SELECT max(sequence_number) FROM kds.events", + "SELECT DISTINCT shard_id FROM kds.events"}) { + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, () -> preparation.prepare( + "CREATE MATERIALIZED VIEW v AS " + select, SESSION, backend)); + + assertThat(select, error.sqlState(), equalTo("0A000")); + assertThat(select, error.getMessage(), containsString("aggregate")); + } + preparation.prepare("CREATE MATERIALIZED VIEW v AS SELECT 'count(x)' AS c, \"group by\" FROM kds.events", + SESSION, backend); + } + + @Test + void droppingTheLastViewAlsoDropsTheStagingTable() { + preparation.prepare(CREATE_VIEW, SESSION, backend); + + preparation.prepare("DROP MATERIALIZED VIEW events_mv", SESSION, backend); + + verify(backend).execute("DROP TABLE \"public\".\"events_mv\" RESTRICT; DROP TABLE IF EXISTS \"kds\".\"events\""); + } + + @Test + void refreshInsideATransactionBlockIsRefused() { + preparation.prepare(CREATE_VIEW, SESSION, backend); + + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> preparation.prepare(REFRESH, IN_TRANSACTION, backend)); + + assertThat(error.sqlState(), equalTo("25001")); + } + + @Test + void dropSchemaCascadeTakesTheViewsThatReadItWithIt() { + preparation.prepare(CREATE_VIEW, SESSION, backend); + + preparation.prepare("DROP SCHEMA kds CASCADE", SESSION, backend); + + verify(backend).execute(argThat(sql -> sql.startsWith( + "DROP TABLE IF EXISTS \"public\".\"events_mv\" CASCADE; DROP SCHEMA \"kds\" CASCADE"))); + assertThat(preparation.handlesDdl(REFRESH, SESSION), is(false)); + } +}