feat(redshift): ingest a Kinesis stream into a streaming materialized view (#8880)

CREATE MATERIALIZED VIEW [AUTO REFRESH NO] AS SELECT over a stream of a Kinesis external schema creates a streaming materialized view, REFRESH MATERIALIZED VIEW loads the stream into it, and DROP MATERIALIZED VIEW [IF EXISTS] [CASCADE] removes it. The view is a PostgreSQL table built from the SELECT over a staging table with the six documented metadata columns. A refresh checks the schema role's Kinesis permissions and its trust of redshift.amazonaws.com, reads each shard from TRIM_HORIZON the first time and after its checkpoint afterwards, and loads each batch in one implicit transaction; Floci keeps the checkpoints per shard, so truncating the view does not rewind the stream. AUTO REFRESH YES, a JOIN, and grouping or aggregation are refused with 0A000, and a view query holding a second statement with 42601.

Closes #7813
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-18 21:21:48 -04:00
1 parent 74938f0e8a
commit 563de77b1e
14 files changed
+1333 -9

No files matched your search

@@ -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) == '#') {
@@ -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 <V> Map<String, V> ordered(Map<String, V> 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 { }
}
@@ -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")) {
@@ -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<String> 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<String, Object> 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<KinesisViewBinding> 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<KinesisViewBinding> 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<KinesisViewBinding> 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<String, Object> page = kinesis.getRecordsForAccount(view.accountId(), iterator, PAGE_LIMIT, region);
@SuppressWarnings("unchecked")
List<KinesisRecord> records = (List<KinesisRecord>) page.get("Records");
iterator = (String) page.get("NextShardIterator");
if (records == null || records.isEmpty()) {
break;
}
for (List<KinesisRecord> 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<Permission> permissions = new ArrayList<>();
for (String action : READ_ACTIONS) {
permissions.add(new Permission(action, streamArn));
}
permissions.add(new Permission("kinesis:ListStreams", "*"));
Optional<String> 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<List<KinesisRecord>> batches(List<KinesisRecord> records) {
List<List<KinesisRecord>> batches = new ArrayList<>();
List<KinesisRecord> 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<KinesisRecord> 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);
}
}
@@ -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<String, String> 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<String, String> 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");
}
}
}
@@ -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<KinesisViewBinding> {
@Inject
public KinesisViewRegistry(StorageFactory storageFactory) {
super(storageFactory.<KinesisViewBinding>create("redshift", "redshift-kinesis-views.json",
new TypeReference<>() { }));
}
KinesisViewRegistry(AccountAwareStorageBackend<KinesisViewBinding> bindings) {
super(bindings);
}
}
@@ -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();
}
}
@@ -24,7 +24,7 @@ abstract class SchemaBindingRegistry<B extends SchemaBinding> 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<B extends SchemaBinding> 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<B> find(String accountId, String clusterKey, String databaseName, String schemaName) {
return bindings.getForAccount(accountId, key(clusterKey, databaseName, schemaName));
}
@@ -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<RedshiftService> redshift) {
this(registry, kinesisSchemas, materializer, parser, glue, metadata, catalogLocks,
ExternalCatalogLocks catalogLocks, KinesisStreamingViews views,
Instance<RedshiftService> 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<String, String, String> clusterRegion) {
this(registry, kinesisSchemas, materializer, parser, glue, metadata, catalogLocks,
new KinesisStreamingViews(new KinesisViewRegistry(
AccountAwareStorageBackend.<KinesisViewBinding>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<String, String, String> 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<KinesisViewBinding> 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<KinesisViewBinding> 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<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.
@@ -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<KinesisViewBinding> 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<ExternalReferenceScanner.Reference> streamSource(String select, SpectrumSession session) {
return ExternalReferenceScanner.scan(select, kinesisBindings(session).keySet()).stream().findFirst();
}
private void createStreamingView(ExternalStatement.CreateStreamingView view,
Map<String, KinesisSchemaBinding> kinesis, SpectrumSession session,
BackendSql backend) {
if (session.inTransaction()) {
throw new SpectrumSqlException("0A000",
"CREATE MATERIALIZED VIEW over a stream inside a transaction is not supported");
}
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<ExternalReferenceScanner.Reference> 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<String, KinesisSchemaBinding> 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<String, KinesisSchemaBinding> kinesisBindings(SpectrumSession session) {
Map<String, KinesisSchemaBinding> 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);
}