feat(redshift): prune external table partitions from query WHERE predicates (#7413)

* feat(redshift): prune external table partitions from query WHERE predicates

Load only the partitions selected by top-level AND predicates of the query WHERE clause for external tables, accumulating partitions across queries and avoiding full scans when specific partitions are requested.

* fix(redshift): handle CASE in partition pruner, overlapping refreshes, and isolate spectrum test schema

* fix(redshift): identify materialized rows by partition and share SQL lexer

Tell materialized external table rows apart by an internal partition identifier column so that refreshing or deleting a partition only deletes its exact rows and never removes rows belonging to partitions whose keys overlap when converted. Dropping a partition no longer reads or authorizes retained overlapping partitions, preventing unauthorized S3 access errors on unselected partitions.

Share tokenization rules between ExternalReferenceScanner and PartitionPruner in SpectrumSqlLexer.

* fix(redshift): hide the partition column behind a view and read strings as strings in the scanner

A partitioned external table kept the partition each row came from in a column of the public table,
so SELECT * returned an extra column and INSERT ... SELECT * could fail on the column count. The rows
now live in a backing table, _floci_spectrum_<table>, and the name the user queries is a view of the
declared columns only. DROP TABLE drops the view and the backing table, and the Data API ListTables
does not list the backing table.

ExternalReferenceScanner took a one-character string such as ';' for a statement separator, which
cleared the table context and let the query skip preparation and its S3 checks. It now reads the
structural characters by token kind.

The pruning integration test used the legacy catalog, whose parser does not read PARTITIONED BY, so
it now creates a Glue database.

* fix(redshift): keep the partition backing table in a schema of its own and send plain batches

The batches that drop and replace the relation of a partitioned external table started with a DO
block. PostgresExtendedBackendSession wraps only batches that start with CREATE or DROP, so an
extended query sent them unchanged and PostgreSQL refused several commands in one prepared
statement. A DO block nested in the wrapper is not valid either, and a schema or table name that
held the dollar-quote tag would have closed the body early. The relation is now dropped with
DROP VIEW or DROP TABLE as the last load made it, so every batch is plain statements.

The backing table was named after the table it backs in the user's schema, so a Glue table of the
same name could drop or reuse it, and the Data API ListTables hid every table with that prefix. It
now lives in the schema floci_spectrum under a name made from the external schema and table, and
ListSchemas and ListTables hide only that schema.

* fix(redshift): load the whole external table when partition keys overlap instead of keeping a backing table

Delete by key value is only safe when no two partitions cast to the same value. When they do (integer 1 and 01, decimal 1.0 and 1.00, boolean true and t), the query reads every partition and a change replaces the whole table. This drops the backing table, view and floci_spectrum schema, which broke dropping a table whose Glue definition gained partition keys, other users' loads, and DROP SCHEMA CASCADE.

* fix(redshift): expect 22P02 SQLSTATE on invalid partition data
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-03 21:39:17 -04:00
1 parent bc31464ab9
commit a42779bb2a
13 files changed
+2220 -155

No files matched your search

+18 -2
View File
@@ -716,8 +716,24 @@ runtime when container management is unsuitable.
Tables declared `STORED AS PARQUET` (or with a Parquet input format or SerDe in Glue) are read the same
way. Columns are matched to the Parquet files by name, ignoring case. A declared column that a partition's
files do not carry, as when the column was added to the table after those files were written, reads as
`NULL`. A value that cannot be converted to the declared type fails the query. Partition pruning is not
supported: every registered partition is listed, authorized and loaded.
`NULL`. A value that cannot be converted to the declared type fails the query.
A partitioned table is loaded partition by partition, and a query loads only the partitions its `WHERE`
can select, as Spectrum reads only those. Only these are listed, checked against the role's S3 access and
read, so a partition that no predicate of the query selects can be unreadable without failing the query.
A predicate selects partitions when it is a top-level `AND` term of the `WHERE` of the block that names the
table, uses only partition keys, literals, comparisons, `IN`, `BETWEEN`, `IS [NOT] NULL`, `AND`, `OR` and
`NOT`, covers an integer, date or string key (a string key only for `=`, `<>` and `IN`), and is false for a
row whose keys are all NULL, so that a table on the nullable side of an outer join keeps its rows. Any
other predicate leaves every partition in. The query still runs unchanged on the rows loaded, so pruning
never changes a result. Partitions loaded by one query stay for the next: a later query adds the ones it
needs, reloads the ones whose objects or Glue entry changed and drops the ones Glue no longer lists.
When two partitions hold key values that PostgreSQL casts to the same value, such as integer `1` and `01`,
rows can no longer be told apart by partition, so a query on that table loads every partition and replaces
the whole table when any of them changes.
Pruning applies to the simple query protocol and the Data API. A session in a transaction block, and a client
on the extended query protocol (the default of the PostgreSQL JDBC driver, unless `preferQueryMode=simple`),
load every partition.
Materialized relations are cached in the cluster database. Each new query checks the associated
role, trust policy and S3 access before using cached data, following the existing S3 enforcement
@@ -5,7 +5,6 @@ import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
@@ -313,144 +312,37 @@ public final class ExternalReferenceScanner {
private static List<Token> tokenize(String sql) {
List<Token> result = new ArrayList<>();
List<SpectrumSqlLexer.Token> raw = SpectrumSqlLexer.tokenize(sql).tokens();
int i = 0;
while (i < sql.length()) {
char c = sql.charAt(i);
if (c == '\'' || c == '-' && i + 1 < sql.length() && sql.charAt(i + 1) == '-'
|| c == '/' && i + 1 < sql.length() && sql.charAt(i + 1) == '*') {
i = skip(sql, i, c == '\'' && isEscapeStringPrefix(sql, i));
} else if (c == '$' && dollarTagEnd(sql, i) > 0) {
i = skipDollarQuoted(sql, i);
} else if (c == '"' || Character.isLetter(c) || c == '_') {
while (i < raw.size()) {
SpectrumSqlLexer.Token t = raw.get(i);
if (t.kind() == SpectrumSqlLexer.Kind.WORD || t.kind() == SpectrumSqlLexer.Kind.QUOTED_WORD) {
List<Word> chain = new ArrayList<>();
i = read(sql, i, chain);
while (true) {
int separator = skipTrivia(sql, i);
if (separator >= sql.length() || sql.charAt(separator) != '.') {
break;
}
int next = skipTrivia(sql, separator + 1);
if (next >= sql.length() || !(sql.charAt(next) == '"' || Character.isLetter(sql.charAt(next))
|| sql.charAt(next) == '_')) {
break;
}
i = read(sql, next, chain);
chain.add(new Word(t.text(), t.kind() == SpectrumSqlLexer.Kind.QUOTED_WORD));
i++;
while (i + 1 < raw.size() && raw.get(i).kind() == SpectrumSqlLexer.Kind.OP
&& ".".equals(raw.get(i).text())
&& (raw.get(i + 1).kind() == SpectrumSqlLexer.Kind.WORD
|| raw.get(i + 1).kind() == SpectrumSqlLexer.Kind.QUOTED_WORD)) {
chain.add(new Word(raw.get(i + 1).text(), raw.get(i + 1).kind() == SpectrumSqlLexer.Kind.QUOTED_WORD));
i += 2;
}
result.add(new Token(chain, '\0'));
} else {
if (c == '(' || c == ')' || c == ',' || c == ';') {
result.add(new Token(null, c));
// by kind, not by text: the string ';' is not a statement separator
char symbol = switch (t.kind()) {
case LPAREN -> '(';
case RPAREN -> ')';
case COMMA -> ',';
case SEMICOLON -> ';';
default -> '\0';
};
if (symbol != '\0') {
result.add(new Token(null, symbol));
}
i++;
}
}
return result;
}
private static int skipTrivia(String sql, int start) {
int i = start;
while (i < sql.length()) {
if (Character.isWhitespace(sql.charAt(i))) {
i++;
} else if (sql.charAt(i) == '-' && i + 1 < sql.length() && sql.charAt(i + 1) == '-'
|| sql.charAt(i) == '/' && i + 1 < sql.length() && sql.charAt(i + 1) == '*') {
i = skip(sql, i, false);
} else {
break;
}
}
return i;
}
private static int read(String sql, int start, List<Word> chain) {
if (sql.charAt(start) == '"') {
StringBuilder value = new StringBuilder();
int i = start + 1;
while (i < sql.length()) {
if (sql.charAt(i) == '"') {
if (i + 1 < sql.length() && sql.charAt(i + 1) == '"') {
value.append('"');
i += 2;
} else {
i++;
break;
}
} else {
value.append(sql.charAt(i++));
}
}
chain.add(new Word(value.toString(), true));
return i;
}
int i = start;
while (i < sql.length() && (Character.isLetterOrDigit(sql.charAt(i)) || sql.charAt(i) == '_'
|| sql.charAt(i) == '$')) {
i++;
}
chain.add(new Word(sql.substring(start, i).toLowerCase(Locale.ROOT), false));
return i;
}
private static boolean isEscapeStringPrefix(String sql, int quote) {
if (quote == 0 || Character.toLowerCase(sql.charAt(quote - 1)) != 'e') {
return false;
}
if (quote == 1) {
return true;
}
char before = sql.charAt(quote - 2);
return !(Character.isLetterOrDigit(before) || before == '_' || before == '$');
}
/** Returns the index just past an opening dollar-quote tag such as {@code $$} or {@code $body$}, or -1. */
private static int dollarTagEnd(String sql, int start) {
int i = start + 1;
if (i < sql.length() && (Character.isLetter(sql.charAt(i)) || sql.charAt(i) == '_')) {
while (i < sql.length() && (Character.isLetterOrDigit(sql.charAt(i)) || sql.charAt(i) == '_')) {
i++;
}
}
return i < sql.length() && sql.charAt(i) == '$' ? i + 1 : -1;
}
private static int skipDollarQuoted(String sql, int start) {
int bodyStart = dollarTagEnd(sql, start);
int close = sql.indexOf(sql.substring(start, bodyStart), bodyStart);
return close < 0 ? sql.length() : close + (bodyStart - start);
}
private static int skip(String sql, int start, boolean backslashEscapes) {
if (sql.charAt(start) == '\'') {
int i = start + 1;
while (i < sql.length()) {
char c = sql.charAt(i);
if (backslashEscapes && c == '\\') {
i += 2;
} else if (c == '\'' && (i + 1 >= sql.length() || sql.charAt(i + 1) != '\'')) {
return i + 1;
} else {
i += c == '\'' ? 2 : 1;
}
}
return sql.length();
}
if (sql.charAt(start) == '-') {
int i = sql.indexOf('\n', start + 2);
return i < 0 ? sql.length() : i;
}
int depth = 1;
int i = start + 2;
while (i < sql.length() && depth > 0) {
if (sql.startsWith("/*", i)) {
depth++;
i += 2;
} else if (sql.startsWith("*/", i)) {
depth--;
i += 2;
} else {
i++;
}
}
return Math.min(i, sql.length());
}
}
@@ -26,8 +26,15 @@ import org.jboss.logging.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
@@ -35,6 +42,7 @@ import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
@@ -42,8 +50,10 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@ApplicationScoped
public class ExternalTableMaterializer {
@@ -56,6 +66,10 @@ public class ExternalTableMaterializer {
"\\bHTTP(?:/[0-9.]+)?\\s+(?:Error:\\s+)?(?:HTTP(?:/[0-9.]+)?\\s+)?403\\b|\\b403\\s*\\(Forbidden\\)|\\b403\\s+Forbidden\\b");
private static final long LOCK_TIMEOUT_SECONDS = 30;
private static final String SCRATCH_KEY_PREFIX = "spectrum-";
private static final String HIVE_DEFAULT_PARTITION = "__HIVE_DEFAULT_PARTITION__";
private static final String NULL_KEY = "\u0000null";
private static final Set<String> INTEGER_TYPES = Set.of("tinyint", "smallint", "int", "integer", "bigint");
private static final Pattern DECIMAL_SCALE = Pattern.compile("^decimal\\(\\d+,(\\d+)\\)$");
private static final Duration STALE_SCRATCH_AGE = Duration.ofHours(1);
private static final String ICEBERG_SETUP = "INSTALL iceberg; LOAD iceberg;\n";
private static final String ICEBERG_MANIFESTS = "SELECT DISTINCT manifest_path FROM read_avro(%s)";
@@ -77,9 +91,14 @@ public class ExternalTableMaterializer {
private final Set<String> sweptAccounts = ConcurrentHashMap.newKeySet();
private final Map<BackendSql, Map<String, PendingLoad>> pendingLoads = new ConcurrentHashMap<>();
private final Map<String, PendingLoad> latestLoads = new ConcurrentHashMap<>();
/** The partitions each partitioned table holds in PostgreSQL, so a query loads only the ones it reads. */
private final ConcurrentHashMap<String, LoadedPartitions> loadedPartitions = new ConcurrentHashMap<>();
private record PendingLoad(String fingerprint, String definitions) { }
/** What a partitioned table holds: the table it was loaded for, and a fingerprint per loaded partition. */
private record LoadedPartitions(String identity, Map<List<String>, String> partitions) { }
public void finishCycle(BackendSql backend) {
pendingLoads.remove(backend);
}
@@ -124,14 +143,23 @@ public class ExternalTableMaterializer {
public Outcome ensureCurrent(BackendSql backend, SpectrumSession session, ExternalSchemaBinding binding,
String tableName) {
return ensureCurrent(backend, session, binding, tableName, null);
}
/**
* Loads the table the way the query needs it. Given the text of the query, a partitioned table loads only
* the partitions its WHERE can select, as Spectrum reads only those; without it every partition loads.
*/
public Outcome ensureCurrent(BackendSql backend, SpectrumSession session, ExternalSchemaBinding binding,
String tableName, String sql) {
try (ExternalCatalogLocks.Guard ignored = catalogLocks.read(binding,
session.inTransaction() || !backend.permitsCachePublication())) {
return ensureCurrentLocked(backend, session, binding, tableName);
return ensureCurrentLocked(backend, session, binding, tableName, sql);
}
}
private Outcome ensureCurrentLocked(BackendSql backend, SpectrumSession session, ExternalSchemaBinding binding,
String tableName) {
String tableName, String sql) {
Table table;
try {
table = RequestScopes.callAs(session.accountId(), () -> glueService.getTable(binding.glueDatabase(), tableName));
@@ -150,6 +178,9 @@ public class ExternalTableMaterializer {
authorizeIcebergMetadata(session.accountId(), binding, roleSession, table, location);
authorizeIcebergManifests(session.accountId(), binding, roleSession, table, location);
List<Partition> partitions = partitions(session.accountId(), binding, table);
if (holdsPartitions(table, session, backend, partitions)) {
return ensurePartitions(backend, session, binding, roleSession, table, location, partitions, sql);
}
List<ReadSource> sources = readSources(session.accountId(), binding, roleSession, table, location, partitions);
List<S3Object> objects = sources.stream().flatMap(source -> source.objects().stream()).toList();
authorizeObjects(session.accountId(), binding, roleSession, sources);
@@ -176,7 +207,9 @@ public class ExternalTableMaterializer {
}
String previousSignature = local == null ? schemaSignatures.get(cacheKey) : local.definitions();
latestLoads.remove(cacheKey);
String definitions = load(backend, session, binding, roleSession, table, sources, previousSignature);
// a load of every partition replaces what the table held, so the partitions it holds are no longer known
loadedPartitions.remove(cacheKey);
String definitions = load(backend, session, binding, roleSession, table, sources, previousSignature, null);
if (!backend.permitsCachePublication()) {
fingerprints.remove(cacheKey);
PendingLoad loaded = new PendingLoad(fingerprint, definitions);
@@ -220,6 +253,99 @@ public class ExternalTableMaterializer {
}
}
/**
* Whether the table is loaded partition by partition: a partitioned table that has partitions, for a session
* whose loads are published at once. A transaction may roll its load back and an Extended Query load is
* published only when its cycle commits, so those keep loading every partition.
*/
private static boolean holdsPartitions(Table table, SpectrumSession session, BackendSql backend,
List<Partition> partitions) {
return hasPartitionKeys(table) && !partitions.isEmpty() && !session.inTransaction()
&& backend.permitsCachePublication();
}
/**
* The table in PostgreSQL holds the partitions loaded so far, and a query adds the ones it reads that are
* missing or have changed and drops the ones Glue no longer has. A query never removes a partition another
* query loaded, so concurrent queries with different predicates cannot take each other's rows away, and the
* predicates of each query still run on the rows in PostgreSQL.
*/
private Outcome ensurePartitions(BackendSql backend, SpectrumSession session, ExternalSchemaBinding binding,
RedshiftRoleAccess.RoleSession roleSession, Table table, Location location,
List<Partition> partitions, String sql) {
String accountId = session.accountId();
Optional<PartitionPruner.Filter> filter = PartitionPruner.filterFor(sql, binding.schemaName(),
table.getName(), table.getPartitionKeys());
// partitions that PostgreSQL's casts make equal cannot be told apart by key value, so they are all read
boolean overlapping = hasOverlappingPartitions(table, partitions);
List<Partition> qualified = filter.isEmpty() || overlapping ? partitions
: partitions.stream().filter(partition -> filter.get().matches(partition.getValues())).toList();
List<ReadSource> sources = readSources(accountId, binding, roleSession, table, location, qualified);
authorizeObjects(accountId, binding, roleSession, sources);
String definitions = columnDefinitions(readPlanWithColumns(binding, table));
String identity = Digests.sha256Hex(table.getVersionId() + "|" + table.getUpdateTime() + "|" + definitions);
String cacheKey = cacheKey(session, binding, table.getName());
String label = binding.schemaName() + "." + table.getName();
ReentrantLock lock = locks.computeIfAbsent(cacheKey, ignored -> new ReentrantLock());
acquire(lock, label, false);
try {
LoadedPartitions state = loadedPartitions.get(cacheKey);
String previousSignature = schemaSignatures.get(cacheKey);
boolean reset = state == null || !state.identity().equals(identity) || !definitions.equals(previousSignature);
Map<List<String>, String> held = reset ? Map.of() : state.partitions();
Set<List<String>> existing = partitions.stream().map(Partition::getValues).collect(Collectors.toSet());
List<List<String>> deletions = new ArrayList<>(held.keySet().stream()
.filter(values -> !existing.contains(values)).toList());
List<ReadSource> toLoad = new ArrayList<>();
Map<List<String>, String> loaded = new HashMap<>(held);
deletions.forEach(loaded::remove);
for (ReadSource source : sources) {
List<String> values = source.partition().getValues();
String fingerprint = partitionFingerprint(table, source);
if (!fingerprint.equals(held.get(values))) {
toLoad.add(source);
if (held.containsKey(values)) {
deletions.add(values);
}
loaded.put(values, fingerprint);
}
}
if (overlapping && !reset && (!deletions.isEmpty() || !toLoad.isEmpty())) {
// a delete by key value cannot tell overlapping partitions apart, so the whole table is replaced
reset = true;
toLoad.clear();
toLoad.addAll(sources);
loaded.clear();
for (ReadSource source : sources) {
loaded.put(source.partition().getValues(), partitionFingerprint(table, source));
}
}
if (!reset && deletions.isEmpty() && toLoad.isEmpty()) {
return Outcome.CURRENT;
}
// what the table holds is about to change, so no fingerprint of a full load can vouch for it
fingerprints.remove(cacheKey);
latestLoads.remove(cacheKey);
pendingLoads.values().forEach(loads -> loads.remove(cacheKey));
loadedPartitions.remove(cacheKey);
load(backend, session, binding, roleSession, table, toLoad, previousSignature, reset ? null : deletions);
schemaSignatures.put(cacheKey, definitions);
loadedPartitions.put(cacheKey, new LoadedPartitions(identity, Map.copyOf(loaded)));
return Outcome.LOADED;
} finally {
lock.unlock();
}
}
/** What a partition was loaded from: its descriptor and the objects it listed, with their sizes and ETags. */
private static String partitionFingerprint(Table table, ReadSource source) {
StringBuilder value = new StringBuilder(partitionEntry(table, source.partition())).append('|');
for (S3Object object : source.objects()) {
value.append(object.getKey()).append(':').append(object.getSize()).append(':').append(object.getETag()).append(';');
}
return Digests.sha256Hex(value.toString());
}
/**
* A session inside a transaction can hold a PostgreSQL lock on the table until it commits, so
* waiting forever on the Java lock here could deadlock in a way PostgreSQL's detector cannot see.
@@ -251,6 +377,7 @@ public class ExternalTableMaterializer {
lock.lock();
try {
fingerprints.remove(key);
loadedPartitions.remove(key);
latestLoads.remove(key);
pendingLoads.values().forEach(loads -> loads.remove(key));
} finally {
@@ -270,6 +397,7 @@ public class ExternalTableMaterializer {
lock.lock();
try {
fingerprints.remove(key);
loadedPartitions.remove(key);
schemaSignatures.remove(key);
latestLoads.remove(key);
pendingLoads.values().forEach(loads -> loads.remove(key));
@@ -284,7 +412,8 @@ public class ExternalTableMaterializer {
/** Tables of one external schema this materializer has loaded into PostgreSQL and still tracks. */
public Set<String> loadedTables(String clusterKey, String databaseName, String schemaName) {
String prefix = schemaPrefix(clusterKey, databaseName, schemaName);
return fingerprints.keySet().stream().filter(key -> key.startsWith(prefix))
return Stream.concat(fingerprints.keySet().stream(), loadedPartitions.keySet().stream())
.filter(key -> key.startsWith(prefix))
.map(key -> key.substring(prefix.length())).collect(Collectors.toSet());
}
@@ -637,16 +766,13 @@ public class ExternalTableMaterializer {
*/
private String load(BackendSql backend, SpectrumSession session, ExternalSchemaBinding binding,
RedshiftRoleAccess.RoleSession roleSession, Table table,
List<ReadSource> sources, String loadedDefinitions) {
GlueTableResolver.ReadPlan plan = GlueTableResolver.readPlan(table);
if (plan.columns().isEmpty()) {
throw new SpectrumSqlException("0A000", "Glue table \"" + binding.schemaName() + "." + table.getName() + "\" declares no columns");
}
List<ReadSource> sources, String loadedDefinitions, List<List<String>> deletions) {
GlueTableResolver.ReadPlan plan = readPlanWithColumns(binding, table);
String schema = quote(binding.schemaName());
String target = schema + "." + quote(table.getName());
String stagingName = "floci_spectrum_stg_" + UUID.randomUUID().toString().replace("-", "");
String staging = "pg_temp." + quote(stagingName);
String definitions = plan.columns().stream().map(column -> quote(column.getName()) + " " + GlueTypeMapper.toPostgres(column.getType())).collect(Collectors.joining(", "));
String definitions = columnDefinitions(plan);
boolean stagingCreated = false;
String scratchKey = null;
try {
@@ -678,7 +804,14 @@ public class ExternalTableMaterializer {
throw new SpectrumReadException(SQLSTATE_LOAD_FAILED, "External table \"" + binding.schemaName() + "." + table.getName() + "\" exceeds configured row limit");
}
}
if (definitions.equals(loadedDefinitions)) {
if (deletions != null) {
// the table already holds other partitions, so only the ones named here are replaced
String delete = deletions.isEmpty() ? "" : "DELETE FROM " + target + " WHERE "
+ deletions.stream().map(values -> "(" + partitionCondition(table, values) + ")")
.distinct().collect(Collectors.joining(" OR ")) + "; ";
backend.execute("CREATE TABLE IF NOT EXISTS " + target + " (" + definitions + "); " + delete
+ "INSERT INTO " + target + " SELECT * FROM " + staging + "; DROP TABLE " + staging);
} else if (definitions.equals(loadedDefinitions)) {
backend.execute("CREATE TABLE IF NOT EXISTS " + target + " (" + definitions + "); TRUNCATE " + target
+ "; INSERT INTO " + target + " SELECT * FROM " + staging + "; DROP TABLE " + staging);
} else {
@@ -711,6 +844,123 @@ public class ExternalTableMaterializer {
}
}
private static GlueTableResolver.ReadPlan readPlanWithColumns(ExternalSchemaBinding binding, Table table) {
GlueTableResolver.ReadPlan plan = GlueTableResolver.readPlan(table);
if (plan.columns().isEmpty()) {
throw new SpectrumSqlException("0A000", "Glue table \"" + binding.schemaName() + "." + table.getName() + "\" declares no columns");
}
return plan;
}
private static String columnDefinitions(GlueTableResolver.ReadPlan plan) {
return plan.columns().stream().map(column -> quote(column.getName()) + " " + GlueTypeMapper.toPostgres(column.getType()))
.collect(Collectors.joining(", "));
}
/**
* Matches the rows a partition loaded: its key columns hold the partition values cast to the column types,
* with the Hive default partition and a value wider than its column as NULL, as {@link #readSelect} projects them.
*/
private static String partitionCondition(Table table, List<String> values) {
List<Column> keys = table.getPartitionKeys();
List<String> terms = new ArrayList<>();
for (int index = 0; index < keys.size(); index++) {
Column key = keys.get(index);
String value = partitionValue(key, values, index);
terms.add(value == null ? quote(key.getName()) + " IS NULL"
: quote(key.getName()) + " = CAST('" + value.replace("'", "''") + "' AS "
+ GlueTypeMapper.toPostgres(key.getType()) + ")");
}
return String.join(" AND ", terms);
}
/** A partition key value as it is loaded: null when it is missing, the Hive default partition or too wide. */
private static String partitionValue(Column key, List<String> values, int index) {
String value = index < values.size() ? values.get(index) : null;
if (value == null || HIVE_DEFAULT_PARTITION.equals(value) || GlueTypeMapper.exceedsWidth(key.getType(), value)) {
return null;
}
return value;
}
/** Whether two partitions hold key values that PostgreSQL casts to the same value, or may do so. */
static boolean hasOverlappingPartitions(Table table, List<Partition> partitions) {
Set<List<String>> seen = new HashSet<>();
for (Partition partition : partitions) {
List<String> canonical = canonicalPartitionValues(table, partition.getValues());
if (canonical == null || !seen.add(canonical)) {
return true;
}
}
return false;
}
/**
* The key values as PostgreSQL holds them after the cast to the column types, or null when a value cannot be
* reduced with confidence, which counts as an overlap so that the table is read whole.
*/
private static List<String> canonicalPartitionValues(Table table, List<String> values) {
List<Column> keys = table.getPartitionKeys();
List<String> canonical = new ArrayList<>();
for (int index = 0; index < keys.size(); index++) {
Column key = keys.get(index);
String value = partitionValue(key, values, index);
String converted = value == null ? NULL_KEY
: canonicalKeyValue(GlueTypeMapper.canonicalGlueType(key.getType()), value);
if (converted == null) {
return null;
}
canonical.add(converted);
}
return canonical;
}
private static String canonicalKeyValue(String type, String value) {
String trimmed = value.trim();
try {
if (INTEGER_TYPES.contains(type)) {
return new BigInteger(trimmed).toString();
}
if (type.startsWith("decimal")) {
BigDecimal number = new BigDecimal(trimmed);
Matcher scale = DECIMAL_SCALE.matcher(type);
if (scale.find()) {
number = number.setScale(Integer.parseInt(scale.group(1)), RoundingMode.HALF_UP);
}
return number.signum() == 0 ? "0" : number.stripTrailingZeros().toPlainString();
}
if (type.equals("float") || type.equals("real") || type.equals("double")) {
// the narrowest float makes the most values equal, so it finds every overlap of the wider ones
return Float.toString(Float.parseFloat(trimmed));
}
return switch (type) {
case "boolean" -> booleanKey(trimmed);
case "date" -> LocalDate.parse(trimmed).toString();
case "timestamp" -> LocalDateTime.parse(trimmed.replace(' ', 'T')).truncatedTo(ChronoUnit.MICROS).toString();
default -> type.startsWith("char") ? value.stripTrailing() : value;
};
} catch (NumberFormatException | DateTimeParseException unparseable) {
LOG.debugv("Partition key value {0} of type {1} is not reduced, so the table is read whole", value, type);
return null;
}
}
/** PostgreSQL reads any unique prefix of true, false, yes, no, on and off, and 1 and 0. */
private static String booleanKey(String value) {
String lower = value.toLowerCase(Locale.ROOT);
if (lower.isEmpty()) {
return null;
}
if (lower.equals("1") || "true".startsWith(lower) || "yes".startsWith(lower) || lower.equals("on")) {
return "true";
}
if (lower.equals("0") || "false".startsWith(lower) || "no".startsWith(lower) || lower.equals("of")
|| lower.equals("off")) {
return "false";
}
return null;
}
private void prepareScratchBucket(String accountId) {
RequestScopes.runAs(accountId, () -> {
ensureScratchBucket();
@@ -930,12 +1180,9 @@ public class ExternalTableMaterializer {
List<String> values = source.partition().getValues();
for (int index = 0; index < partitionKeys.size(); index++) {
Column key = partitionKeys.get(index);
String value = index < values.size() ? values.get(index) : null;
if (value != null && GlueTypeMapper.exceedsWidth(key.getType(), value)) {
// a data column wider than its width is NULL, so a partition value is as well
value = null;
}
String expression = value == null || "__HIVE_DEFAULT_PARTITION__".equals(value)
// a data column wider than its width is NULL, so a partition value is as well
String value = partitionValue(key, values, index);
String expression = value == null
? "CAST(NULL AS VARCHAR)"
: "CAST('" + value.replace("'", "''") + "' AS VARCHAR)";
parts.add("COALESCE(" + expression + ", '\\N') AS " + quote(key.getName()));
@@ -0,0 +1,746 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import io.github.hectorvent.floci.services.glue.model.Column;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
/**
* Works out, from the text of a query, which partitions of an external table the query can touch.
*
* <p>Spectrum reads only the partitions whose key values satisfy the partition predicates of the
* {@code WHERE} clause. This class reads those predicates and nothing else: the original SQL still runs
* against the loaded rows, so a partition kept here costs time and a partition dropped wrongly would lose
* rows. It therefore drops a partition only when a predicate it fully understands rules it out, and keeps
* every partition otherwise.
*
* <p>A predicate counts when it is a top-level {@code AND} term of the {@code WHERE} of the query block that
* names the table, built only from the table's partition keys, literals, comparisons, {@code IN},
* {@code BETWEEN}, {@code IS [NOT] NULL}, {@code AND}, {@code OR} and {@code NOT}, over integer, date and
* string keys, and it rejects a row whose keys are all NULL. The last rule keeps the predicate valid when the
* table is on the nullable side of an outer join, where an unmatched row has NULL keys.
*/
final class PartitionPruner {
private static final String HIVE_DEFAULT_PARTITION = "__HIVE_DEFAULT_PARTITION__";
private static final Set<String> SEGMENT_BOUNDARIES = Set.of("union", "intersect", "except");
private static final Set<String> CLAUSE_AFTER_WHERE = Set.of("group", "order", "having", "limit", "offset",
"fetch", "window", "qualify", "for", "returning");
private static final Set<String> NOT_AN_ALIAS = Set.of("where", "join", "inner", "left", "right", "full",
"cross", "natural", "on", "using", "group", "order", "having", "limit", "offset", "union", "intersect",
"except", "window", "fetch", "for", "lateral", "tablesample", "qualify", "returning", "set", "values",
"select", "from", "as");
private PartitionPruner() {
}
/** The partitions of one table that a query can touch. */
static final class Filter {
private final List<Column> keys;
private final List<List<Node>> occurrences;
private Filter(List<Column> keys, List<List<Node>> occurrences) {
this.keys = keys;
this.occurrences = occurrences;
}
/** Whether a partition with these key values can hold rows the query reads. */
boolean matches(List<String> values) {
Row row = new Row(keys, values);
for (List<Node> conjuncts : occurrences) {
boolean all = true;
for (Node conjunct : conjuncts) {
try {
if (conjunct.eval(row) != Tri.TRUE) {
all = false;
break;
}
} catch (Undecidable expected) {
// a key value this class cannot read stays in, as if the predicate did not exist
}
}
if (all) {
return true;
}
}
return false;
}
}
/**
* The filter for {@code schema.table} in {@code sql}, or empty when every partition may be read: the
* table has no usable predicate in some place it is named, or the text is not understood.
*/
static Optional<Filter> filterFor(String sql, String schema, String table, List<Column> partitionKeys) {
if (sql == null || partitionKeys == null || partitionKeys.isEmpty()) {
return Optional.empty();
}
Tokens tokens = tokenize(sql);
if (tokens.unsafe || !tokens.balanced()) {
return Optional.empty();
}
List<List<Node>> occurrences = new ArrayList<>();
int found = 0;
for (int i = 0; i < tokens.list.size(); i++) {
Chain chain = chainAt(tokens, i);
if (chain == null) {
continue;
}
if (isTable(chain, schema, table)) {
found++;
List<Node> conjuncts = conjunctsFor(tokens, chain, schema, table, partitionKeys);
if (conjuncts.isEmpty()) {
return Optional.empty();
}
occurrences.add(conjuncts);
}
i = chain.end - 1;
}
return found == 0 ? Optional.empty() : Optional.of(new Filter(partitionKeys, occurrences));
}
private static List<Node> conjunctsFor(Tokens tokens, Chain occurrence, String schema, String table,
List<Column> keys) {
int depth = tokens.depth[occurrence.start];
int blockStart = 0;
for (int j = occurrence.start - 1; j >= 0; j--) {
if (tokens.depth[j] < depth || tokens.depth[j] == depth && isBoundary(tokens.list.get(j))) {
blockStart = j + 1;
break;
}
}
int blockEnd = tokens.list.size();
for (int j = occurrence.end; j < tokens.list.size(); j++) {
if (tokens.depth[j] < depth || tokens.depth[j] == depth && isBoundary(tokens.list.get(j))) {
blockEnd = j;
break;
}
}
int where = -1;
for (int j = blockStart; j < blockEnd; j++) {
if (tokens.depth[j] == depth && tokens.list.get(j).isWord("where")) {
where = j;
break;
}
}
if (where < occurrence.end) {
return List.of();
}
int clauseEnd = blockEnd;
int caseLevel = 0;
for (int j = where + 1; j < blockEnd; j++) {
if (tokens.depth[j] == depth) {
Token token = tokens.list.get(j);
if (token.isWord("case")) {
caseLevel++;
} else if (token.isWord("end")) {
caseLevel = Math.max(0, caseLevel - 1);
} else if (caseLevel == 0 && CLAUSE_AFTER_WHERE.stream().anyMatch(token::isWord)) {
clauseEnd = j;
break;
}
}
}
Set<List<String>> qualifiers = qualifiers(tokens, occurrence, schema, table);
if (qualifiers == null) {
return List.of();
}
List<Node> conjuncts = new ArrayList<>();
for (List<Token> conjunct : split(tokens.list.subList(where + 1, clauseEnd))) {
Node node = parseConjunct(conjunct, keys, qualifiers);
if (node != null && rejectsNullKeys(node, keys)) {
conjuncts.add(node);
}
}
return conjuncts;
}
private static boolean rejectsNullKeys(Node node, List<Column> keys) {
List<String> nulls = new ArrayList<>();
for (int i = 0; i < keys.size(); i++) {
nulls.add(null);
}
try {
return node.eval(new Row(keys, nulls)) != Tri.TRUE;
} catch (Undecidable expected) {
// an all-NULL row always evaluates, so this is only a defence: a predicate that cannot be checked is not used
return false;
}
}
/**
* The qualifiers a column of this table may carry in the block, each as the words before the column name:
* the alias when the table is aliased, else the table name, with its schema and with its database too.
* Null when the alias cannot be read, which leaves only unqualified columns in the predicate.
*/
private static Set<List<String>> qualifiers(Tokens tokens, Chain occurrence, String schema, String table) {
int next = occurrence.end;
String alias = null;
if (next < tokens.list.size() && tokens.list.get(next).isWord("as")) {
next++;
}
if (next < tokens.list.size()) {
Token candidate = tokens.list.get(next);
boolean named = candidate.kind == Kind.QUOTED_WORD
|| candidate.kind == Kind.WORD && !NOT_AN_ALIAS.contains(candidate.text);
if (named) {
alias = candidate.text;
if (next + 1 < tokens.list.size() && tokens.list.get(next + 1).kind == Kind.LPAREN) {
return null;
}
}
}
if (alias != null) {
return Set.of(List.of(alias));
}
Set<List<String>> names = new HashSet<>();
names.add(List.of(table));
names.add(List.of(schema, table));
if (occurrence.words.size() == 3) {
names.add(occurrence.words.stream().map(Token::text).toList());
}
return names;
}
private static boolean isBoundary(Token token) {
return token.kind == Kind.SEMICOLON || token.kind == Kind.WORD && SEGMENT_BOUNDARIES.contains(token.text);
}
/** Splits the terms of a {@code WHERE}; a clause holding a top-level OR is a single term. */
private static List<List<Token>> split(List<Token> clause) {
int depth = 0;
int caseDepth = 0;
for (Token token : clause) {
if (token.kind == Kind.LPAREN) {
depth++;
} else if (token.kind == Kind.RPAREN) {
depth--;
} else if (token.isWord("case")) {
caseDepth++;
} else if (token.isWord("end")) {
caseDepth = Math.max(0, caseDepth - 1);
} else if (depth == 0 && caseDepth == 0 && token.isWord("or")) {
return List.of(clause);
}
}
if (caseDepth != 0) {
return List.of();
}
List<List<Token>> terms = new ArrayList<>();
List<Token> current = new ArrayList<>();
depth = 0;
caseDepth = 0;
boolean inBetween = false;
for (Token token : clause) {
if (token.kind == Kind.LPAREN) {
depth++;
} else if (token.kind == Kind.RPAREN) {
depth--;
} else if (token.isWord("case")) {
caseDepth++;
} else if (token.isWord("end")) {
caseDepth = Math.max(0, caseDepth - 1);
}
if (depth == 0 && caseDepth == 0 && token.isWord("between")) {
inBetween = true;
}
if (depth == 0 && caseDepth == 0 && token.isWord("and")) {
if (inBetween) {
inBetween = false;
} else {
terms.add(current);
current = new ArrayList<>();
continue;
}
}
current.add(token);
}
terms.add(current);
return terms;
}
// ---- predicate parsing and evaluation ----
private enum Tri { TRUE, FALSE, UNKNOWN;
Tri not() {
return this == TRUE ? FALSE : this == FALSE ? TRUE : UNKNOWN;
}
}
/** A key value that cannot be compared the way PostgreSQL would compare it. */
private static final class Undecidable extends RuntimeException {
Undecidable() {
super(null, null, false, false);
}
}
/** A term this class does not support. */
private static final class Unsupported extends RuntimeException {
Unsupported() {
super(null, null, false, false);
}
}
private record Row(List<Column> keys, List<String> values) {
String value(int index) {
String value = index < values.size() ? values.get(index) : null;
if (value == null || HIVE_DEFAULT_PARTITION.equals(value)
|| GlueTypeMapper.exceedsWidth(keys.get(index).getType(), value)) {
return null;
}
return value;
}
}
private interface Node {
Tri eval(Row row);
}
private enum KeyType { INTEGER, DATE, STRING }
private static KeyType keyType(Column key) {
String type = GlueTypeMapper.canonicalGlueType(key.getType());
return switch (type) {
case "tinyint", "smallint", "int", "integer", "bigint" -> KeyType.INTEGER;
case "date" -> KeyType.DATE;
case "string" -> KeyType.STRING;
default -> type.matches("(?:varchar|char)\\(\\d+\\)") ? KeyType.STRING : null;
};
}
private static Node parseConjunct(List<Token> tokens, List<Column> keys, Set<List<String>> qualifiers) {
try {
Parser parser = new Parser(tokens, keys, qualifiers);
Node node = parser.expression();
return parser.atEnd() ? node : null;
} catch (Unsupported expected) {
return null;
}
}
private static final class Parser {
private final List<Token> tokens;
private final List<Column> keys;
private final Set<List<String>> qualifiers;
private int position;
Parser(List<Token> tokens, List<Column> keys, Set<List<String>> qualifiers) {
this.tokens = tokens;
this.keys = keys;
this.qualifiers = qualifiers;
}
boolean atEnd() {
return position == tokens.size();
}
Node expression() {
Node left = conjunction();
while (word("or")) {
position++;
Node a = left;
Node b = conjunction();
left = row -> {
Tri x = a.eval(row);
Tri y = b.eval(row);
return x == Tri.TRUE || y == Tri.TRUE ? Tri.TRUE
: x == Tri.FALSE && y == Tri.FALSE ? Tri.FALSE : Tri.UNKNOWN;
};
}
return left;
}
private Node conjunction() {
Node left = negation();
while (word("and")) {
position++;
Node a = left;
Node b = negation();
left = row -> {
Tri x = a.eval(row);
Tri y = b.eval(row);
return x == Tri.FALSE || y == Tri.FALSE ? Tri.FALSE
: x == Tri.TRUE && y == Tri.TRUE ? Tri.TRUE : Tri.UNKNOWN;
};
}
return left;
}
private Node negation() {
if (word("not")) {
position++;
Node inner = negation();
return row -> inner.eval(row).not();
}
return predicate();
}
private Node predicate() {
if (peekKind(Kind.LPAREN)) {
position++;
Node inner = expression();
expect(Kind.RPAREN);
return inner;
}
Operand left = operand();
if (word("is")) {
position++;
boolean negated = word("not");
if (negated) {
position++;
}
if (!word("null") || left.key < 0) {
throw new Unsupported();
}
position++;
int index = left.key;
return row -> (row.value(index) == null) != negated ? Tri.TRUE : Tri.FALSE;
}
boolean negated = word("not");
if (negated) {
position++;
}
if (word("in")) {
position++;
return negate(inList(left), negated);
}
if (word("between")) {
position++;
Operand low = operand();
if (!word("and")) {
throw new Unsupported();
}
position++;
Operand high = operand();
Node ge = comparison(left, ">=", low);
Node le = comparison(left, "<=", high);
Node both = row -> {
Tri x = ge.eval(row);
Tri y = le.eval(row);
return x == Tri.FALSE || y == Tri.FALSE ? Tri.FALSE
: x == Tri.TRUE && y == Tri.TRUE ? Tri.TRUE : Tri.UNKNOWN;
};
return negate(both, negated);
}
if (negated || !peekKind(Kind.OP)) {
throw new Unsupported();
}
String operator = tokens.get(position++).text;
return comparison(left, operator, operand());
}
private static Node negate(Node node, boolean negated) {
return negated ? row -> node.eval(row).not() : node;
}
private Node inList(Operand left) {
expect(Kind.LPAREN);
List<Node> equalities = new ArrayList<>();
do {
equalities.add(comparison(left, "=", operand()));
if (peekKind(Kind.COMMA)) {
position++;
} else {
break;
}
} while (true);
expect(Kind.RPAREN);
return row -> {
boolean unknown = false;
for (Node equality : equalities) {
Tri result = equality.eval(row);
if (result == Tri.TRUE) {
return Tri.TRUE;
}
unknown |= result == Tri.UNKNOWN;
}
return unknown ? Tri.UNKNOWN : Tri.FALSE;
};
}
private Node comparison(Operand left, String operator, Operand right) {
Operand key = left;
Operand literal = right;
String effective = operator;
if (left.key < 0 && right.key >= 0) {
key = right;
literal = left;
effective = switch (operator) {
case "<" -> ">";
case ">" -> "<";
case "<=" -> ">=";
case ">=" -> "<=";
default -> operator;
};
}
if (key.key < 0 || literal.key >= 0 || literal.literal == null) {
throw new Unsupported();
}
KeyType type = keyType(keys.get(key.key));
if (type == null) {
throw new Unsupported();
}
String op = switch (effective) {
case "=", "<>", "!=", "<", ">", "<=", ">=" -> effective.equals("!=") ? "<>" : effective;
default -> throw new Unsupported();
};
int index = key.key;
return switch (type) {
case INTEGER -> {
BigInteger bound = integerLiteral(literal.literal);
yield row -> compare(row.value(index), op, value -> new BigInteger(value.trim()).compareTo(bound));
}
case DATE -> {
LocalDate bound = dateLiteral(literal.literal);
yield row -> compare(row.value(index), op, value -> parseDate(value).compareTo(bound));
}
case STRING -> {
if (!"=".equals(op) && !"<>".equals(op) || !literal.literal.quoted) {
throw new Unsupported();
}
String bound = literal.literal.text;
yield row -> compare(row.value(index), op, value -> value.equals(bound) ? 0 : 1);
}
};
}
private interface Comparer {
int compareTo(String value);
}
private static Tri compare(String value, String op, Comparer comparer) {
if (value == null) {
return Tri.UNKNOWN;
}
int order;
try {
order = comparer.compareTo(value);
} catch (NumberFormatException | DateTimeParseException ignored) {
throw new Undecidable();
}
boolean result = switch (op) {
case "=" -> order == 0;
case "<>" -> order != 0;
case "<" -> order < 0;
case ">" -> order > 0;
case "<=" -> order <= 0;
default -> order >= 0;
};
return result ? Tri.TRUE : Tri.FALSE;
}
private static LocalDate parseDate(String value) {
return LocalDate.parse(value.trim());
}
private static BigInteger integerLiteral(Token literal) {
try {
return new BigInteger(literal.text.trim());
} catch (NumberFormatException expected) {
throw new Unsupported();
}
}
private static LocalDate dateLiteral(Token literal) {
if (!literal.quoted) {
throw new Unsupported();
}
try {
return parseDate(literal.text);
} catch (DateTimeParseException expected) {
throw new Unsupported();
}
}
private record Operand(int key, Token literal) { }
private Operand operand() {
if (position >= tokens.size()) {
throw new Unsupported();
}
Token token = tokens.get(position);
if (token.kind == Kind.STRING) {
position++;
return new Operand(-1, new Token(Kind.STRING, token.text, true));
}
boolean negative = token.kind == Kind.OP && "-".equals(token.text);
if (negative || token.kind == Kind.OP && "+".equals(token.text)) {
position++;
if (position >= tokens.size() || tokens.get(position).kind != Kind.NUMBER) {
throw new Unsupported();
}
Token number = tokens.get(position++);
return new Operand(-1, new Token(Kind.NUMBER, (negative ? "-" : "") + number.text, false));
}
if (token.kind == Kind.NUMBER) {
position++;
return new Operand(-1, new Token(Kind.NUMBER, token.text, false));
}
return new Operand(keyReference(), null);
}
private int keyReference() {
List<Token> words = new ArrayList<>();
while (position < tokens.size() && (tokens.get(position).kind == Kind.WORD
|| tokens.get(position).kind == Kind.QUOTED_WORD)) {
words.add(tokens.get(position++));
if (position < tokens.size() && tokens.get(position).kind == Kind.OP
&& ".".equals(tokens.get(position).text)) {
position++;
} else {
break;
}
}
if (words.isEmpty()) {
throw new Unsupported();
}
Token name = words.getLast();
List<String> qualifier = words.subList(0, words.size() - 1).stream().map(Token::text).toList();
if (!qualifier.isEmpty() && !qualifiers.contains(qualifier)) {
throw new Unsupported();
}
for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i).getName();
boolean same = name.kind == Kind.QUOTED_WORD ? name.text.equals(key) : name.text.equalsIgnoreCase(key);
if (same) {
return i;
}
}
throw new Unsupported();
}
private boolean word(String text) {
return position < tokens.size() && tokens.get(position).isWord(text);
}
private boolean peekKind(Kind kind) {
return position < tokens.size() && tokens.get(position).kind == kind;
}
private void expect(Kind kind) {
if (!peekKind(kind)) {
throw new Unsupported();
}
position++;
}
}
// ---- tokenizer ----
private enum Kind { WORD, QUOTED_WORD, STRING, NUMBER, OP, LPAREN, RPAREN, COMMA, SEMICOLON, OTHER }
private record Token(Kind kind, String text, boolean quoted) {
Token(Kind kind, String text) {
this(kind, text, kind == Kind.STRING);
}
boolean isWord(String word) {
return kind == Kind.WORD && text.equals(word);
}
}
private static final class Tokens {
final List<Token> list;
int[] depth;
final boolean unsafe;
Tokens(List<Token> list, boolean unsafe) {
this.list = list;
this.unsafe = unsafe;
}
boolean balanced() {
depth = new int[list.size()];
int level = 0;
int caseCount = 0;
for (int i = 0; i < list.size(); i++) {
Token token = list.get(i);
Kind kind = token.kind;
if (kind == Kind.RPAREN) {
level--;
if (level < 0) {
return false;
}
}
depth[i] = level;
if (kind == Kind.LPAREN) {
level++;
}
if (token.isWord("case")) {
caseCount++;
} else if (token.isWord("end")) {
caseCount--;
if (caseCount < 0) {
return false;
}
}
if (kind == Kind.SEMICOLON) {
if (level != 0 || caseCount != 0) {
return false;
}
}
}
return level == 0 && caseCount == 0;
}
}
private record Chain(int start, int end, List<Token> words) { }
private static Chain chainAt(Tokens tokens, int index) {
Token first = tokens.list.get(index);
if (first.kind != Kind.WORD && first.kind != Kind.QUOTED_WORD) {
return null;
}
if (index > 0 && tokens.list.get(index - 1).kind == Kind.OP && ".".equals(tokens.list.get(index - 1).text)) {
return null;
}
List<Token> words = new ArrayList<>();
int i = index;
while (i < tokens.list.size() && (tokens.list.get(i).kind == Kind.WORD
|| tokens.list.get(i).kind == Kind.QUOTED_WORD)) {
words.add(tokens.list.get(i++));
if (i + 1 < tokens.list.size() && tokens.list.get(i).kind == Kind.OP && ".".equals(tokens.list.get(i).text)
&& (tokens.list.get(i + 1).kind == Kind.WORD || tokens.list.get(i + 1).kind == Kind.QUOTED_WORD)) {
i++;
} else {
break;
}
}
return new Chain(index, i, words);
}
/** A name exactly as the scanner reads a table: {@code schema.table} or {@code database.schema.table}. */
private static boolean isTable(Chain chain, String schema, String table) {
List<Token> words = chain.words;
if (words.size() == 2) {
return words.get(0).text.equals(schema) && words.get(1).text.equals(table);
}
return words.size() == 3 && words.get(1).text.equals(schema) && words.get(2).text.equals(table);
}
private static Tokens tokenize(String sql) {
SpectrumSqlLexer.Result result = SpectrumSqlLexer.tokenize(sql);
List<Token> list = new ArrayList<>(result.tokens().size());
for (SpectrumSqlLexer.Token t : result.tokens()) {
Kind kind = switch (t.kind()) {
case WORD -> Kind.WORD;
case QUOTED_WORD -> Kind.QUOTED_WORD;
case STRING -> Kind.STRING;
case NUMBER -> Kind.NUMBER;
case OP -> Kind.OP;
case LPAREN -> Kind.LPAREN;
case RPAREN -> Kind.RPAREN;
case COMMA -> Kind.COMMA;
case SEMICOLON -> Kind.SEMICOLON;
case DOLLAR_QUOTED, OTHER -> Kind.OTHER;
};
list.add(new Token(kind, t.text(), t.quoted()));
}
return new Tokens(list, result.unsafe());
}
}
@@ -138,7 +138,7 @@ public class SpectrumQueryPreparation {
try (ExternalCatalogLocks.Guard ignored = catalogLocks.read(binding,
session.inTransaction() || !backend.permitsCachePublication())) {
requireCurrentBinding(session, binding);
ExternalTableMaterializer.Outcome outcome = materializer.ensureCurrent(backend, session, binding, reference.table());
ExternalTableMaterializer.Outcome outcome = materializer.ensureCurrent(backend, session, binding, reference.table(), sql);
if (outcome == ExternalTableMaterializer.Outcome.NOT_EXTERNAL) {
throw new SpectrumSqlException("42P01", "external relation \"" + reference.schema()
+ "." + reference.table() + "\" does not exist");
@@ -0,0 +1,219 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Tokenizes SQL for Spectrum analysis (reference scanning and partition pruning).
*
* <p>Handles comments, quoted identifiers, string literals, and dollar-quoted blocks.
*/
final class SpectrumSqlLexer {
enum Kind {
WORD,
QUOTED_WORD,
STRING,
NUMBER,
DOLLAR_QUOTED,
LPAREN,
RPAREN,
COMMA,
SEMICOLON,
OP,
OTHER
}
record Token(Kind kind, String text, boolean quoted) {
Token(Kind kind, String text) {
this(kind, text, kind == Kind.QUOTED_WORD || kind == Kind.STRING);
}
boolean isWord(String word) {
return kind == Kind.WORD && text.equals(word);
}
}
record Result(List<Token> tokens, boolean unsafe) {
}
private SpectrumSqlLexer() {
}
static Result tokenize(String sql) {
if (sql == null || sql.isEmpty()) {
return new Result(List.of(), false);
}
List<Token> tokens = new ArrayList<>();
boolean unsafe = false;
int i = 0;
while (i < sql.length()) {
char c = sql.charAt(i);
if (Character.isWhitespace(c)) {
i++;
} else if (c == '-' && i + 1 < sql.length() && sql.charAt(i + 1) == '-') {
int newline = sql.indexOf('\n', i + 2);
i = newline < 0 ? sql.length() : newline + 1;
} else if (c == '/' && i + 1 < sql.length() && sql.charAt(i + 1) == '*') {
int depth = 1;
i += 2;
while (i < sql.length() && depth > 0) {
if (sql.startsWith("/*", i)) {
depth++;
i += 2;
} else if (sql.startsWith("*/", i)) {
depth--;
i += 2;
} else {
i++;
}
}
if (depth > 0) {
unsafe = true;
}
} else if (c == '$' && dollarTagEnd(sql, i) > 0) {
int start = i;
int bodyStart = dollarTagEnd(sql, i);
String tag = sql.substring(start, bodyStart);
int close = sql.indexOf(tag, bodyStart);
if (close < 0) {
unsafe = true;
i = sql.length();
} else {
int end = close + tag.length();
tokens.add(new Token(Kind.DOLLAR_QUOTED, sql.substring(start, end)));
unsafe = true;
i = end;
}
} else if (c == '"') {
StringBuilder value = new StringBuilder();
i++;
boolean closed = false;
while (i < sql.length()) {
char ch = sql.charAt(i);
if (ch == '"') {
if (i + 1 < sql.length() && sql.charAt(i + 1) == '"') {
value.append('"');
i += 2;
continue;
}
i++;
closed = true;
break;
}
value.append(ch);
i++;
}
if (!closed) {
unsafe = true;
}
tokens.add(new Token(Kind.QUOTED_WORD, value.toString()));
} else if (c == '\'') {
boolean backslashEscapes = isEscapeStringPrefix(sql, i);
StringBuilder value = new StringBuilder();
i++;
boolean closed = false;
while (i < sql.length()) {
char ch = sql.charAt(i);
if (backslashEscapes && ch == '\\' && i + 1 < sql.length()) {
value.append(sql.charAt(i + 1));
i += 2;
} else if (ch == '\'') {
if (i + 1 < sql.length() && sql.charAt(i + 1) == '\'') {
value.append('\'');
i += 2;
continue;
}
i++;
closed = true;
break;
} else {
value.append(ch);
i++;
}
}
if (!closed) {
unsafe = true;
}
tokens.add(new Token(Kind.STRING, value.toString()));
} else if (Character.isLetter(c) || c == '_') {
int start = i;
while (i < sql.length() && (Character.isLetterOrDigit(sql.charAt(i)) || sql.charAt(i) == '_'
|| sql.charAt(i) == '$')) {
i++;
}
String word = sql.substring(start, i);
if (i < sql.length() && (sql.charAt(i) == '\'' || sql.charAt(i) == '&' && i + 1 < sql.length()
&& sql.charAt(i + 1) == '\'')) {
unsafe = true;
}
tokens.add(new Token(Kind.WORD, word.toLowerCase(Locale.ROOT)));
} else if (Character.isDigit(c)) {
int start = i;
while (i < sql.length() && Character.isDigit(sql.charAt(i))) {
i++;
}
if (i + 1 < sql.length() && sql.charAt(i) == '.' && Character.isDigit(sql.charAt(i + 1))) {
i++;
while (i < sql.length() && Character.isDigit(sql.charAt(i))) {
i++;
}
}
tokens.add(new Token(Kind.NUMBER, sql.substring(start, i)));
} else if (c == '$') {
int start = i++;
while (i < sql.length() && Character.isDigit(sql.charAt(i))) {
i++;
}
tokens.add(new Token(Kind.OTHER, sql.substring(start, i)));
} else if (c == '(') {
tokens.add(new Token(Kind.LPAREN, "("));
i++;
} else if (c == ')') {
tokens.add(new Token(Kind.RPAREN, ")"));
i++;
} else if (c == ',') {
tokens.add(new Token(Kind.COMMA, ","));
i++;
} else if (c == ';') {
tokens.add(new Token(Kind.SEMICOLON, ";"));
i++;
} else {
String two = i + 1 < sql.length() ? sql.substring(i, i + 2) : "";
if (two.equals("<=") || two.equals(">=") || two.equals("<>") || two.equals("!=") || two.equals("::")) {
tokens.add(new Token(two.equals("::") ? Kind.OTHER : Kind.OP, two));
i += 2;
} else if ("=<>.+-".indexOf(c) >= 0) {
tokens.add(new Token(Kind.OP, String.valueOf(c)));
i++;
} else {
tokens.add(new Token(Kind.OTHER, String.valueOf(c)));
i++;
}
}
}
return new Result(tokens, unsafe);
}
private static int dollarTagEnd(String sql, int start) {
int i = start + 1;
if (i < sql.length() && (Character.isLetter(sql.charAt(i)) || sql.charAt(i) == '_')) {
while (i < sql.length() && (Character.isLetterOrDigit(sql.charAt(i)) || sql.charAt(i) == '_')) {
i++;
}
}
return i < sql.length() && sql.charAt(i) == '$' ? i + 1 : -1;
}
private static boolean isEscapeStringPrefix(String sql, int quote) {
if (quote == 0 || Character.toLowerCase(sql.charAt(quote - 1)) != 'e') {
return false;
}
if (quote == 1) {
return true;
}
char before = sql.charAt(quote - 2);
return !(Character.isLetterOrDigit(before) || before == '_' || before == '$');
}
}
@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.services.redshift.spectrum.ExternalCatalogRegi
import io.github.hectorvent.floci.services.redshift.spectrum.ExternalStatement;
import io.github.hectorvent.floci.services.redshift.spectrum.ExternalStatementParser;
import io.github.hectorvent.floci.services.redshift.spectrum.GlueTableBuilder;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumCatalog;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.github.hectorvent.floci.testing.SidecarContainersProfile;
@@ -79,6 +80,9 @@ class RedshiftSpectrumIntegrationTest {
@Inject
ExternalCatalogRegistry externalRegistry;
@Inject
SpectrumCatalog spectrumCatalog;
private static final String ROLE_NAME = "SpectrumItRole";
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/" + ROLE_NAME;
private static final String TRUST_POLICY = """
@@ -124,6 +128,9 @@ class RedshiftSpectrumIntegrationTest {
iamService.deleteRolePolicy(ROLE_NAME, "AllowS3");
iamService.deleteRole(ROLE_NAME);
}
if (spectrumCatalog != null) {
spectrumCatalog.clear();
}
}
@Test
@@ -605,6 +612,72 @@ class RedshiftSpectrumIntegrationTest {
}
}
@Test
@Timeout(120)
void readsOnlyThePartitionsTheWhereSelectsAndCompletesTheTableForALaterQuery() throws Exception {
bucket = "spectrum-pruning-" + System.nanoTime();
s3Service.createBucket(bucket, "us-east-1");
s3Service.putObject(bucket, "events/day=1/part-1.csv", "1,10\n2,20\n".getBytes(StandardCharsets.UTF_8),
"text/csv", null);
s3Service.putObject(bucket, "events/day=2/part-1.csv", "not-a-number,30\n".getBytes(StandardCharsets.UTF_8),
"text/csv", null);
glueDatabase = "spectrum_pruning_" + System.nanoTime();
Database database = new Database();
database.setName(glueDatabase);
glueService.createDatabase(database);
clusterId = "it-pruning-" + System.nanoTime();
Cluster cluster = createClusterWithRole(clusterId);
// a partition that cannot be read fails the query that reads it, which shows which partitions were read
String url = "jdbc:postgresql://127.0.0.1:" + cluster.getEndpoint().getPort()
+ "/dev?preferQueryMode=simple&socketTimeout=30";
String schemaName = "pruning_lake";
try (Connection connection = Awaitility.await().atMost(Duration.ofSeconds(30)).pollDelay(Duration.ZERO)
.pollInterval(Duration.ofMillis(500)).ignoreExceptions()
.until(() -> DriverManager.getConnection(url, "admin", "Secret123"), Objects::nonNull);
Statement statement = connection.createStatement()) {
statement.execute("CREATE EXTERNAL SCHEMA " + schemaName + " FROM DATA CATALOG DATABASE '" + glueDatabase
+ "' IAM_ROLE '" + ROLE_ARN + "'");
statement.execute("CREATE EXTERNAL TABLE " + schemaName + ".events (id INTEGER, amount INTEGER) "
+ "PARTITIONED BY (day INTEGER) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' "
+ "STORED AS TEXTFILE LOCATION 's3://" + bucket + "/events/'");
statement.execute("ALTER TABLE " + schemaName + ".events ADD "
+ "PARTITION (day='1') LOCATION 's3://" + bucket + "/events/day=1/' "
+ "PARTITION (day='2') LOCATION 's3://" + bucket + "/events/day=2/'");
try (ResultSet rows = statement.executeQuery(
"SELECT SUM(amount) FROM " + schemaName + ".events WHERE day = 1")) {
assertTrue(rows.next());
assertEquals(30, rows.getLong(1));
}
SQLException unreadable = assertThrows(SQLException.class,
() -> statement.executeQuery("SELECT SUM(amount) FROM " + schemaName + ".events"));
assertEquals("22P02", unreadable.getSQLState());
s3Service.putObject(bucket, "events/day=2/part-1.csv", "3,40\n".getBytes(StandardCharsets.UTF_8),
"text/csv", null);
try (ResultSet rows = statement.executeQuery(
"SELECT day, SUM(amount) FROM " + schemaName + ".events GROUP BY day ORDER BY day")) {
assertTrue(rows.next());
assertEquals(1, rows.getInt(1));
assertEquals(30, rows.getLong(2));
assertTrue(rows.next());
assertEquals(2, rows.getInt(1));
assertEquals(40, rows.getLong(2));
assertFalse(rows.next());
}
try (ResultSet rows = statement.executeQuery(
"SELECT COUNT(*) FROM " + schemaName + ".events WHERE day = 1")) {
assertTrue(rows.next());
assertEquals(2, rows.getLong(1));
}
statement.execute("DROP SCHEMA IF EXISTS " + schemaName + " CASCADE");
} finally {
s3Service.deleteObject(bucket, "events/day=1/part-1.csv");
s3Service.deleteObject(bucket, "events/day=2/part-1.csv");
}
}
private static void assertTotal(Statement statement, long total) throws SQLException {
try (ResultSet rows = statement.executeQuery("SELECT COALESCE(SUM(amount),0) FROM lake.events")) {
assertTrue(rows.next());
@@ -14,6 +14,15 @@ import static org.hamcrest.Matchers.equalTo;
class ExternalReferenceScannerTest {
private static final Set<String> SCHEMAS = Set.of("analytics", "Mixed");
@Test
void aStringThatLooksLikePunctuationDoesNotEndTheTableContext() {
for (String text : new String[] {";", "(", ")", ","}) {
assertThat(text, ExternalReferenceScanner.scan(
"SELECT e.id FROM (SELECT '" + text + "') s, analytics.events e", SCHEMAS),
contains(new Reference("analytics", "events")));
}
}
@Test
void findsQualifiedReferencesAndIgnoresOtherSchemas() {
assertThat(ExternalReferenceScanner.scan("SELECT * FROM analytics.events e JOIN public.users u ON true", SCHEMAS),
@@ -183,4 +192,19 @@ class ExternalReferenceScannerTest {
assertThat(ExternalReferenceScanner.scan("SELECT EXTRACT(year FROM ts) FROM analytics.events", SCHEMAS),
contains(new Reference("analytics", "events")));
}
@Test
void findsReferencesPastNestedBlockComments() {
assertThat(ExternalReferenceScanner.scan(
"SELECT * FROM /* outer /* nested */ */ analytics.events", SCHEMAS),
contains(new Reference("analytics", "events")));
}
@Test
void ignoresReferencesInsideDollarQuotesWithCustomTag() {
assertThat(ExternalReferenceScanner.scan("SELECT $sql$ FROM analytics.events $sql$", SCHEMAS), empty());
assertThat(ExternalReferenceScanner.scan(
"SELECT $sql$ FROM analytics.events $sql$ FROM analytics.events", SCHEMAS),
contains(new Reference("analytics", "events")));
}
}
@@ -56,6 +56,7 @@ import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -1106,6 +1107,258 @@ class ExternalTableMaterializerTest {
verify(duck, never()).query(anyString(), any(), anyString(), anyString(), any());
}
private static final String DAY_ONE_SQL = "SELECT * FROM analytics.events WHERE day = '2026-01-01'";
private static final String DAY_TWO_SQL = "SELECT * FROM analytics.events WHERE day = '2026-01-02'";
private Table dayPartitionedTable() {
Table table = csvTable();
table.setPartitionKeys(List.of(new Column("day", "string")));
when(glue.getTable("lake", "events")).thenReturn(table);
return table;
}
private Partition dayPartition(Table table, String day, String prefix, String etag) {
StorageDescriptor descriptor = new StorageDescriptor();
descriptor.setLocation("s3://bucket/" + prefix);
descriptor.setInputFormat("org.apache.hadoop.mapred.TextInputFormat");
descriptor.setColumns(table.getStorageDescriptor().getColumns());
Partition partition = new Partition();
partition.setValues(List.of(day));
partition.setStorageDescriptor(descriptor);
when(s3.listObjectsWithPrefixes(eq("bucket"), eq(prefix), eq(""), eq(1000), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(
List.of(new S3Object("bucket", prefix + "part-1.csv", new byte[]{1}, "text/csv", etag)),
List.of(), false, null));
return partition;
}
@Test
void loadsOnlyThePartitionsTheWhereCanSelect() {
Table table = dayPartitionedTable();
Partition one = dayPartition(table, "2026-01-01", "one/", "e1");
Partition two = dayPartition(table, "2026-01-02", "two/", "e2");
when(glue.getPartitions("lake", "events")).thenReturn(List.of(one, two));
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events", DAY_TWO_SQL),
equalTo(ExternalTableMaterializer.Outcome.LOADED));
verify(duck).execute(argThat(sql -> sql.contains("s3://bucket/two/part-1.csv")
&& !sql.contains("s3://bucket/one/")), any(), anyString(), eq(ACCOUNT));
verify(s3, never()).listObjectsWithPrefixes(eq("bucket"), eq("one/"), any(), anyInt(), any(), any());
}
@Test
void addsAPartitionAnotherQueryNeedsWithoutRemovingTheOnesAlreadyLoaded() {
Table table = dayPartitionedTable();
Partition one = dayPartition(table, "2026-01-01", "one/", "e1");
Partition two = dayPartition(table, "2026-01-02", "two/", "e2");
when(glue.getPartitions("lake", "events")).thenReturn(List.of(one, two));
materializer.ensureCurrent(backend, session(false), BINDING, "events", DAY_ONE_SQL);
int loaded = backend.statements.size();
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events", DAY_TWO_SQL),
equalTo(ExternalTableMaterializer.Outcome.LOADED));
List<String> added = backend.statements.subList(loaded, backend.statements.size());
assertThat(added.stream().noneMatch(sql -> sql.contains("TRUNCATE") || sql.contains("DROP TABLE \"analytics\"")),
equalTo(true));
assertThat(added.stream().anyMatch(sql -> sql.contains("INSERT INTO \"analytics\".\"events\"")), equalTo(true));
assertThat(added.stream().noneMatch(sql -> sql.contains("DELETE FROM")), equalTo(true));
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events", null),
equalTo(ExternalTableMaterializer.Outcome.CURRENT));
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events", DAY_ONE_SQL),
equalTo(ExternalTableMaterializer.Outcome.CURRENT));
}
@Test
void replacesOnlyAPartitionWhoseObjectsChanged() {
Table table = dayPartitionedTable();
Partition one = dayPartition(table, "2026-01-01", "one/", "e1");
Partition two = dayPartition(table, "2026-01-02", "two/", "e2");
when(glue.getPartitions("lake", "events")).thenReturn(List.of(one, two));
materializer.ensureCurrent(backend, session(false), BINDING, "events", null);
dayPartition(table, "2026-01-01", "one/", "e1-changed");
int loaded = backend.statements.size();
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events", null),
equalTo(ExternalTableMaterializer.Outcome.LOADED));
List<String> changed = backend.statements.subList(loaded, backend.statements.size());
assertThat(changed.stream().anyMatch(sql -> sql.contains(
"DELETE FROM \"analytics\".\"events\" WHERE (\"day\" = CAST('2026-01-01' AS text))")), equalTo(true));
assertThat(changed.stream().noneMatch(sql -> sql.contains("2026-01-02")), equalTo(true));
verify(duck, times(2)).execute(anyString(), any(), anyString(), eq(ACCOUNT));
}
@Test
void dropsTheRowsOfAPartitionGlueNoLongerHas() {
Table table = dayPartitionedTable();
Partition one = dayPartition(table, "2026-01-01", "one/", "e1");
Partition two = dayPartition(table, "2026-01-02", "two/", "e2");
when(glue.getPartitions("lake", "events")).thenReturn(List.of(one, two));
materializer.ensureCurrent(backend, session(false), BINDING, "events", null);
when(glue.getPartitions("lake", "events")).thenReturn(List.of(one));
int loaded = backend.statements.size();
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events", DAY_ONE_SQL),
equalTo(ExternalTableMaterializer.Outcome.LOADED));
List<String> dropped = backend.statements.subList(loaded, backend.statements.size());
assertThat(dropped.stream().anyMatch(sql -> sql.contains(
"DELETE FROM \"analytics\".\"events\" WHERE (\"day\" = CAST('2026-01-02' AS text))")), equalTo(true));
}
@Test
void matchesTheNullPartitionRowsOfADeletedHiveDefaultPartition() {
Table table = dayPartitionedTable();
Partition defaultPartition = dayPartition(table, "__HIVE_DEFAULT_PARTITION__", "none/", "e0");
Partition one = dayPartition(table, "2026-01-01", "one/", "e1");
when(glue.getPartitions("lake", "events")).thenReturn(List.of(defaultPartition, one));
materializer.ensureCurrent(backend, session(false), BINDING, "events", null);
when(glue.getPartitions("lake", "events")).thenReturn(List.of(one));
int loaded = backend.statements.size();
materializer.ensureCurrent(backend, session(false), BINDING, "events", null);
assertThat(backend.statements.subList(loaded, backend.statements.size()).stream()
.anyMatch(sql -> sql.contains("WHERE (\"day\" IS NULL)")), equalTo(true));
}
@Test
void reloadsTheTableWhenItsDefinitionChanges() {
Table table = dayPartitionedTable();
Partition one = dayPartition(table, "2026-01-01", "one/", "e1");
when(glue.getPartitions("lake", "events")).thenReturn(List.of(one));
materializer.ensureCurrent(backend, session(false), BINDING, "events", DAY_ONE_SQL);
table.setVersionId("2");
int loaded = backend.statements.size();
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events", DAY_ONE_SQL),
equalTo(ExternalTableMaterializer.Outcome.LOADED));
assertThat(backend.statements.subList(loaded, backend.statements.size()).stream()
.anyMatch(sql -> sql.contains("TRUNCATE")), equalTo(true));
}
@Test
void doesNotReadAPartitionTheWhereExcludesEvenWhenItsObjectsAreDenied() {
Table table = dayPartitionedTable();
Partition one = dayPartition(table, "2026-01-01", "one/", "e1");
Partition two = dayPartition(table, "2026-01-02", "two/", "e2");
when(glue.getPartitions("lake", "events")).thenReturn(List.of(one, two));
doThrow(new AwsException("AccessDenied", "Access Denied", 403)).when(s3)
.authorizeSignedGetObject(anyString(), anyString(), eq("bucket"), eq("two/part-1.csv"));
materializer.ensureCurrent(backend, session(false), BINDING, "events", DAY_ONE_SQL);
SpectrumSqlException denied = assertThrows(SpectrumSqlException.class,
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events", DAY_TWO_SQL));
assertThat(denied.sqlState(), equalTo("42501"));
}
@Test
void loadsEveryPartitionInATransactionAndOnAnExtendedQueryBackend() {
Table table = dayPartitionedTable();
Partition one = dayPartition(table, "2026-01-01", "one/", "e1");
Partition two = dayPartition(table, "2026-01-02", "two/", "e2");
when(glue.getPartitions("lake", "events")).thenReturn(List.of(one, two));
materializer.ensureCurrent(backend, session(true), BINDING, "events", DAY_ONE_SQL);
RecordingBackend extended = new RecordingBackend();
extended.publicationAllowed = false;
materializer.ensureCurrent(extended, session(false), BINDING, "events", DAY_ONE_SQL);
verify(duck, times(2)).execute(argThat(sql -> sql.contains("s3://bucket/one/part-1.csv")
&& sql.contains("s3://bucket/two/part-1.csv")), any(), anyString(), eq(ACCOUNT));
}
@Test
void loadsEveryPartitionWhenTheQueryHasNoPartitionPredicate() {
Table table = dayPartitionedTable();
Partition one = dayPartition(table, "2026-01-01", "one/", "e1");
Partition two = dayPartition(table, "2026-01-02", "two/", "e2");
when(glue.getPartitions("lake", "events")).thenReturn(List.of(one, two));
materializer.ensureCurrent(backend, session(false), BINDING, "events",
"SELECT * FROM analytics.events WHERE id = 1");
verify(duck).execute(argThat(sql -> sql.contains("s3://bucket/one/part-1.csv")
&& sql.contains("s3://bucket/two/part-1.csv")), any(), anyString(), eq(ACCOUNT));
}
@Test
void createsTheTableEmptyWhenNoPartitionIsSelected() {
Table table = dayPartitionedTable();
Partition one = dayPartition(table, "2026-01-01", "one/", "e1");
when(glue.getPartitions("lake", "events")).thenReturn(List.of(one));
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events", DAY_TWO_SQL),
equalTo(ExternalTableMaterializer.Outcome.LOADED));
verify(duck, never()).execute(anyString(), any(), anyString(), anyString());
assertThat(backend.statements.stream().anyMatch(sql -> sql.contains("CREATE TABLE")), equalTo(true));
}
@Test
void refreshingOnePartitionReloadsOtherPartitionsWhoseConvertedKeysOverlap() {
Table table = csvTable();
table.setPartitionKeys(List.of(new Column("day", "int")));
when(glue.getTable("lake", "events")).thenReturn(table);
Partition p1 = dayPartition(table, "1", "one/", "e1");
Partition p01 = dayPartition(table, "01", "zero-one/", "e01");
when(glue.getPartitions("lake", "events")).thenReturn(List.of(p1, p01));
materializer.ensureCurrent(backend, session(false), BINDING, "events",
"SELECT * FROM analytics.events WHERE day IN (1, 01)");
Partition p1Changed = dayPartition(table, "1", "one/", "e1-new");
when(glue.getPartitions("lake", "events")).thenReturn(List.of(p1Changed, p01));
reset(duck);
int loaded = backend.statements.size();
materializer.ensureCurrent(backend, session(false), BINDING, "events",
"SELECT * FROM analytics.events WHERE day = 1");
verify(duck).execute(argThat(sql -> sql.contains("s3://bucket/one/part-1.csv")
&& sql.contains("s3://bucket/zero-one/part-1.csv")), any(), anyString(), eq(ACCOUNT));
List<String> replaced = backend.statements.subList(loaded, backend.statements.size());
assertThat(replaced.stream().anyMatch(sql -> sql.contains("TRUNCATE")), equalTo(true));
assertThat(replaced.stream().noneMatch(sql -> sql.contains("DELETE FROM")), equalTo(true));
}
@Test
void readsEveryPartitionWhenTwoKeysCastToTheSameValueEvenIfTheWhereExcludesOne() {
Table table = csvTable();
table.setPartitionKeys(List.of(new Column("day", "int")));
when(glue.getTable("lake", "events")).thenReturn(table);
Partition p1 = dayPartition(table, "1", "one/", "e1");
Partition p01 = dayPartition(table, "01", "zero-one/", "e01");
Partition p2 = dayPartition(table, "2", "two/", "e2");
when(glue.getPartitions("lake", "events")).thenReturn(List.of(p1, p01, p2));
materializer.ensureCurrent(backend, session(false), BINDING, "events",
"SELECT * FROM analytics.events WHERE day = 2");
verify(duck).execute(argThat(sql -> sql.contains("s3://bucket/one/part-1.csv")
&& sql.contains("s3://bucket/zero-one/part-1.csv")
&& sql.contains("s3://bucket/two/part-1.csv")), any(), anyString(), eq(ACCOUNT));
}
@Test
void keepsBothOverlappingPartitionsCurrentWhenNothingChanged() {
Table table = csvTable();
table.setPartitionKeys(List.of(new Column("day", "int")));
when(glue.getTable("lake", "events")).thenReturn(table);
Partition p1 = dayPartition(table, "1", "one/", "e1");
Partition p01 = dayPartition(table, "01", "zero-one/", "e01");
when(glue.getPartitions("lake", "events")).thenReturn(List.of(p1, p01));
materializer.ensureCurrent(backend, session(false), BINDING, "events",
"SELECT * FROM analytics.events WHERE day = 1");
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events",
"SELECT * FROM analytics.events WHERE day = 1"),
equalTo(ExternalTableMaterializer.Outcome.CURRENT));
}
private static Map<String, Object> schemaRow(String file, String name) {
return Map.of("file_name", file, "name", name);
}
@@ -0,0 +1,76 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import io.github.hectorvent.floci.services.glue.model.Column;
import io.github.hectorvent.floci.services.glue.model.Partition;
import io.github.hectorvent.floci.services.glue.model.Table;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PartitionOverlapTest {
@Test
void integerKeysThatCastToTheSameValueOverlap() {
assertTrue(overlap("int", "1", "01"));
assertTrue(overlap("bigint", "7", "+7"));
assertFalse(overlap("int", "1", "2"));
}
@Test
void decimalKeysOverlapOnValueAndScale() {
assertTrue(overlap("decimal(5,2)", "1.0", "1.00"));
assertTrue(overlap("decimal(5,2)", "1.001", "1.002"));
assertFalse(overlap("decimal(5,2)", "1.01", "1.02"));
}
@Test
void booleanKeysOverlapOnPostgresSpellings() {
assertTrue(overlap("boolean", "true", "t"));
assertTrue(overlap("boolean", "false", "off"));
assertFalse(overlap("boolean", "true", "false"));
}
@Test
void dateAndTimestampKeysOverlapOnTheirValue() {
assertTrue(overlap("date", "2026-01-02", "2026-01-02"));
assertTrue(overlap("timestamp", "2026-01-02 03:04:05", "2026-01-02T03:04:05"));
assertFalse(overlap("date", "2026-01-02", "2026-01-03"));
}
@Test
void stringKeysOverlapOnlyWhenEqual() {
assertFalse(overlap("string", "1", "01"));
assertTrue(overlap("char(3)", "a", "a "));
}
@Test
void missingAndDefaultPartitionsBothBecomeNull() {
assertTrue(overlap("string", "__HIVE_DEFAULT_PARTITION__", null));
}
@Test
void aValueThatCannotBeReducedCountsAsAnOverlap() {
assertTrue(overlap("int", "abc", "1"));
}
private static boolean overlap(String type, String first, String second) {
Column key = new Column();
key.setName("k");
key.setType(type);
Table table = new Table();
table.setPartitionKeys(List.of(key));
List<Partition> partitions = new ArrayList<>();
for (String value : new String[] {first, second}) {
Partition partition = new Partition();
List<String> values = new ArrayList<>();
values.add(value);
partition.setValues(values);
partitions.add(partition);
}
return ExternalTableMaterializer.hasOverlappingPartitions(table, partitions);
}
}
@@ -0,0 +1,343 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import io.github.hectorvent.floci.services.glue.model.Column;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
class PartitionPrunerTest {
private static final List<Column> DAY = List.of(new Column("day", "string"));
private static final List<Column> YEAR_MONTH = List.of(new Column("year", "int"), new Column("month", "int"));
private static final List<Column> DATE_KEY = List.of(new Column("dt", "date"));
private static Optional<PartitionPruner.Filter> filter(String sql, List<Column> keys) {
return PartitionPruner.filterFor(sql, "lake", "events", keys);
}
private static boolean keeps(Optional<PartitionPruner.Filter> filter, String... values) {
return filter.orElseThrow().matches(List.of(values));
}
@Test
void keepsOnlyThePartitionAnEqualityNames() {
Optional<PartitionPruner.Filter> filter = filter("SELECT * FROM lake.events WHERE day = '2026-01-02'", DAY);
assertThat(keeps(filter, "2026-01-02"), is(true));
assertThat(keeps(filter, "2026-01-01"), is(false));
}
@Test
void readsAnInListAndItsNegation() {
Optional<PartitionPruner.Filter> in = filter("SELECT * FROM lake.events WHERE day IN ('a', 'b')", DAY);
Optional<PartitionPruner.Filter> notIn = filter("SELECT * FROM lake.events WHERE day NOT IN ('a', 'b')", DAY);
assertThat(keeps(in, "a"), is(true));
assertThat(keeps(in, "c"), is(false));
assertThat(keeps(notIn, "a"), is(false));
assertThat(keeps(notIn, "c"), is(true));
}
@Test
void comparesIntegerKeysByValueIncludingRangesAndBetween() {
Optional<PartitionPruner.Filter> range = filter(
"SELECT * FROM lake.events WHERE year >= 2021 AND year < 2023 AND month = '7'", YEAR_MONTH);
Optional<PartitionPruner.Filter> between = filter(
"SELECT * FROM lake.events WHERE year BETWEEN 2020 AND 2022 AND month = 1", YEAR_MONTH);
assertThat(keeps(range, "2021", "7"), is(true));
assertThat(keeps(range, "2022", "07"), is(true));
assertThat(keeps(range, "2023", "7"), is(false));
assertThat(keeps(range, "2020", "7"), is(false));
assertThat(keeps(range, "2021", "8"), is(false));
assertThat(keeps(between, "2022", "1"), is(true));
assertThat(keeps(between, "2019", "1"), is(false));
}
@Test
void comparesDateKeysByDate() {
Optional<PartitionPruner.Filter> filter = filter(
"SELECT * FROM lake.events WHERE dt > '2026-01-10' AND dt <= '2026-01-12'", DATE_KEY);
assertThat(keeps(filter, "2026-01-11"), is(true));
assertThat(keeps(filter, "2026-01-12"), is(true));
assertThat(keeps(filter, "2026-01-10"), is(false));
assertThat(keeps(filter, "2026-01-13"), is(false));
}
@Test
void readsALiteralOnTheLeftAndNegativeNumbers() {
Optional<PartitionPruner.Filter> filter = filter("SELECT * FROM lake.events WHERE 5 < year AND month = -1", YEAR_MONTH);
assertThat(keeps(filter, "6", "-1"), is(true));
assertThat(keeps(filter, "5", "-1"), is(false));
}
@Test
void ignoresTermsItCannotReadAndKeepsTheRest() {
Optional<PartitionPruner.Filter> filter = filter(
"SELECT * FROM lake.events WHERE id = 7 AND lower(day) = 'x' AND day = 'a'", DAY);
assertThat(keeps(filter, "a"), is(true));
assertThat(keeps(filter, "b"), is(false));
}
@Test
void doesNotPruneWhenNothingInTheWhereIsReadable() {
assertThat(filter("SELECT * FROM lake.events WHERE id = 7", DAY).isPresent(), is(false));
assertThat(filter("SELECT * FROM lake.events WHERE lower(day) = 'a'", DAY).isPresent(), is(false));
assertThat(filter("SELECT * FROM lake.events", DAY).isPresent(), is(false));
}
@Test
void treatsAWhereWithATopLevelOrAsOneTerm() {
Optional<PartitionPruner.Filter> keysOnly = filter("SELECT * FROM lake.events WHERE day = 'a' OR day = 'b'", DAY);
assertThat(keeps(keysOnly, "a"), is(true));
assertThat(keeps(keysOnly, "b"), is(true));
assertThat(keeps(keysOnly, "c"), is(false));
assertThat(filter("SELECT * FROM lake.events WHERE day = 'a' OR id = 1 AND day = 'b'", DAY).isPresent(), is(false));
}
@Test
void keepsAnAndInsideBetweenWithTheBetween() {
Optional<PartitionPruner.Filter> filter = filter(
"SELECT * FROM lake.events WHERE year BETWEEN 2020 AND 2021 AND month = 3", YEAR_MONTH);
assertThat(keeps(filter, "2021", "3"), is(true));
assertThat(keeps(filter, "2022", "3"), is(false));
}
@Test
void readsNotAndParentheses() {
Optional<PartitionPruner.Filter> filter = filter(
"SELECT * FROM lake.events WHERE NOT (day = 'a' OR day = 'b')", DAY);
assertThat(keeps(filter, "c"), is(true));
assertThat(keeps(filter, "a"), is(false));
}
@Test
void qualifiesColumnsByTheAliasWhenThereIsOne() {
Optional<PartitionPruner.Filter> aliased = filter("SELECT * FROM lake.events AS e WHERE e.day = 'a'", DAY);
Optional<PartitionPruner.Filter> bareAlias = filter("SELECT * FROM lake.events e WHERE e.day = 'a'", DAY);
Optional<PartitionPruner.Filter> tableName = filter("SELECT * FROM lake.events WHERE events.day = 'a'", DAY);
Optional<PartitionPruner.Filter> schemaAndTable = filter("SELECT * FROM lake.events WHERE lake.events.day = 'a'", DAY);
assertThat(keeps(aliased, "b"), is(false));
assertThat(keeps(bareAlias, "b"), is(false));
assertThat(keeps(tableName, "b"), is(false));
assertThat(keeps(schemaAndTable, "b"), is(false));
assertThat(filter("SELECT * FROM lake.events e WHERE events.day = 'a'", DAY).isPresent(), is(false));
assertThat(filter("SELECT * FROM lake.events e WHERE o.day = 'a'", DAY).isPresent(), is(false));
}
@Test
void readsADatabaseQualifiedName() {
Optional<PartitionPruner.Filter> filter = filter("SELECT * FROM dev.lake.events WHERE day = 'a'", DAY);
assertThat(keeps(filter, "b"), is(false));
}
@Test
void usesTheWhereOfTheBlockThatNamesTheTable() {
Optional<PartitionPruner.Filter> inner = filter(
"SELECT * FROM o WHERE o.id IN (SELECT id FROM lake.events WHERE day = 'a') AND o.x = 1", DAY);
Optional<PartitionPruner.Filter> notInnerWhere = filter(
"SELECT * FROM (SELECT * FROM lake.events) s WHERE s.day = 'a'", DAY);
assertThat(keeps(inner, "b"), is(false));
assertThat(keeps(inner, "a"), is(true));
assertThat(notInnerWhere.isPresent(), is(false));
}
@Test
void unionsEveryPlaceTheTableIsNamedAndGivesUpIfOneHasNoPredicate() {
Optional<PartitionPruner.Filter> both = filter(
"SELECT id FROM lake.events WHERE day = 'a' UNION ALL SELECT id FROM lake.events WHERE day = 'b'", DAY);
assertThat(keeps(both, "a"), is(true));
assertThat(keeps(both, "b"), is(true));
assertThat(keeps(both, "c"), is(false));
assertThat(filter("SELECT id FROM lake.events WHERE day = 'a' UNION ALL SELECT id FROM lake.events", DAY)
.isPresent(), is(false));
assertThat(filter("SELECT 1 FROM lake.events WHERE day = 'a'; SELECT 2 FROM lake.events", DAY).isPresent(),
is(false));
}
@Test
void stopsTheWhereAtTheClauseThatFollowsIt() {
Optional<PartitionPruner.Filter> filter = filter(
"SELECT day, count(*) FROM lake.events WHERE day = 'a' GROUP BY day HAVING count(*) > 1 ORDER BY 1 LIMIT 5", DAY);
assertThat(keeps(filter, "a"), is(true));
assertThat(keeps(filter, "b"), is(false));
}
@Test
void dropsATermThatAcceptsNullBecauseTheTableMayBeOnTheNullableSideOfAnOuterJoin() {
assertThat(filter("SELECT o.id FROM o LEFT JOIN lake.events e ON o.id = e.id WHERE e.day IS NULL", DAY)
.isPresent(), is(false));
assertThat(filter("SELECT o.id FROM o LEFT JOIN lake.events e ON o.id = e.id WHERE e.day IS NULL OR e.day = 'a'", DAY)
.isPresent(), is(false));
assertThat(filter("SELECT o.id FROM o LEFT JOIN lake.events e ON o.id = e.id WHERE NOT (e.day = 'a')", DAY)
.isPresent(), is(true));
assertThat(filter("SELECT o.id FROM o LEFT JOIN lake.events e ON o.id = e.id WHERE NOT (e.day IS NOT NULL)", DAY)
.isPresent(), is(false));
}
@Test
void keepsAnIsNotNullTermAndDropsTheDefaultPartition() {
Optional<PartitionPruner.Filter> filter = filter("SELECT * FROM lake.events WHERE day IS NOT NULL", DAY);
assertThat(keeps(filter, "a"), is(true));
assertThat(keeps(filter, "__HIVE_DEFAULT_PARTITION__"), is(false));
}
@Test
void readsTheHiveDefaultPartitionAndAValueWiderThanItsKeyAsNull() {
Optional<PartitionPruner.Filter> equality = filter("SELECT * FROM lake.events WHERE day = 'a'", DAY);
Optional<PartitionPruner.Filter> narrow = filter("SELECT * FROM lake.events WHERE day = 'abcd'",
List.of(new Column("day", "varchar(3)")));
assertThat(keeps(equality, "__HIVE_DEFAULT_PARTITION__"), is(false));
assertThat(keeps(narrow, "abcd"), is(false));
assertThat(keeps(narrow, "abc"), is(false));
}
@Test
void keepsAPartitionWhoseValueItCannotCompare() {
Optional<PartitionPruner.Filter> filter = filter("SELECT * FROM lake.events WHERE year = 2020 AND month = 1", YEAR_MONTH);
assertThat(keeps(filter, "not-a-number", "1"), is(true));
}
@Test
void readsOnlyEqualityOnStringKeysBecauseOrderingDependsOnTheCollation() {
assertThat(filter("SELECT * FROM lake.events WHERE day > 'a'", DAY).isPresent(), is(false));
assertThat(filter("SELECT * FROM lake.events WHERE day LIKE 'a%'", DAY).isPresent(), is(false));
assertThat(filter("SELECT * FROM lake.events WHERE day = 1", DAY).isPresent(), is(false));
}
@Test
void ignoresKeyTypesItDoesNotCompare() {
assertThat(filter("SELECT * FROM lake.events WHERE p = 1.5", List.of(new Column("p", "double"))).isPresent(),
is(false));
assertThat(filter("SELECT * FROM lake.events WHERE p = '2026-01-01 00:00:00'",
List.of(new Column("p", "timestamp"))).isPresent(), is(false));
assertThat(filter("SELECT * FROM lake.events WHERE dt = '1/2/2026'", DATE_KEY).isPresent(), is(false));
}
@Test
void ignoresCommentsAndQuotedTextThatLooksLikeSql() {
Optional<PartitionPruner.Filter> filter = filter(
"SELECT 'x) where' /* WHERE day = 'z' */ FROM lake.events -- ) WHERE\n WHERE \"day\" = 'a)b'", DAY);
assertThat(keeps(filter, "a)b"), is(true));
assertThat(keeps(filter, "z"), is(false));
}
@Test
void givesUpOnTextWhoseQuotingItDoesNotRead() {
assertThat(filter("SELECT E'a\\'' FROM lake.events WHERE day = 'a'", DAY).isPresent(), is(false));
assertThat(filter("SELECT $$x$$ FROM lake.events WHERE day = 'a'", DAY).isPresent(), is(false));
assertThat(filter("SELECT 'unterminated FROM lake.events WHERE day = 'a'", DAY).isPresent(), is(false));
assertThat(filter("SELECT (1 FROM lake.events WHERE day = 'a'", DAY).isPresent(), is(false));
assertThat(filter("SELECT 1) FROM lake.events WHERE day = 'a'", DAY).isPresent(), is(false));
}
@Test
void ignoresAParameterAndKeepsTheOtherTerms() {
Optional<PartitionPruner.Filter> filter = filter(
"SELECT * FROM lake.events WHERE day = $1 AND day <> 'b'", DAY);
assertThat(keeps(filter, "a"), is(true));
assertThat(keeps(filter, "b"), is(false));
}
@Test
void ignoresAnotherSchemaOrTable() {
assertThat(filter("SELECT * FROM other.events WHERE day = 'a'", DAY).isPresent(), is(false));
assertThat(filter("SELECT * FROM lake.other WHERE day = 'a'", DAY).isPresent(), is(false));
assertThat(PartitionPruner.filterFor("SELECT * FROM lake.events WHERE day = 'a'", "lake", "events", List.of())
.isPresent(), is(false));
assertThat(PartitionPruner.filterFor(null, "lake", "events", DAY).isPresent(), is(false));
}
@Test
void doesNotTreatAColumnQualifiedBySchemaAndTableAsAnotherReference() {
Optional<PartitionPruner.Filter> filter = filter(
"SELECT lake.events.id FROM lake.events WHERE lake.events.day = 'a'", DAY);
assertThat(keeps(filter, "a"), is(true));
assertThat(keeps(filter, "b"), is(false));
}
@Test
void matchesQuotedNamesExactlyAndUnquotedOnesIgnoringCase() {
Optional<PartitionPruner.Filter> upperUnquoted = filter("SELECT * FROM LAKE.EVENTS WHERE DAY = 'a'", DAY);
Optional<PartitionPruner.Filter> quotedCase = PartitionPruner.filterFor(
"SELECT * FROM \"Lake\".\"Events\" WHERE \"Day\" = 'a'", "Lake", "Events", List.of(new Column("Day", "string")));
assertThat(keeps(upperUnquoted, "b"), is(false));
assertThat(keeps(quotedCase, "b"), is(false));
assertThat(PartitionPruner.filterFor("SELECT * FROM \"Lake\".\"Events\" WHERE \"day\" = 'a'", "Lake", "Events",
List.of(new Column("Day", "string"))).isPresent(), is(false));
}
@Test
void aWhereBeforeTheTableIsNamedDoesNotApplyToIt() {
assertThat(filter("SELECT * FROM a WHERE a.x = 1 AND EXISTS (SELECT 1 FROM lake.events)", DAY).isPresent(),
is(false));
assertThat(filter("SELECT * FROM lake.events WHERE day = 'a'", DAY).isPresent(), is(true));
}
@Test
void doesNotTreatAndInsideCaseAsATopLevelSeparator() {
String sql = "SELECT * FROM lake.events WHERE CASE WHEN id = 7 AND day = 'a' AND id = 8 THEN TRUE ELSE TRUE END";
assertThat(filter(sql, DAY).isPresent(), is(false));
}
@Test
void keepsValidConjunctAlongsideACaseExpression() {
String sql = "SELECT * FROM lake.events WHERE (CASE WHEN id = 1 THEN 'a' ELSE 'b' END) = 'a' AND day = '2026-01-01'";
Optional<PartitionPruner.Filter> filter = filter(sql, DAY);
assertThat(keeps(filter, "2026-01-01"), is(true));
assertThat(keeps(filter, "2026-01-02"), is(false));
}
@Test
void readsPredicatesPastNestedComments() {
Optional<PartitionPruner.Filter> filter = filter(
"SELECT * FROM lake.events WHERE /* outer /* nested */ */ day = '2026-01-01'", DAY);
assertThat(keeps(filter, "2026-01-01"), is(true));
assertThat(keeps(filter, "2026-01-02"), is(false));
}
@Test
void ignoresDollarQuotedPredicatesAndFallsBackSafely() {
String sql = "SELECT * FROM lake.events WHERE day = $tag$2026-01-01$tag$";
assertThat(filter(sql, DAY).isPresent(), is(false));
}
@Test
void handlesQuotedIdentifiersWithEscapesInPredicates() {
Optional<PartitionPruner.Filter> filter = filter(
"SELECT * FROM lake.events WHERE \"day\" = '2026-01-01'", DAY);
assertThat(keeps(filter, "2026-01-01"), is(true));
assertThat(keeps(filter, "2026-01-02"), is(false));
}
@Test
void returnsEmptyFilterForUnterminatedLiteralsInPredicates() {
assertThat(filter("SELECT * FROM lake.events WHERE day = 'unterminated", DAY).isPresent(), is(false));
assertThat(filter("SELECT * FROM lake.events WHERE \"day = '2026-01-01'", DAY).isPresent(), is(false));
assertThat(filter("SELECT * FROM lake.events WHERE /* unclosed day = '2026-01-01'", DAY).isPresent(), is(false));
}
}
@@ -28,7 +28,7 @@ class SpectrumQueryPreparationTest {
materializer = mock(ExternalTableMaterializer.class);
backend = mock(BackendSql.class);
when(registry.list(SESSION.accountId(), SESSION.clusterKey(), "dev")).thenReturn(List.of(BINDING));
when(materializer.ensureCurrent(any(), any(), any(), anyString()))
when(materializer.ensureCurrent(any(), any(), any(), anyString(), anyString()))
.thenReturn(ExternalTableMaterializer.Outcome.CURRENT);
glue = mock(GlueService.class);
preparation = new SpectrumQueryPreparation(registry, materializer, new ExternalStatementParser(),
@@ -59,9 +59,10 @@ class SpectrumQueryPreparationTest {
@Test
void preparesDistinctExternalReferences() {
assertFalse(preparation.prepare("SELECT a.id, SUM(b.amount) FROM lake.sales a JOIN lake.sales b "
+ "ON a.id=b.id JOIN public.customers c ON c.id=a.id GROUP BY a.id ORDER BY a.id", SESSION, backend));
verify(materializer).ensureCurrent(backend, SESSION, BINDING, "sales");
String sql = "SELECT a.id, SUM(b.amount) FROM lake.sales a JOIN lake.sales b "
+ "ON a.id=b.id JOIN public.customers c ON c.id=a.id GROUP BY a.id ORDER BY a.id";
assertFalse(preparation.prepare(sql, SESSION, backend));
verify(materializer).ensureCurrent(backend, SESSION, BINDING, "sales", sql);
}
@Test
@@ -80,7 +81,7 @@ class SpectrumQueryPreparationTest {
@Test
void missingGlueTableDoesNotUseCachedRelation() {
when(materializer.ensureCurrent(backend, SESSION, BINDING, "sales"))
when(materializer.ensureCurrent(backend, SESSION, BINDING, "sales", "SELECT * FROM lake.sales"))
.thenReturn(ExternalTableMaterializer.Outcome.NOT_EXTERNAL);
SpectrumSqlException error = assertThrows(SpectrumSqlException.class, () ->
preparation.prepare("SELECT * FROM lake.sales", SESSION, backend));
@@ -0,0 +1,175 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class SpectrumSqlLexerTest {
@Test
void handlesNullAndEmptySql() {
SpectrumSqlLexer.Result nullResult = SpectrumSqlLexer.tokenize(null);
assertTrue(nullResult.tokens().isEmpty());
assertFalse(nullResult.unsafe());
SpectrumSqlLexer.Result emptyResult = SpectrumSqlLexer.tokenize("");
assertTrue(emptyResult.tokens().isEmpty());
assertFalse(emptyResult.unsafe());
}
@Test
void tokenizesWordsCaseInsensitively() {
SpectrumSqlLexer.Result result = SpectrumSqlLexer.tokenize("SELECT Col_One FROM Table_A");
assertFalse(result.unsafe());
List<SpectrumSqlLexer.Token> tokens = result.tokens();
assertEquals(4, tokens.size());
assertEquals(SpectrumSqlLexer.Kind.WORD, tokens.get(0).kind());
assertEquals("select", tokens.get(0).text());
assertEquals(SpectrumSqlLexer.Kind.WORD, tokens.get(1).kind());
assertEquals("col_one", tokens.get(1).text());
assertEquals(SpectrumSqlLexer.Kind.WORD, tokens.get(2).kind());
assertEquals("from", tokens.get(2).text());
assertEquals(SpectrumSqlLexer.Kind.WORD, tokens.get(3).kind());
assertEquals("table_a", tokens.get(3).text());
}
@Test
void stripsLineAndBlockComments() {
String sql = """
-- single line comment
SELECT /* inline comment */ 1
/* multi-line
comment */
/* nested /* block */ comment */
FROM t
""";
SpectrumSqlLexer.Result result = SpectrumSqlLexer.tokenize(sql);
assertFalse(result.unsafe());
List<String> texts = result.tokens().stream().map(SpectrumSqlLexer.Token::text).toList();
assertThat(texts, equalTo(List.of("select", "1", "from", "t")));
}
@Test
void flagsUnterminatedBlockCommentAsUnsafe() {
SpectrumSqlLexer.Result result = SpectrumSqlLexer.tokenize("SELECT 1 /* unterminated");
assertTrue(result.unsafe());
}
@Test
void parsesQuotedIdentifiersAndEscapes() {
SpectrumSqlLexer.Result result = SpectrumSqlLexer.tokenize("SELECT \"My \"\"Quoted\"\" Col\" FROM \"T\"");
assertFalse(result.unsafe());
List<SpectrumSqlLexer.Token> tokens = result.tokens();
assertEquals(4, tokens.size());
assertEquals(SpectrumSqlLexer.Kind.QUOTED_WORD, tokens.get(1).kind());
assertEquals("My \"Quoted\" Col", tokens.get(1).text());
assertTrue(tokens.get(1).quoted());
assertEquals(SpectrumSqlLexer.Kind.QUOTED_WORD, tokens.get(3).kind());
assertEquals("T", tokens.get(3).text());
}
@Test
void flagsUnterminatedQuotedIdentifierAsUnsafe() {
SpectrumSqlLexer.Result result = SpectrumSqlLexer.tokenize("SELECT \"unterminated FROM t");
assertTrue(result.unsafe());
}
@Test
void parsesStringLiteralsAndEscapes() {
SpectrumSqlLexer.Result result = SpectrumSqlLexer.tokenize("SELECT 'it''s a value', 'regular'");
assertFalse(result.unsafe());
List<SpectrumSqlLexer.Token> tokens = result.tokens();
assertEquals(4, tokens.size());
assertEquals(SpectrumSqlLexer.Kind.STRING, tokens.get(1).kind());
assertEquals("it's a value", tokens.get(1).text());
assertTrue(tokens.get(1).quoted());
assertEquals(SpectrumSqlLexer.Kind.COMMA, tokens.get(2).kind());
assertEquals(SpectrumSqlLexer.Kind.STRING, tokens.get(3).kind());
assertEquals("regular", tokens.get(3).text());
}
@Test
void parsesEscapeStringConstantsAndMarksUnsafe() {
SpectrumSqlLexer.Result result = SpectrumSqlLexer.tokenize("SELECT E'hello \\'world\\'', e'line\\n'");
assertTrue(result.unsafe());
List<SpectrumSqlLexer.Token> tokens = result.tokens();
assertEquals(6, tokens.size());
assertEquals("select", tokens.get(0).text());
assertEquals("e", tokens.get(1).text());
assertEquals("hello 'world'", tokens.get(2).text());
assertEquals(",", tokens.get(3).text());
assertEquals("e", tokens.get(4).text());
assertEquals("linen", tokens.get(5).text());
}
@Test
void flagsUnterminatedStringAsUnsafe() {
SpectrumSqlLexer.Result result = SpectrumSqlLexer.tokenize("SELECT 'unterminated");
assertTrue(result.unsafe());
}
@Test
void handlesDollarQuotedBlocksAndMarksUnsafe() {
SpectrumSqlLexer.Result anonymous = SpectrumSqlLexer.tokenize("SELECT $$function body$$ FROM t");
assertTrue(anonymous.unsafe());
assertEquals(4, anonymous.tokens().size());
assertEquals(SpectrumSqlLexer.Kind.DOLLAR_QUOTED, anonymous.tokens().get(1).kind());
assertEquals("$$function body$$", anonymous.tokens().get(1).text());
SpectrumSqlLexer.Result tagged = SpectrumSqlLexer.tokenize("SELECT $tag$body$tag$ FROM t");
assertTrue(tagged.unsafe());
assertEquals(4, tagged.tokens().size());
assertEquals(SpectrumSqlLexer.Kind.DOLLAR_QUOTED, tagged.tokens().get(1).kind());
assertEquals("$tag$body$tag$", tagged.tokens().get(1).text());
}
@Test
void handlesPositionalParameters() {
SpectrumSqlLexer.Result result = SpectrumSqlLexer.tokenize("SELECT * FROM t WHERE id = $1 AND val = $12");
assertFalse(result.unsafe());
List<SpectrumSqlLexer.Token> params = result.tokens().stream()
.filter(t -> t.text().startsWith("$")).toList();
assertEquals(2, params.size());
assertEquals("$1", params.get(0).text());
assertEquals(SpectrumSqlLexer.Kind.OTHER, params.get(0).kind());
assertEquals("$12", params.get(1).text());
}
@Test
void parsesOperatorsAndPunctuation() {
SpectrumSqlLexer.Result result = SpectrumSqlLexer.tokenize("SELECT a::int <= 10 AND b >= 20 AND c <> 30 AND d != 40;");
assertFalse(result.unsafe());
List<SpectrumSqlLexer.Token> tokens = result.tokens();
List<String> opTexts = tokens.stream().filter(t -> t.kind() == SpectrumSqlLexer.Kind.OP).map(SpectrumSqlLexer.Token::text).toList();
assertThat(opTexts, equalTo(List.of("<=", ">=", "<>", "!=")));
assertTrue(tokens.stream().anyMatch(t -> t.kind() == SpectrumSqlLexer.Kind.SEMICOLON));
assertTrue(tokens.stream().anyMatch(t -> t.kind() == SpectrumSqlLexer.Kind.OTHER && t.text().equals("::")));
}
@Test
void parsesNumbers() {
SpectrumSqlLexer.Result result = SpectrumSqlLexer.tokenize("SELECT 42, 3.14159, 100");
assertFalse(result.unsafe());
List<SpectrumSqlLexer.Token> numbers = result.tokens().stream()
.filter(t -> t.kind() == SpectrumSqlLexer.Kind.NUMBER).toList();
assertEquals(3, numbers.size());
assertEquals("42", numbers.get(0).text());
assertEquals("3.14159", numbers.get(1).text());
assertEquals("100", numbers.get(2).text());
}
@Test
void flagsCustomPrefixStringsAsUnsafe() {
SpectrumSqlLexer.Result unicode = SpectrumSqlLexer.tokenize("SELECT u&'d\\0061t\\0061'");
assertTrue(unicode.unsafe());
SpectrumSqlLexer.Result bit = SpectrumSqlLexer.tokenize("SELECT b'101'");
assertTrue(bit.unsafe());
}
}