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()));
diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/PartitionPruner.java b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/PartitionPruner.java
new file mode 100644
index 0000000000..3451fb5e97
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/PartitionPruner.java
@@ -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.
+ *
+ * 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.
+ *
+ *
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 SEGMENT_BOUNDARIES = Set.of("union", "intersect", "except");
+ private static final Set CLAUSE_AFTER_WHERE = Set.of("group", "order", "having", "limit", "offset",
+ "fetch", "window", "qualify", "for", "returning");
+ private static final Set 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 keys;
+ private final List> occurrences;
+
+ private Filter(List keys, List> occurrences) {
+ this.keys = keys;
+ this.occurrences = occurrences;
+ }
+
+ /** Whether a partition with these key values can hold rows the query reads. */
+ boolean matches(List values) {
+ Row row = new Row(keys, values);
+ for (List 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 filterFor(String sql, String schema, String table, List partitionKeys) {
+ if (sql == null || partitionKeys == null || partitionKeys.isEmpty()) {
+ return Optional.empty();
+ }
+ Tokens tokens = tokenize(sql);
+ if (tokens.unsafe || !tokens.balanced()) {
+ return Optional.empty();
+ }
+ List> 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 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 conjunctsFor(Tokens tokens, Chain occurrence, String schema, String table,
+ List 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> qualifiers = qualifiers(tokens, occurrence, schema, table);
+ if (qualifiers == null) {
+ return List.of();
+ }
+ List conjuncts = new ArrayList<>();
+ for (List 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 keys) {
+ List 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> 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> 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> split(List 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> terms = new ArrayList<>();
+ List 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 keys, List 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 tokens, List keys, Set> 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 tokens;
+ private final List keys;
+ private final Set> qualifiers;
+ private int position;
+
+ Parser(List tokens, List keys, Set> 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 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 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 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 list;
+ int[] depth;
+ final boolean unsafe;
+
+ Tokens(List 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 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 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 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 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());
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumQueryPreparation.java b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumQueryPreparation.java
index 06d1d3bf82..f6694676f1 100644
--- a/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumQueryPreparation.java
+++ b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumQueryPreparation.java
@@ -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");
diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumSqlLexer.java b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumSqlLexer.java
new file mode 100644
index 0000000000..0caab6f269
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumSqlLexer.java
@@ -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).
+ *
+ * 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 tokens, boolean unsafe) {
+ }
+
+ private SpectrumSqlLexer() {
+ }
+
+ static Result tokenize(String sql) {
+ if (sql == null || sql.isEmpty()) {
+ return new Result(List.of(), false);
+ }
+ List 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 == '$');
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftSpectrumIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftSpectrumIntegrationTest.java
index fbebe622c4..3d7088997a 100644
--- a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftSpectrumIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftSpectrumIntegrationTest.java
@@ -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());
diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/ExternalReferenceScannerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/ExternalReferenceScannerTest.java
index df2b92a078..7d40567cca 100644
--- a/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/ExternalReferenceScannerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/ExternalReferenceScannerTest.java
@@ -14,6 +14,15 @@ import static org.hamcrest.Matchers.equalTo;
class ExternalReferenceScannerTest {
private static final Set 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")));
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/ExternalTableMaterializerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/ExternalTableMaterializerTest.java
index 871cd6aec0..0b1b431e62 100644
--- a/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/ExternalTableMaterializerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/ExternalTableMaterializerTest.java
@@ -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 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 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 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 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 schemaRow(String file, String name) {
return Map.of("file_name", file, "name", name);
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/PartitionOverlapTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/PartitionOverlapTest.java
new file mode 100644
index 0000000000..4da596bdee
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/PartitionOverlapTest.java
@@ -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 partitions = new ArrayList<>();
+ for (String value : new String[] {first, second}) {
+ Partition partition = new Partition();
+ List values = new ArrayList<>();
+ values.add(value);
+ partition.setValues(values);
+ partitions.add(partition);
+ }
+ return ExternalTableMaterializer.hasOverlappingPartitions(table, partitions);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/PartitionPrunerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/PartitionPrunerTest.java
new file mode 100644
index 0000000000..37278d8012
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/PartitionPrunerTest.java
@@ -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 DAY = List.of(new Column("day", "string"));
+ private static final List YEAR_MONTH = List.of(new Column("year", "int"), new Column("month", "int"));
+ private static final List DATE_KEY = List.of(new Column("dt", "date"));
+
+ private static Optional filter(String sql, List keys) {
+ return PartitionPruner.filterFor(sql, "lake", "events", keys);
+ }
+
+ private static boolean keeps(Optional filter, String... values) {
+ return filter.orElseThrow().matches(List.of(values));
+ }
+
+ @Test
+ void keepsOnlyThePartitionAnEqualityNames() {
+ Optional 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 in = filter("SELECT * FROM lake.events WHERE day IN ('a', 'b')", DAY);
+ Optional 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 range = filter(
+ "SELECT * FROM lake.events WHERE year >= 2021 AND year < 2023 AND month = '7'", YEAR_MONTH);
+ Optional 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 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 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 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 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 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 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 aliased = filter("SELECT * FROM lake.events AS e WHERE e.day = 'a'", DAY);
+ Optional bareAlias = filter("SELECT * FROM lake.events e WHERE e.day = 'a'", DAY);
+ Optional tableName = filter("SELECT * FROM lake.events WHERE events.day = 'a'", DAY);
+ Optional 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 filter = filter("SELECT * FROM dev.lake.events WHERE day = 'a'", DAY);
+
+ assertThat(keeps(filter, "b"), is(false));
+ }
+
+ @Test
+ void usesTheWhereOfTheBlockThatNamesTheTable() {
+ Optional inner = filter(
+ "SELECT * FROM o WHERE o.id IN (SELECT id FROM lake.events WHERE day = 'a') AND o.x = 1", DAY);
+ Optional 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 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 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 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 equality = filter("SELECT * FROM lake.events WHERE day = 'a'", DAY);
+ Optional 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 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 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 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 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 upperUnquoted = filter("SELECT * FROM LAKE.EVENTS WHERE DAY = 'a'", DAY);
+ Optional 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 filter = filter(sql, DAY);
+
+ assertThat(keeps(filter, "2026-01-01"), is(true));
+ assertThat(keeps(filter, "2026-01-02"), is(false));
+ }
+
+ @Test
+ void readsPredicatesPastNestedComments() {
+ Optional 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 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));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumQueryPreparationTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumQueryPreparationTest.java
index 8bfbd13e8b..9fd04c063c 100644
--- a/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumQueryPreparationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumQueryPreparationTest.java
@@ -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));
diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumSqlLexerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumSqlLexerTest.java
new file mode 100644
index 0000000000..69643c242f
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumSqlLexerTest.java
@@ -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 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 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 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 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 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 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 tokens = result.tokens();
+ List 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 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());
+ }
+}