mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
bc31464ab9
commit
a42779bb2a
13 files changed
+2220
-155
No files matched your search
+73
@@ -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());
|
||||
|
||||
+24
@@ -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")));
|
||||
}
|
||||
}
|
||||
+253
@@ -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);
|
||||
}
|
||||
|
||||
+76
@@ -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);
|
||||
}
|
||||
}
|
||||
+343
@@ -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));
|
||||
}
|
||||
}
|
||||
+6
-5
@@ -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));
|
||||
|
||||
+175
@@ -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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user