mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(athena): take templated partition values from the object path (#8242)
This commit is contained in:
1 parent
4cd8ab991e
commit
01d61afd8a
9 files changed
+1042
-16
No files matched your search
+291
@@ -0,0 +1,291 @@
|
||||
package io.floci.aws.services.athena;
|
||||
|
||||
import io.floci.aws.services.floci.duck.FlociDuckClient;
|
||||
import io.floci.aws.services.glue.GlueService;
|
||||
import io.floci.aws.services.glue.model.Column;
|
||||
import io.floci.aws.services.glue.model.Database;
|
||||
import io.floci.aws.services.glue.model.StorageDescriptor;
|
||||
import io.floci.aws.services.glue.model.Table;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import io.floci.aws.testing.SidecarContainersProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Reads projecting tables whose partitions follow a {@code storage.location.template} through the
|
||||
* real floci-duck sidecar, using the views Athena would build for them.
|
||||
*
|
||||
* <p>Each table reads the same one-row Parquet file, which, like any partitioned dataset, holds no
|
||||
* partition columns: {@code region} and {@code dt} exist only in the object paths. Athena derives
|
||||
* them from the path through the template, so every table here returns {@code r1, eu, 2026-03-14};
|
||||
* the default {@code column=value} layout is the control.
|
||||
*
|
||||
* <p>The views come from {@link GlueViewDdlBuilder} over these tables alone rather than from Athena
|
||||
* end to end: the sidecar application is shared with other test classes, and Athena builds views
|
||||
* for every Glue table it holds, so another class's tables would be in every query.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(SidecarContainersProfile.class)
|
||||
class AthenaPartitionTemplateSidecarIntegrationTest {
|
||||
|
||||
/** One row, {@code id = 'r1', status = 'ok'}, written by DuckDB. */
|
||||
private static final byte[] PARQUET = Base64.getDecoder().decode(
|
||||
"UEFSMRUAFQwVECwVAhUAFQYVBgAABhQCAAAAcjEVABUMFRAsFQIVABUGFQYAAAYUAgAAAG9rFQIZPDUAGA1kdWNrZGJfc2No"
|
||||
+ "ZW1hFQQAFQwlABgCaWQlAAAVDCUAGAZzdGF0dXMlAAAWAhkcGSwmABwVDBkVABkYAmlkFQIWAhYuFjImCDwYAnIxGAJyMRYA"
|
||||
+ "KAJyMRgCcjEREQAZHBUAFQAVAgAAACYAHBUMGRUAGRgGc3RhdHVzFQIWAhYuFjImOjwYAm9rGAJvaxYAKAJvaxgCb2sREQAZ"
|
||||
+ "HBUAFQAVAgAAABZcFgImCBZkACgoRHVja0RCIHZlcnNpb24gdjIuMC4wIChidWlsZCBkNTRjYmJlM2RmKRksHAAAHAAAAOgA"
|
||||
+ "AABQQVIx");
|
||||
|
||||
private static final List<Map<String, String>> EXPECTED_ROW =
|
||||
List.of(Map.of("id", "r1", "region", "eu", "dt", "2026-03-14"));
|
||||
|
||||
@Inject
|
||||
FlociDuckClient duck;
|
||||
|
||||
@Inject
|
||||
S3Service s3Service;
|
||||
|
||||
private String bucket;
|
||||
private String schema;
|
||||
private final List<String> keys = new ArrayList<>();
|
||||
private final List<Table> tables = new ArrayList<>();
|
||||
|
||||
@BeforeAll
|
||||
static void requireDocker() {
|
||||
SidecarContainersProfile.requireDocker();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void createBucket() {
|
||||
bucket = "athena-template-" + System.nanoTime();
|
||||
schema = "template_" + System.nanoTime();
|
||||
s3Service.createBucket(bucket, "us-east-1");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void deleteBucket() {
|
||||
for (String key : keys) {
|
||||
s3Service.deleteObject(bucket, key);
|
||||
}
|
||||
s3Service.deleteBucket(bucket);
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultLayoutReadsPartitionValuesFromColumnEqualsValueFolders() {
|
||||
table("sales_hive", "hive", null, "hive/region=eu/dt=2026-03-14/part.parquet");
|
||||
|
||||
assertEquals(EXPECTED_ROW, queryEuInMarch("sales_hive"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void templateWithBareValuesMapsEachFolderToItsKey() {
|
||||
table("sales_bare", "bare", "bare/${region}/${dt}/", "bare/eu/2026-03-14/part.parquet");
|
||||
|
||||
assertEquals(EXPECTED_ROW, queryEuInMarch("sales_bare"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void templateWithLiteralPrefixesAndStaticFolders() {
|
||||
table("sales_mixed", "mixed", "mixed/region=${region}/static/${dt}/",
|
||||
"mixed/region=eu/static/2026-03-14/part.parquet");
|
||||
|
||||
assertEquals(EXPECTED_ROW, queryEuInMarch("sales_mixed"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Athena builds a path from one value per key, so an object whose repeated placeholder holds two
|
||||
* different values is at a path no query addresses, and is never read.
|
||||
*/
|
||||
@Test
|
||||
void templateRepeatingAPlaceholderReadsOnlyPathsWhereItsValuesAgree() {
|
||||
table("sales_repeat", "repeat", "repeat/${region}/${dt}/${region}/",
|
||||
"repeat/eu/2026-03-14/eu/part.parquet", "repeat/eu/2026-03-14/us/part.parquet");
|
||||
|
||||
assertEquals(EXPECTED_ROW, queryEuInMarch("sales_repeat"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Each row carries the values of its own path, and an object at a path whose value the key's
|
||||
* type cannot hold (no date is {@code latest}) is one projection never generates, so it is not
|
||||
* read rather than failing the query.
|
||||
*/
|
||||
@Test
|
||||
void eachObjectCarriesItsOwnPathsValuesAndUnparsableValuesAreNotRead() {
|
||||
table("sales_bare", "bare", "bare/${region}/${dt}/",
|
||||
"bare/eu/2026-03-14/part.parquet", "bare/us/2026-03-15/part.parquet",
|
||||
"bare/eu/latest/part.parquet");
|
||||
|
||||
List<Map<String, String>> rows = query("SELECT region, CAST(dt AS VARCHAR) AS dt "
|
||||
+ "FROM " + view("sales_bare") + " ORDER BY region");
|
||||
|
||||
assertEquals(List.of(Map.of("region", "eu", "dt", "2026-03-14"),
|
||||
Map.of("region", "us", "dt", "2026-03-15")), rows);
|
||||
assertEquals(EXPECTED_ROW, queryEuInMarch("sales_bare"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The Firehose layout AWS documents: one string key projected as a date whose format spans four
|
||||
* folders, behind a single placeholder. Athena (engine v3) reports the whole
|
||||
* {@code 2026/11/10/05} as its value.
|
||||
*/
|
||||
@Test
|
||||
void placeholderWhoseDateFormatSpansFoldersTakesEveryFolderAsItsValue() {
|
||||
Map<String, String> parameters = new LinkedHashMap<>();
|
||||
parameters.put("classification", "parquet");
|
||||
parameters.put("projection.enabled", "true");
|
||||
parameters.put("projection.datehour.type", "date");
|
||||
parameters.put("projection.datehour.format", "yyyy/MM/dd/HH");
|
||||
parameters.put("projection.datehour.range", "2026/01/01/00,NOW");
|
||||
parameters.put("projection.datehour.interval", "1");
|
||||
parameters.put("projection.datehour.interval.unit", "HOURS");
|
||||
parameters.put("storage.location.template", "s3://" + bucket + "/firehose/${datehour}/");
|
||||
register("sales_firehose", "firehose", parameters, List.of(column("datehour", "string")),
|
||||
"firehose/2026/11/10/05/part.parquet");
|
||||
|
||||
assertEquals(List.of(Map.of("id", "r1", "datehour", "2026/11/10/05")),
|
||||
query("SELECT id, datehour FROM " + view("sales_firehose")
|
||||
+ " WHERE datehour = '2026/11/10/05'"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A multi-folder date with more of the template after it. Reading it with one wildcard for the
|
||||
* date matched no object, which fails the view and with it every other view in the batch.
|
||||
*/
|
||||
@Test
|
||||
void dateSpanningFoldersFollowedByMoreOfTheTemplate() {
|
||||
Map<String, String> parameters = new LinkedHashMap<>();
|
||||
parameters.put("classification", "parquet");
|
||||
parameters.put("projection.enabled", "true");
|
||||
parameters.put("projection.dt.type", "date");
|
||||
parameters.put("projection.dt.format", "yyyy/MM/dd");
|
||||
parameters.put("projection.dt.range", "2026/01/01,NOW");
|
||||
parameters.put("projection.region.type", "injected");
|
||||
parameters.put("storage.location.template", "s3://" + bucket + "/nested/${dt}/region=${region}/");
|
||||
register("sales_nested", "nested", parameters,
|
||||
List.of(column("dt", "string"), column("region", "string")),
|
||||
"nested/2026/03/14/region=eu/part.parquet");
|
||||
|
||||
assertEquals(List.of(Map.of("id", "r1", "region", "eu", "dt", "2026/03/14")),
|
||||
query("SELECT id, region, dt FROM " + view("sales_nested") + " WHERE region = 'eu'"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Ten placeholders put {@code dt} at group 10, past what DuckDB's scalar {@code regexp_extract}
|
||||
* accepts. The keys before it need no projection type for the view, so they set none.
|
||||
*/
|
||||
@Test
|
||||
void templateWithTenPlaceholdersReadsTheTenth() {
|
||||
List<String> hierarchy = List.of("account", "team", "service", "env", "cluster", "zone", "rack", "host");
|
||||
Map<String, String> parameters = new LinkedHashMap<>();
|
||||
parameters.put("classification", "parquet");
|
||||
parameters.put("projection.enabled", "true");
|
||||
parameters.put("projection.region.type", "injected");
|
||||
parameters.put("projection.dt.type", "date");
|
||||
parameters.put("projection.dt.format", "yyyy-MM-dd");
|
||||
parameters.put("projection.dt.range", "2026-01-01,NOW");
|
||||
StringBuilder template = new StringBuilder("s3://" + bucket + "/deep/");
|
||||
List<Column> partitionKeys = new ArrayList<>();
|
||||
for (String key : hierarchy) {
|
||||
template.append("${").append(key).append("}/");
|
||||
partitionKeys.add(column(key, "string"));
|
||||
}
|
||||
parameters.put("storage.location.template", template + "${region}/${dt}/");
|
||||
partitionKeys.add(column("region", "string"));
|
||||
partitionKeys.add(column("dt", "date"));
|
||||
register("sales_deep", "deep", parameters, partitionKeys,
|
||||
"deep/a1/t1/s1/prod/c1/z1/r1/h1/eu/2026-03-14/part.parquet");
|
||||
|
||||
assertEquals(EXPECTED_ROW, queryEuInMarch("sales_deep"));
|
||||
}
|
||||
|
||||
// ---- helpers ----
|
||||
|
||||
/**
|
||||
* Uploads the Parquet file to each of {@code objectKeys} and declares a projecting table over
|
||||
* {@code root}, laid out by {@code template} (relative to the bucket) or by the default layout.
|
||||
*/
|
||||
private void table(String name, String root, String template, String... objectKeys) {
|
||||
Map<String, String> parameters = new LinkedHashMap<>();
|
||||
parameters.put("classification", "parquet");
|
||||
parameters.put("projection.enabled", "true");
|
||||
parameters.put("projection.region.type", "injected");
|
||||
parameters.put("projection.dt.type", "date");
|
||||
parameters.put("projection.dt.format", "yyyy-MM-dd");
|
||||
parameters.put("projection.dt.range", "2026-01-01,NOW");
|
||||
if (template != null) {
|
||||
parameters.put("storage.location.template", "s3://" + bucket + "/" + template);
|
||||
}
|
||||
register(name, root, parameters, List.of(column("region", "string"), column("dt", "date")), objectKeys);
|
||||
}
|
||||
|
||||
/** Uploads the Parquet file to each of {@code objectKeys} and declares a table over {@code root}. */
|
||||
private void register(String name, String root, Map<String, String> parameters, List<Column> partitionKeys,
|
||||
String... objectKeys) {
|
||||
for (String key : objectKeys) {
|
||||
s3Service.putObject(bucket, key, PARQUET, "application/octet-stream", null);
|
||||
keys.add(key);
|
||||
}
|
||||
StorageDescriptor descriptor = new StorageDescriptor();
|
||||
descriptor.setLocation("s3://" + bucket + "/" + root + "/");
|
||||
descriptor.setInputFormat("org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat");
|
||||
StorageDescriptor.SerDeInfo serde = new StorageDescriptor.SerDeInfo();
|
||||
serde.setSerializationLibrary("org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe");
|
||||
descriptor.setSerdeInfo(serde);
|
||||
descriptor.setColumns(List.of(column("id", "string"), column("status", "string")));
|
||||
Table table = new Table();
|
||||
table.setName(name);
|
||||
table.setStorageDescriptor(descriptor);
|
||||
table.setPartitionKeys(partitionKeys);
|
||||
table.setParameters(parameters);
|
||||
tables.add(table);
|
||||
}
|
||||
|
||||
/** A typical projected-partition query, with the equality filter an injected key requires. */
|
||||
private List<Map<String, String>> queryEuInMarch(String table) {
|
||||
return query("SELECT id, region, CAST(dt AS VARCHAR) AS dt FROM " + view(table)
|
||||
+ " WHERE region = 'eu' AND dt BETWEEN DATE '2026-03-01' AND DATE '2026-03-31'");
|
||||
}
|
||||
|
||||
private List<Map<String, String>> query(String sql) {
|
||||
GlueService glue = Mockito.mock(GlueService.class);
|
||||
Database database = new Database();
|
||||
database.setName(schema);
|
||||
when(glue.getDatabases()).thenReturn(List.of(database));
|
||||
when(glue.getTables(schema)).thenReturn(tables);
|
||||
String views = new GlueViewDdlBuilder(glue).build(null);
|
||||
|
||||
List<Map<String, String>> rows = new ArrayList<>();
|
||||
for (Map<String, Object> row : duck.query(sql, views)) {
|
||||
Map<String, String> values = new LinkedHashMap<>();
|
||||
row.forEach((column, value) -> values.put(column, String.valueOf(value)));
|
||||
rows.add(values);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
private String view(String table) {
|
||||
return "\"" + schema + "\".\"" + table + "\"";
|
||||
}
|
||||
|
||||
private static Column column(String name, String type) {
|
||||
Column column = new Column();
|
||||
column.setName(name);
|
||||
column.setType(type);
|
||||
return column;
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -131,6 +132,102 @@ class GlueViewDdlBuilderTest {
|
||||
assertTrue(ddl.contains("\"we\"\"ird\" AS \"we\"\"ird\""), ddl);
|
||||
}
|
||||
|
||||
private static Column column(String name, String type) {
|
||||
Column c = column(name);
|
||||
c.setType(type);
|
||||
return c;
|
||||
}
|
||||
|
||||
private Table projectingParquetTable(String location, Map<String, String> parameters) {
|
||||
Table table = createTable("events", location, "org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe",
|
||||
"org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat");
|
||||
table.getStorageDescriptor().setColumns(List.of(column("id")));
|
||||
table.setPartitionKeys(List.of(column("region", "string"), column("dt", "date")));
|
||||
table.setParameters(parameters);
|
||||
return table;
|
||||
}
|
||||
|
||||
/**
|
||||
* A template of bare values, one folder per key. The files hold no partition columns, so each
|
||||
* value comes from the object's path, through the template, as Athena maps it; without this the
|
||||
* view selects columns nothing defines and DuckDB rejects it.
|
||||
*/
|
||||
@Test
|
||||
void templatedPartitionKeysAreTakenFromTheObjectPath() {
|
||||
String ddl = ddlFor(projectingParquetTable("s3://b/data/", Map.of("projection.enabled", "true",
|
||||
"storage.location.template", "s3://b/data/${region}/${dt}/")));
|
||||
|
||||
String regex = "'^s3://b/data/([^/]+)/([^/]+)/'";
|
||||
assertEquals("CREATE SCHEMA IF NOT EXISTS \"audit\";\n"
|
||||
+ "CREATE OR REPLACE VIEW \"audit\".\"events\" AS SELECT \"id\" AS \"id\", "
|
||||
+ "regexp_extract(\"$path\", " + regex + ", 1) AS \"region\", "
|
||||
+ "TRY_CAST(regexp_extract(\"$path\", " + regex + ", 2) AS DATE) AS \"dt\" "
|
||||
+ "FROM read_parquet('s3://b/data/*/*/**', union_by_name = true, hive_partitioning = false, "
|
||||
+ "filename = '$path') "
|
||||
+ "WHERE regexp_matches(\"$path\", " + regex + ") "
|
||||
+ "AND TRY_CAST(regexp_extract(\"$path\", " + regex + ", 2) AS DATE) IS NOT NULL;\n", ddl);
|
||||
}
|
||||
|
||||
/** RE2 has no backreferences, so a repeated placeholder's occurrences are compared in the view. */
|
||||
@Test
|
||||
void repeatedPlaceholderMustHoldTheSameValueAtEachOccurrence() {
|
||||
String ddl = ddlFor(projectingParquetTable("s3://b/repeat/", Map.of("projection.enabled", "true",
|
||||
"storage.location.template", "s3://b/repeat/${region}/${dt}/${region}/")));
|
||||
|
||||
String regex = "'^s3://b/repeat/([^/]+)/([^/]+)/([^/]+)/'";
|
||||
assertTrue(ddl.contains("regexp_extract(\"$path\", " + regex + ", 1) = "
|
||||
+ "regexp_extract(\"$path\", " + regex + ", 3)"), ddl);
|
||||
}
|
||||
|
||||
/**
|
||||
* A template omitting a partition key leaves that key with nothing to bind to, and one view
|
||||
* failing to bind fails the whole batch. Athena fails only queries on the table, so the table
|
||||
* gets no view and its neighbours are still built.
|
||||
*/
|
||||
@Test
|
||||
void tableWhoseTemplateOmitsAPartitionKeyGetsNoViewAndLeavesOthersBuilt() {
|
||||
Table incomplete = projectingParquetTable("s3://b/missing/", Map.of("projection.enabled", "true",
|
||||
"storage.location.template", "s3://b/missing/${region}/"));
|
||||
Table healthy = tableWithColumns("healthy", "s3://b/healthy/", List.of(column("id")), null);
|
||||
Database db = createDatabase("audit");
|
||||
when(glueService.getDatabases()).thenReturn(List.of(db));
|
||||
when(glueService.getTables("audit")).thenReturn(List.of(incomplete, healthy));
|
||||
|
||||
String ddl = builder.build(null);
|
||||
|
||||
assertFalse(ddl.contains("\"events\""), ddl);
|
||||
assertTrue(ddl.contains("CREATE OR REPLACE VIEW \"audit\".\"healthy\""), ddl);
|
||||
}
|
||||
|
||||
/** An Iceberg table reads through its metadata, so a template omitting a key costs it no view. */
|
||||
@Test
|
||||
void icebergTableWithAnIncompleteTemplateKeepsItsView() {
|
||||
Table table = icebergTable("orders", "s3://bucket/warehouse/orders",
|
||||
"s3://bucket/warehouse/orders/metadata/00001-abc.metadata.json");
|
||||
table.setPartitionKeys(List.of(column("region", "string"), column("dt", "date")));
|
||||
Map<String, String> parameters = new HashMap<>(table.getParameters());
|
||||
parameters.put("projection.enabled", "true");
|
||||
parameters.put("storage.location.template", "s3://bucket/warehouse/orders/${region}/");
|
||||
table.setParameters(parameters);
|
||||
|
||||
String ddl = ddlFor(table);
|
||||
|
||||
assertTrue(ddl.contains("CREATE OR REPLACE VIEW \"audit\".\"orders\" AS SELECT \"region\" AS \"region\", "
|
||||
+ "\"dt\" AS \"dt\" FROM iceberg_scan('s3://bucket/warehouse/orders/metadata/00001-abc.metadata.json');\n"),
|
||||
ddl);
|
||||
}
|
||||
|
||||
/** The default column=value layout is left to DuckDB's Hive partitioning, as before. */
|
||||
@Test
|
||||
void defaultLayoutStillReadsPartitionValuesThroughHivePartitioning() {
|
||||
String ddl = ddlFor(projectingParquetTable("s3://b/hive/", Map.of("projection.enabled", "true")));
|
||||
|
||||
assertEquals("CREATE SCHEMA IF NOT EXISTS \"audit\";\n"
|
||||
+ "CREATE OR REPLACE VIEW \"audit\".\"events\" AS SELECT \"id\" AS \"id\", "
|
||||
+ "\"region\" AS \"region\", \"dt\" AS \"dt\" "
|
||||
+ "FROM read_parquet('s3://b/hive/region=*/dt=*/**', union_by_name = true);\n", ddl);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testTwoDatabasesQualifiedViewsAndSchemaPerDb() {
|
||||
Database shopDb = createDatabase("shop");
|
||||
|
||||
@@ -13,6 +13,7 @@ import static org.hamcrest.Matchers.contains;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class GlueTableResolverTest {
|
||||
@@ -129,6 +130,82 @@ class GlueTableResolverTest {
|
||||
assertThat(GlueTableResolver.buildProjection(table), equalTo("\"tenantId\" AS \"tenantId\""));
|
||||
}
|
||||
|
||||
private static Table templatedTable(String template, Column... partitionKeys) {
|
||||
Table table = table("org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat", "s3://bucket/events/",
|
||||
List.of(column("id", "string")));
|
||||
table.setPartitionKeys(List.of(partitionKeys));
|
||||
table.setParameters(Map.of("projection.enabled", "true", "storage.location.template", template));
|
||||
return table;
|
||||
}
|
||||
|
||||
/** A string key is the matched text itself; any other type is cast, so a non-value yields NULL, not an error. */
|
||||
@Test
|
||||
void templatedKeysAreCastToTheirDeclaredTypes() {
|
||||
Table table = templatedTable("s3://bucket/events/${region}/${year}/${dt}/",
|
||||
column("region", "string"), column("year", "int"), column("dt", "date"));
|
||||
|
||||
String regex = "'^s3://bucket/events/([^/]+)/([^/]+)/([^/]+)/'";
|
||||
assertThat(GlueTableResolver.buildProjection(table), equalTo("\"id\" AS \"id\", "
|
||||
+ "regexp_extract(\"$path\", " + regex + ", 1) AS \"region\", "
|
||||
+ "TRY_CAST(regexp_extract(\"$path\", " + regex + ", 2) AS INTEGER) AS \"year\", "
|
||||
+ "TRY_CAST(regexp_extract(\"$path\", " + regex + ", 3) AS DATE) AS \"dt\""));
|
||||
assertThat(GlueTableResolver.pathFilter(table), equalTo("regexp_matches(\"$path\", " + regex + ")"
|
||||
+ " AND TRY_CAST(regexp_extract(\"$path\", " + regex + ", 2) AS INTEGER) IS NOT NULL"
|
||||
+ " AND TRY_CAST(regexp_extract(\"$path\", " + regex + ", 3) AS DATE) IS NOT NULL"));
|
||||
}
|
||||
|
||||
/**
|
||||
* DuckDB's scalar {@code regexp_extract} stops at group 9, so a key at group 10 is read through
|
||||
* the struct form, and the keys before it keep the scalar form.
|
||||
*/
|
||||
@Test
|
||||
void aKeyPastTheNinthGroupIsExtractedThroughTheStructForm() {
|
||||
Table table = templatedTable("s3://bucket/events/${account}/${team}/${service}/${env}/${cluster}/"
|
||||
+ "${zone}/${rack}/${host}/${region}/${dt}/",
|
||||
column("account", "string"), column("team", "string"), column("service", "string"),
|
||||
column("env", "string"), column("cluster", "string"), column("zone", "string"),
|
||||
column("rack", "string"), column("host", "string"), column("region", "string"),
|
||||
column("dt", "date"));
|
||||
|
||||
String regex = "'^s3://bucket/events/" + "([^/]+)/".repeat(10) + "'";
|
||||
String projection = GlueTableResolver.buildProjection(table);
|
||||
assertThat(projection, containsString("regexp_extract(\"$path\", " + regex + ", 9) AS \"region\""));
|
||||
assertThat(projection, containsString("TRY_CAST(regexp_extract(\"$path\", " + regex + ", "
|
||||
+ "['g1', 'g2', 'g3', 'g4', 'g5', 'g6', 'g7', 'g8', 'g9', 'g10']).g10 AS DATE) AS \"dt\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void templatedReadAddsTheObjectPathAndTurnsOffHivePartitioning() {
|
||||
Table table = templatedTable("s3://bucket/events/${region}/", column("region", "string"));
|
||||
|
||||
assertThat(GlueTableResolver.readExpression(table, "read_json_auto", "s3://bucket/events/*"),
|
||||
equalTo("read_json_auto('s3://bucket/events/*/**', hive_partitioning = false, filename = '$path')"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void singleQuotesInTheTemplateAreEscapedInTheRegexLiteral() {
|
||||
Table table = templatedTable("s3://bucket/o'brien/${region}/", column("region", "string"));
|
||||
|
||||
assertThat(GlueTableResolver.pathFilter(table), equalTo("regexp_matches(\"$path\", '^s3://bucket/o''brien/([^/]+)/')"));
|
||||
}
|
||||
|
||||
/** Tables without a template read and project exactly as they did, and an Iceberg table ignores one. */
|
||||
@Test
|
||||
void tablesWithoutATemplateAreReadAsBefore() {
|
||||
Table plain = table("org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat", "s3://bucket/events/",
|
||||
List.of(column("id", "string")));
|
||||
Table iceberg = templatedTable("s3://bucket/events/${region}/", column("region", "string"));
|
||||
iceberg.setParameters(Map.of("projection.enabled", "true", "table_type", "ICEBERG",
|
||||
"storage.location.template", "s3://bucket/events/${region}/"));
|
||||
|
||||
for (Table table : List.of(plain, iceberg)) {
|
||||
assertThat(GlueTableResolver.readExpression(table, "read_parquet", "s3://bucket/events"),
|
||||
equalTo("read_parquet('s3://bucket/events/**', union_by_name = true)"));
|
||||
assertThat(GlueTableResolver.pathFilter(table), is(nullValue()));
|
||||
}
|
||||
assertThat(GlueTableResolver.buildProjection(iceberg), equalTo("\"id\" AS \"id\", \"region\" AS \"region\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void isIcebergTableFalseWhenParametersMissing() {
|
||||
assertThat(GlueTableResolver.isIcebergTable(new Table()), is(false));
|
||||
|
||||
@@ -7,12 +7,15 @@ import io.floci.aws.services.glue.model.Table;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@@ -95,6 +98,185 @@ class PartitionProjectionTest {
|
||||
assertEquals(BUCKET + "/tenant=*", PartitionProjection.readPath(t, BUCKET));
|
||||
}
|
||||
|
||||
// ---- location template ----
|
||||
|
||||
private static Table templated(String template, String... keys) {
|
||||
return table("audit_events", projecting("storage.location.template", template),
|
||||
Arrays.stream(keys).map(PartitionProjectionTest::column).toList());
|
||||
}
|
||||
|
||||
/** Bare values, one folder per placeholder. */
|
||||
@Test
|
||||
void templateWithBareValuesCapturesOneSegmentPerKey() {
|
||||
PartitionProjection.LocationTemplate template = PartitionProjection.locationTemplate(
|
||||
templated(BUCKET + "/data/${region}/${dt}/", "region", "dt"));
|
||||
|
||||
assertEquals("^s3://audit-logs/data/([^/]+)/([^/]+)/", template.regex());
|
||||
assertEquals(Map.of("region", List.of(1), "dt", List.of(2)), template.groups());
|
||||
}
|
||||
|
||||
/** From the AWS docs' examples: literal {@code col=} prefixes and static folders around placeholders. */
|
||||
@Test
|
||||
void templateKeepsLiteralSegmentsAroundThePlaceholders() {
|
||||
PartitionProjection.LocationTemplate template = PartitionProjection.locationTemplate(
|
||||
templated(BUCKET + "/table_root/a=${a}/${b}/some_static_subdirectory/", "a", "b"));
|
||||
|
||||
assertEquals("^s3://audit-logs/table_root/a=([^/]+)/([^/]+)/some_static_subdirectory/", template.regex());
|
||||
assertEquals(Map.of("a", List.of(1), "b", List.of(2)), template.groups());
|
||||
}
|
||||
|
||||
/** Also from the AWS docs: a placeholder may repeat, and every occurrence is reported. */
|
||||
@Test
|
||||
void repeatedPlaceholderReportsEachOfItsGroups() {
|
||||
PartitionProjection.LocationTemplate template = PartitionProjection.locationTemplate(
|
||||
templated(BUCKET + "/${region}/${dt}/${region}/", "region", "dt"));
|
||||
|
||||
assertEquals("^s3://audit-logs/([^/]+)/([^/]+)/([^/]+)/", template.regex());
|
||||
assertEquals(Map.of("region", List.of(1, 3), "dt", List.of(2)), template.groups());
|
||||
}
|
||||
|
||||
/** Without a trailing slash the last placeholder still ends at a folder boundary, as readPath reads it. */
|
||||
@Test
|
||||
void templateWithoutTrailingSlashStillEndsAtAFolder() {
|
||||
PartitionProjection.LocationTemplate template = PartitionProjection.locationTemplate(
|
||||
templated(BUCKET + "/events/${dt}", "dt"));
|
||||
|
||||
assertEquals("^s3://audit-logs/events/([^/]+)/", template.regex());
|
||||
}
|
||||
|
||||
@Test
|
||||
void regexMetacharactersInTheTemplateAreLiteral() {
|
||||
PartitionProjection.LocationTemplate template = PartitionProjection.locationTemplate(
|
||||
templated("s3://data.lake/v1+(beta)/${region}/", "region"));
|
||||
|
||||
assertEquals("^s3://data\\.lake/v1\\+\\(beta\\)/([^/]+)/", template.regex());
|
||||
}
|
||||
|
||||
/**
|
||||
* A placeholder naming no partition key is still a wildcard in the read path, so it keeps its
|
||||
* group and the keys after it are numbered past it. Placeholder names match keys case-insensitively.
|
||||
*/
|
||||
@Test
|
||||
void placeholderNamingNoKeyStillTakesAGroup() {
|
||||
PartitionProjection.LocationTemplate template = PartitionProjection.locationTemplate(
|
||||
templated(BUCKET + "/${zone}/${Region}/", "region"));
|
||||
|
||||
assertEquals("^s3://audit-logs/([^/]+)/([^/]+)/", template.regex());
|
||||
assertEquals(Map.of("region", List.of(2)), template.groups());
|
||||
}
|
||||
|
||||
@Test
|
||||
void noLocationTemplateWithoutATemplateProjectionOrAKeyItNames() {
|
||||
assertNull(PartitionProjection.locationTemplate(table("t", projecting(), List.of(column("region")))));
|
||||
assertNull(PartitionProjection.locationTemplate(table("t",
|
||||
Map.of("storage.location.template", BUCKET + "/${region}/"), List.of(column("region")))));
|
||||
assertNull(PartitionProjection.locationTemplate(templated(BUCKET + "/${zone}/", "region")));
|
||||
assertNull(PartitionProjection.locationTemplate(templated(BUCKET + "/${region}/")));
|
||||
}
|
||||
|
||||
/**
|
||||
* The Firehose layout AWS documents: a date projection whose format holds slashes stands for that
|
||||
* many more folders behind one placeholder, and the group spans them all.
|
||||
*/
|
||||
@Test
|
||||
void dateFormatWithSlashesWidensItsGroupToEveryFolderItSpans() {
|
||||
Table t = table("firehose", projecting(
|
||||
"storage.location.template", BUCKET + "/prefix/${datehour}/",
|
||||
"projection.datehour.type", "date",
|
||||
"projection.datehour.format", "yyyy/MM/dd/HH"),
|
||||
List.of(column("datehour")));
|
||||
|
||||
PartitionProjection.LocationTemplate template = PartitionProjection.locationTemplate(t);
|
||||
|
||||
assertEquals("^s3://audit-logs/prefix/([^/]+(?:/[^/]+)(?:/[^/]+)(?:/[^/]+))/", template.regex());
|
||||
assertEquals(Map.of("datehour", List.of(1)), template.groups());
|
||||
}
|
||||
|
||||
/**
|
||||
* A multi-folder date followed by more of the template: the read path needs a wildcard per folder
|
||||
* the date spans, or it looks for {@code region=} right after the year and matches no object.
|
||||
*/
|
||||
@Test
|
||||
void readPathAndRegexGiveAMultiFolderDateTheSameFolders() {
|
||||
Table t = table("orders", projecting(
|
||||
"storage.location.template", BUCKET + "/orders/${dt}/region=${region}/",
|
||||
"projection.dt.type", "date",
|
||||
"projection.dt.format", "yyyy/MM/dd"),
|
||||
List.of(column("dt"), column("region")));
|
||||
|
||||
assertEquals(BUCKET + "/orders/*/*/*/region=*", PartitionProjection.readPath(t, BUCKET));
|
||||
assertEquals("^s3://audit-logs/orders/([^/]+(?:/[^/]+)(?:/[^/]+))/region=([^/]+)/",
|
||||
PartitionProjection.locationTemplate(t).regex());
|
||||
}
|
||||
|
||||
/** Only a date projection's format describes the value's shape; other types keep one folder. */
|
||||
@Test
|
||||
void slashesInTheFormatOfANonDateProjectionDoNotWidenItsGroup() {
|
||||
Table t = table("t", projecting(
|
||||
"storage.location.template", BUCKET + "/${region}/",
|
||||
"projection.region.type", "enum",
|
||||
"projection.region.format", "a/b"),
|
||||
List.of(column("region")));
|
||||
|
||||
assertEquals("^s3://audit-logs/([^/]+)/", PartitionProjection.locationTemplate(t).regex());
|
||||
}
|
||||
|
||||
// ---- incomplete location template ----
|
||||
|
||||
@Test
|
||||
void templateOmittingAPartitionKeyIsIncompleteAndHasNoLocationTemplate() {
|
||||
Table t = templated(BUCKET + "/missing/${tenant}/", "tenant", "dt");
|
||||
|
||||
assertTrue(PartitionProjection.hasIncompleteLocationTemplate(t));
|
||||
assertNull(PartitionProjection.locationTemplate(t));
|
||||
}
|
||||
|
||||
@Test
|
||||
void templateNamingEveryKeyOrNoTemplateAtAllIsNotIncomplete() {
|
||||
assertFalse(PartitionProjection.hasIncompleteLocationTemplate(
|
||||
templated(BUCKET + "/${Tenant}/${dt}/", "tenant", "DT")));
|
||||
assertFalse(PartitionProjection.hasIncompleteLocationTemplate(
|
||||
table("t", projecting(), List.of(column("tenant")))));
|
||||
assertFalse(PartitionProjection.hasIncompleteLocationTemplate(
|
||||
table("t", Map.of("storage.location.template", BUCKET + "/x/"), List.of(column("tenant")))));
|
||||
}
|
||||
|
||||
/** An Iceberg table is read through its metadata, so a template it carries is never checked. */
|
||||
@Test
|
||||
void icebergTableWithAnIncompleteTemplateIsNotIncomplete() {
|
||||
Map<String, String> params = projecting("storage.location.template", BUCKET + "/missing/${tenant}/");
|
||||
params.put("table_type", "ICEBERG");
|
||||
Table t = table("audit_events", params, List.of(column("tenant"), column("dt")));
|
||||
|
||||
assertFalse(PartitionProjection.hasIncompleteLocationTemplate(t));
|
||||
assertDoesNotThrow(() -> PartitionProjection.assertLocationTemplatesComplete(
|
||||
"SELECT * FROM audit_events", List.of(t)));
|
||||
}
|
||||
|
||||
/** Athena's message, as captured from engine v3, for a query reading the table. */
|
||||
@Test
|
||||
void queryReadingATableWithAnIncompleteTemplateFailsAsAthenaDoes() {
|
||||
Table t = templated(BUCKET + "/missing/${tenant}/", "tenant", "dt");
|
||||
t.setDatabaseName("audit");
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () ->
|
||||
PartitionProjection.assertLocationTemplatesComplete(
|
||||
"SELECT * FROM audit_events WHERE tenant = 'a'", List.of(t)));
|
||||
|
||||
assertEquals("INVALID_TABLE_PROPERTY: The 'storage.location.template' table property must contain "
|
||||
+ "templates for all partition columns! Table: audit.audit_events Template: "
|
||||
+ BUCKET + "/missing/${tenant}/", e.getMessage());
|
||||
}
|
||||
|
||||
/** Athena keeps the database's other tables queryable, so a query not reading the table passes. */
|
||||
@Test
|
||||
void queryNotReadingTheTableWithAnIncompleteTemplateIsAccepted() {
|
||||
Table t = templated(BUCKET + "/missing/${tenant}/", "tenant", "dt");
|
||||
|
||||
assertDoesNotThrow(() -> PartitionProjection.assertLocationTemplatesComplete(
|
||||
"SELECT * FROM other_events WHERE note = 'audit_events'", List.of(t)));
|
||||
}
|
||||
|
||||
// ---- injected columns ----
|
||||
|
||||
private Table injectedTenantTable() {
|
||||
|
||||
Reference in new issue
Block a user