mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -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
+15
-1
@@ -112,7 +112,7 @@ results storage.
|
||||
## How it works
|
||||
|
||||
1. **Lazy sidecar start**: On the first `StartQueryExecution` call, Floci checks for a local `floci/floci-duck:latest` image and starts the container. Subsequent queries reuse the running container.
|
||||
2. **Glue DDL injection**: Floci registers every Glue database as a DuckDB schema (`CREATE SCHEMA IF NOT EXISTS "<schema>"`) and creates qualified views (`CREATE OR REPLACE VIEW "<db>"."<table>"`) mapping each table to its S3 location via DuckDB's `read_parquet`, `read_json_auto`, or `read_csv_auto` functions, chosen based on the table's `InputFormat` or SerDe serialization library. In addition, tables in the query context database receive unqualified view aliases (`CREATE OR REPLACE VIEW "<table>"` in DuckDB's default `main` schema), so queries can reference tables as both `FROM db.table` and `FROM table`.
|
||||
2. **Glue DDL injection**: Floci registers every Glue database as a DuckDB schema (`CREATE SCHEMA IF NOT EXISTS "<schema>"`) and creates qualified views (`CREATE OR REPLACE VIEW "<db>"."<table>"`) mapping each table to its S3 location via DuckDB's `read_parquet`, `read_json_auto`, or `read_csv_auto` functions, chosen based on the table's `InputFormat` or SerDe serialization library (a table with partition projection reads only its partition folders; see [Partition projection](#partition-projection)). In addition, tables in the query context database receive unqualified view aliases (`CREATE OR REPLACE VIEW "<table>"` in DuckDB's default `main` schema), so queries can reference tables as both `FROM db.table` and `FROM table`.
|
||||
3. **Query execution**: The user's SQL is wrapped in `COPY (...) TO 's3://...' (FORMAT CSV, HEADER)` and executed. Results are written directly to the output S3 path.
|
||||
4. **Results retrieval**: `GetQueryResults` reads the CSV back from S3 and returns it in the standard Athena `ResultSet` shape. Each column's `Type` comes from DuckDB describing the query, mapped to the Athena name (`bigint`, `integer`, `double`, `boolean`, `date`, `time`, `timestamp`, `decimal` and so on), with `Precision` and `Scale` for a decimal; a column whose type has no Athena name, such as an interval, and every column of a query DuckDB cannot describe are reported as `varchar`. DuckDB widens `sum` and `count_if` over integers to `HUGEINT`, which is reported as `bigint`, Trino's type for them; a sum past `bigint`'s range, which Athena fails with `NUMERIC_VALUE_OUT_OF_RANGE`, is returned instead.
|
||||
|
||||
@@ -129,6 +129,20 @@ For every other table, the DuckDB read function is chosen from the Glue table's
|
||||
| `InputFormat` contains `hive` | `read_json_auto` |
|
||||
| Anything else | `read_csv_auto` |
|
||||
|
||||
## Partition projection
|
||||
|
||||
A Glue table with `projection.enabled` set to `true` is read the way Athena reads it, from its partition layout rather than from its whole location:
|
||||
|
||||
- **Read path**: only the partition folders are read, `<location>/<key>=*/...` in the default `column=value` layout, or the `storage.location.template` with each `${key}` placeholder as a wildcard (one per folder, for a `date` format that holds slashes). Anything else stored under the location, such as query results, is not read as table data.
|
||||
- **Partition values**: in the default layout, DuckDB's Hive partitioning supplies each key's value. With a template, the view takes each value from the object's S3 path by matching it against the template, and casts it to the key's declared type. A `date` projection whose `format` holds slashes (`yyyy/MM/dd/HH`, the Firehose layout) spans that many folders behind one placeholder. A repeated placeholder must hold the same value at each occurrence, and an object whose path value does not parse as its key's type is not read.
|
||||
- **Validation**: as on Athena, a query fails when it leaves an `injected` key without a static equality condition in its `WHERE` clause (`CONSTRAINT_VIOLATION`), or when it reads a table whose template has no placeholder for one of its keys (`INVALID_TABLE_PROPERTY`). Such a table gets no view, so the other tables stay queryable.
|
||||
|
||||
Not yet supported:
|
||||
|
||||
- Values outside the projection (a date before the range or after `NOW`, an unlisted `enum` value) are read; Athena returns zero rows for them.
|
||||
- A `date` or `timestamp` key with a `format` other than ISO is not parsed, so its objects are not read.
|
||||
- The object path backs the template's values but is not exposed: Athena's `"$path"` pseudo-column cannot be selected.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Property | Default | Description |
|
||||
|
||||
@@ -186,9 +186,12 @@ public class AthenaService {
|
||||
|
||||
// Submit async — caller gets the ID immediately while execution runs in background
|
||||
vertx.executeBlocking(() -> {
|
||||
// Athena rejects a query that leaves an injected partition column unconstrained. It fails
|
||||
// the query rather than the submission, which is what throwing here produces.
|
||||
PartitionProjection.assertInjectedColumnsFiltered(query, tablesForProjectionCheck(database));
|
||||
// Athena fails a query that reads a table with an incomplete location template, or that
|
||||
// leaves an injected partition column unconstrained. It fails the query rather than the
|
||||
// submission, which is what throwing here produces.
|
||||
List<Table> projectionTables = tablesForProjectionCheck(database);
|
||||
PartitionProjection.assertLocationTemplatesComplete(query, projectionTables);
|
||||
PartitionProjection.assertInjectedColumnsFiltered(query, projectionTables);
|
||||
String setupDdl = ddlBuilder.build(database);
|
||||
if (outputLocation != null) {
|
||||
ensureOutputBucket(outputLocation);
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.floci.aws.services.athena;
|
||||
|
||||
import io.floci.aws.services.glue.GlueService;
|
||||
import io.floci.aws.services.glue.GlueTableResolver;
|
||||
import io.floci.aws.services.glue.PartitionProjection;
|
||||
import io.floci.aws.services.glue.model.Database;
|
||||
import io.floci.aws.services.glue.model.Table;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
@@ -92,6 +93,14 @@ public class GlueViewDdlBuilder {
|
||||
|| t.getStorageDescriptor().getLocation().isBlank()) {
|
||||
continue;
|
||||
}
|
||||
// Athena fails every query on such a table, and only those (AthenaService checks
|
||||
// for it). A view can't bind the key the template omits, and one view failing to
|
||||
// bind fails the whole batch, so the table gets none.
|
||||
if (PartitionProjection.hasIncompleteLocationTemplate(t)) {
|
||||
LOG.debugv("skip Glue table {0}.{1}: storage.location.template omits a partition key",
|
||||
schemaOrNull, t.getName());
|
||||
continue;
|
||||
}
|
||||
String location = t.getStorageDescriptor().getLocation();
|
||||
String normalizedLocation = location.endsWith("/")
|
||||
? location.substring(0, location.length() - 1)
|
||||
@@ -107,15 +116,19 @@ public class GlueViewDdlBuilder {
|
||||
} else {
|
||||
String readFn = GlueTableResolver.inferReadFunction(t);
|
||||
String readPath = GlueTableResolver.readPath(t, normalizedLocation);
|
||||
fromClause = GlueTableResolver.readExpression(readFn, readPath);
|
||||
fromClause = GlueTableResolver.readExpression(t, readFn, readPath);
|
||||
}
|
||||
sb.append("CREATE OR REPLACE VIEW ")
|
||||
.append(target)
|
||||
.append(" AS SELECT ")
|
||||
.append(GlueTableResolver.buildProjection(t))
|
||||
.append(" FROM ")
|
||||
.append(fromClause)
|
||||
.append(";\n");
|
||||
.append(fromClause);
|
||||
String pathFilter = GlueTableResolver.pathFilter(t);
|
||||
if (pathFilter != null) {
|
||||
sb.append(" WHERE ").append(pathFilter);
|
||||
}
|
||||
sb.append(";\n");
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("skip Glue table {0}.{1}: {2}", schemaOrNull, t != null ? t.getName() : "unknown", e.getMessage());
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
@@ -34,6 +35,18 @@ public final class GlueTableResolver {
|
||||
/** Hive table property naming how many header lines a delimited file carries. */
|
||||
private static final String PARAM_SKIP_HEADER = "skip.header.line.count";
|
||||
|
||||
/**
|
||||
* The column a templated table's read adds to carry each row's object path, from which its
|
||||
* partition values are taken. Named after Athena's own {@code "$path"} pseudo-column, a name no
|
||||
* data column takes; the view's explicit projection leaves it out.
|
||||
*/
|
||||
private static final String OBJECT_PATH_COLUMN = "$path";
|
||||
|
||||
/** The largest group index DuckDB's scalar {@code regexp_extract} accepts. */
|
||||
private static final int MAX_SCALAR_GROUP = 9;
|
||||
|
||||
private static final Pattern DECIMAL_TYPE = Pattern.compile("decimal\\(\\s*\\d+\\s*,\\s*\\d+\\s*\\)");
|
||||
|
||||
private GlueTableResolver() {
|
||||
}
|
||||
|
||||
@@ -205,6 +218,10 @@ public final class GlueTableResolver {
|
||||
* <p>Partition keys are part of the table's schema and are what partition predicates filter on,
|
||||
* so they are projected too. A table that declares no columns keeps {@code *}, leaving inference
|
||||
* in charge.
|
||||
*
|
||||
* <p>Partition values are not stored in the data files. In the default {@code column=value}
|
||||
* layout DuckDB's Hive partitioning supplies them by name; with a {@code storage.location.template}
|
||||
* each one is taken from the object's path instead, as Athena does, and cast to the key's type.
|
||||
*/
|
||||
public static String buildProjection(Table table) {
|
||||
List<Column> declared = declaredColumns(table);
|
||||
@@ -225,16 +242,140 @@ public final class GlueTableResolver {
|
||||
return "*";
|
||||
}
|
||||
|
||||
PartitionProjection.LocationTemplate template = locationTemplate(table);
|
||||
Map<String, Column> templatedKeys = templatedKeys(table, template);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < names.size(); i++) {
|
||||
if (i > 0) {
|
||||
sb.append(", ");
|
||||
}
|
||||
sb.append(quote(names.get(i))).append(" AS ").append(quote(names.get(i)));
|
||||
String name = names.get(i);
|
||||
Column key = templatedKeys.get(name.toLowerCase(Locale.ROOT));
|
||||
String value = key == null ? quote(name) : partitionValue(template, key);
|
||||
sb.append(value).append(" AS ").append(quote(name));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* The condition a templated table's view keeps rows by, or {@code null} for any other table: that
|
||||
* the object's path is one Athena could address through the template.
|
||||
*
|
||||
* <p>Athena never lists a projecting table's location; it builds each partition's path from
|
||||
* values and reads what is there. An object is therefore visible only if some values produce its
|
||||
* path: the path matches the template, a repeated placeholder holds the same value at each
|
||||
* occurrence, and each typed key's value parses as that type. The read glob is wider on all three
|
||||
* counts, so the view narrows it back.
|
||||
*
|
||||
* <p>TODO: Athena also reads only the values the projection generates ("queries for values that
|
||||
* are beyond the range bounds defined for partition projection ... [return] zero rows"), so an
|
||||
* object at a date before the range, after {@code NOW}, off the {@code interval}, an integer
|
||||
* without its {@code digits} padding, or an {@code enum} value not listed is invisible to it but
|
||||
* read here. The default {@code column=value} layout reads them too; filtering on the projection's
|
||||
* values would fix both.
|
||||
*/
|
||||
public static String pathFilter(Table table) {
|
||||
PartitionProjection.LocationTemplate template = locationTemplate(table);
|
||||
if (template == null) {
|
||||
return null;
|
||||
}
|
||||
List<String> terms = new ArrayList<>();
|
||||
terms.add("regexp_matches(" + quote(OBJECT_PATH_COLUMN) + ", '" + escape(template.regex()) + "')");
|
||||
for (Column key : templatedKeys(table, template).values()) {
|
||||
List<Integer> groups = template.groups().get(key.getName().toLowerCase(Locale.ROOT));
|
||||
for (int occurrence = 1; occurrence < groups.size(); occurrence++) {
|
||||
terms.add(pathSegment(template, groups.getFirst()) + " = "
|
||||
+ pathSegment(template, groups.get(occurrence)));
|
||||
}
|
||||
if (!"VARCHAR".equals(partitionValueType(key.getType()))) {
|
||||
terms.add(partitionValue(template, key) + " IS NOT NULL");
|
||||
}
|
||||
}
|
||||
return String.join(" AND ", terms);
|
||||
}
|
||||
|
||||
/**
|
||||
* The table's location template, for a table read through {@code read_*}. An Iceberg table is
|
||||
* resolved through its own metadata, which a template plays no part in.
|
||||
*/
|
||||
private static PartitionProjection.LocationTemplate locationTemplate(Table table) {
|
||||
return isIcebergTable(table) ? null : PartitionProjection.locationTemplate(table);
|
||||
}
|
||||
|
||||
/** The partition keys {@code template} names, by lowercased name; empty without a template. */
|
||||
private static Map<String, Column> templatedKeys(Table table, PartitionProjection.LocationTemplate template) {
|
||||
Map<String, Column> keys = new LinkedHashMap<>();
|
||||
if (template == null) {
|
||||
return keys;
|
||||
}
|
||||
for (Column key : table.getPartitionKeys()) {
|
||||
if (key != null && key.getName() != null
|
||||
&& template.groups().containsKey(key.getName().toLowerCase(Locale.ROOT))) {
|
||||
keys.putIfAbsent(key.getName().toLowerCase(Locale.ROOT), key);
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* The text one placeholder matched in the row's object path.
|
||||
*
|
||||
* <p>DuckDB's scalar {@code regexp_extract} takes a group index from 0 to 9 only, and a view using
|
||||
* a larger one fails to bind, which fails every view in the batch. A later group, as in a
|
||||
* template with ten or more placeholders (repeats included), is read through the struct form
|
||||
* instead, which names the groups up to it and returns each as a field. The scalar form stays
|
||||
* for the rest, keeping the common view short.
|
||||
*/
|
||||
private static String pathSegment(PartitionProjection.LocationTemplate template, int group) {
|
||||
String extract = "regexp_extract(" + quote(OBJECT_PATH_COLUMN) + ", '" + escape(template.regex()) + "', ";
|
||||
if (group <= MAX_SCALAR_GROUP) {
|
||||
return extract + group + ")";
|
||||
}
|
||||
StringBuilder names = new StringBuilder("[");
|
||||
for (int i = 1; i <= group; i++) {
|
||||
names.append(i > 1 ? ", " : "").append("'g").append(i).append('\'');
|
||||
}
|
||||
return extract + names + "]).g" + group;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code key}'s value for the row: its first placeholder's text, cast to the key's type. The cast
|
||||
* is a {@code TRY_CAST} so that an object whose path holds no such value is dropped by
|
||||
* {@link #pathFilter} rather than failing the whole query.
|
||||
*/
|
||||
private static String partitionValue(PartitionProjection.LocationTemplate template, Column key) {
|
||||
String text = pathSegment(template, template.groups().get(key.getName().toLowerCase(Locale.ROOT)).getFirst());
|
||||
String type = partitionValueType(key.getType());
|
||||
return "VARCHAR".equals(type) ? text : "TRY_CAST(" + text + " AS " + type + ")";
|
||||
}
|
||||
|
||||
/**
|
||||
* The DuckDB type a partition value is cast to: the scalar Hive types a partition key can take,
|
||||
* and {@code VARCHAR} for the string types and anything else.
|
||||
*
|
||||
* <p>TODO: a {@code date} or {@code timestamp} key projected with a {@code projection.<key>.format}
|
||||
* other than ISO ({@code yyyy-MM-dd}, {@code yyyy-MM-dd HH:mm:ss}) needs {@code strptime} with the
|
||||
* Java pattern translated; until then its values do not parse and its objects are not read.
|
||||
*/
|
||||
private static String partitionValueType(String glueType) {
|
||||
String type = glueType == null ? "" : glueType.trim().toLowerCase(Locale.ROOT);
|
||||
if (DECIMAL_TYPE.matcher(type).matches()) {
|
||||
return type.toUpperCase(Locale.ROOT);
|
||||
}
|
||||
return switch (type) {
|
||||
case "tinyint" -> "TINYINT";
|
||||
case "smallint" -> "SMALLINT";
|
||||
case "int", "integer" -> "INTEGER";
|
||||
case "bigint" -> "BIGINT";
|
||||
case "float" -> "FLOAT";
|
||||
case "double" -> "DOUBLE";
|
||||
case "boolean" -> "BOOLEAN";
|
||||
case "date" -> "DATE";
|
||||
case "timestamp" -> "TIMESTAMP";
|
||||
default -> "VARCHAR";
|
||||
};
|
||||
}
|
||||
|
||||
private static List<Column> declaredColumns(Table table) {
|
||||
List<Column> declared = new ArrayList<>();
|
||||
if (table != null) {
|
||||
@@ -275,12 +416,28 @@ public final class GlueTableResolver {
|
||||
}
|
||||
|
||||
public static String readExpression(String readFn, String normalizedLocation) {
|
||||
String escapedLocation = normalizedLocation.replace("'", "''");
|
||||
String glob = escapedLocation + "/**";
|
||||
if ("read_parquet".equals(readFn)) {
|
||||
return "read_parquet('" + glob + "', union_by_name = true)";
|
||||
return readExpression(readFn, normalizedLocation, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link #readExpression(String, String)} for {@code table}. A table with a location template
|
||||
* also reads each row's object path, which {@link #buildProjection} takes its partition values
|
||||
* from. Hive partitioning is switched off for it: the template is the only source of those
|
||||
* values, and a {@code col=value} segment it happens to contain would otherwise be read as a
|
||||
* second, untyped column.
|
||||
*/
|
||||
public static String readExpression(Table table, String readFn, String normalizedLocation) {
|
||||
if (locationTemplate(table) == null) {
|
||||
return readExpression(readFn, normalizedLocation);
|
||||
}
|
||||
return readFn + "('" + glob + "')";
|
||||
return readExpression(readFn, normalizedLocation,
|
||||
", hive_partitioning = false, filename = '" + escape(OBJECT_PATH_COLUMN) + "'");
|
||||
}
|
||||
|
||||
private static String readExpression(String readFn, String normalizedLocation, String options) {
|
||||
String glob = escape(normalizedLocation) + "/**";
|
||||
String unionByName = "read_parquet".equals(readFn) ? ", union_by_name = true" : "";
|
||||
return readFn + "('" + glob + "'" + unionByName + options + ")";
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -7,6 +7,7 @@ import io.floci.aws.services.glue.model.Table;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
@@ -87,9 +88,13 @@ public final class PartitionProjection {
|
||||
* lands inside the read path, and the next query fails trying to read it as table data.
|
||||
*
|
||||
* <p>The layout comes from {@code storage.location.template} when set, and otherwise from the
|
||||
* default {@code column=value} form over the partition keys. Values stay wildcards: narrowing
|
||||
* default {@code column=value} form over the partition keys. A template's placeholder becomes one
|
||||
* wildcard per folder its value spans (see {@link #placeholderFolders}): a single {@code *} stops
|
||||
* at the next slash, so a multi-folder value followed by more of the template would match no
|
||||
* object, and a read matching no object fails its view. Values stay wildcards: narrowing
|
||||
* them to the partitions a query actually needs requires that query's predicates, so the read
|
||||
* stays wide and the query itself does the filtering.
|
||||
* stays wide and the query itself does the filtering. The values a templated table's rows carry
|
||||
* come from each object's path, through {@link #locationTemplate(Table)}.
|
||||
*/
|
||||
public static String readPath(Table table, String normalizedLocation) {
|
||||
if (!enabled(table)) {
|
||||
@@ -98,7 +103,8 @@ public final class PartitionProjection {
|
||||
|
||||
String template = parameter(table, LOCATION_TEMPLATE);
|
||||
if (template != null && !template.isBlank()) {
|
||||
String wildcarded = TEMPLATE_PLACEHOLDER.matcher(template).replaceAll("*");
|
||||
String wildcarded = TEMPLATE_PLACEHOLDER.matcher(template).replaceAll(placeholder ->
|
||||
"*" + "/*".repeat(placeholderFolders(table, placeholderName(placeholder.group())) - 1));
|
||||
return stripTrailingSlash(wildcarded);
|
||||
}
|
||||
|
||||
@@ -116,6 +122,184 @@ public final class PartitionProjection {
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* A {@code storage.location.template} read the other way round: a pattern over object paths
|
||||
* that recovers the partition values an object was stored under.
|
||||
*
|
||||
* <p>{@code regex} matches the start of the path of every object the template's read path can
|
||||
* reach, with one capture group per placeholder, numbered in template order. {@code groups}
|
||||
* maps each partition key the template names, lowercased, to the groups of its placeholders.
|
||||
* A key may appear more than once, as in {@code ${a}/${b}/${a}/}; DuckDB's regex engine (RE2)
|
||||
* has no backreferences, so the regex cannot require the repeats to agree, and the caller
|
||||
* compares them instead.
|
||||
*/
|
||||
public record LocationTemplate(String regex, Map<String, List<Integer>> groups) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The {@code storage.location.template} of a projecting table as a {@link LocationTemplate},
|
||||
* or {@code null} when the table does not project its partitions, sets no template, has no
|
||||
* partition keys, or has a template that omits one of them (see
|
||||
* {@link #hasIncompleteLocationTemplate}).
|
||||
*
|
||||
* <p>Athena maps partition values to object paths through the template: "a custom template
|
||||
* enables Athena to properly map partition values to custom Amazon S3 file locations that do
|
||||
* not follow a typical {@code .../column=value/...} pattern". The default {@code column=value}
|
||||
* layout needs none of this, since DuckDB's Hive partitioning reads those values on its own.
|
||||
*
|
||||
* <p>TODO: two placeholders sharing a folder, as in {@code ${hour}-${day}/}, are split
|
||||
* greedily, so a value holding the separator is cut in the wrong place and, for a typed key,
|
||||
* dropped by {@link GlueTableResolver#pathFilter}. Athena builds paths from values and has no
|
||||
* such ambiguity, but its docs rule the layout out: "make sure that each placeholder (and the
|
||||
* S3 path itself) is terminated by a single forward slash".
|
||||
*/
|
||||
public static LocationTemplate locationTemplate(Table table) {
|
||||
if (!enabled(table) || table.getPartitionKeys() == null || hasIncompleteLocationTemplate(table)) {
|
||||
return null;
|
||||
}
|
||||
String template = parameter(table, LOCATION_TEMPLATE);
|
||||
if (template == null || template.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
Set<String> keys = partitionKeyNames(table);
|
||||
|
||||
// Each placeholder becomes a group exactly where readPath puts its wildcards, spanning the same
|
||||
// folders (placeholderFolders), so the regex and the read path describe the same objects.
|
||||
StringBuilder regex = new StringBuilder("^");
|
||||
Map<String, List<Integer>> groups = new LinkedHashMap<>();
|
||||
Matcher placeholder = TEMPLATE_PLACEHOLDER.matcher(template);
|
||||
int literalStart = 0;
|
||||
int group = 0;
|
||||
while (placeholder.find()) {
|
||||
String name = placeholderName(placeholder.group());
|
||||
regex.append(regexLiteral(template.substring(literalStart, placeholder.start())))
|
||||
.append(placeholderGroup(table, name));
|
||||
group++;
|
||||
if (keys.contains(name)) {
|
||||
groups.computeIfAbsent(name, ignored -> new ArrayList<>()).add(group);
|
||||
}
|
||||
literalStart = placeholder.end();
|
||||
}
|
||||
if (groups.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
// readPath reads below the template with a trailing "/**", so every object sits under it.
|
||||
regex.append(regexLiteral(stripTrailingSlash(template.substring(literalStart)))).append('/');
|
||||
return new LocationTemplate(regex.toString(), groups);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code table} projects its partitions through a {@code storage.location.template}
|
||||
* that has no placeholder for one of its partition keys.
|
||||
*
|
||||
* <p>Athena's docs call such a template invalid ("the template must contain a placeholder for
|
||||
* each partition column"), and Athena fails every query on the table with
|
||||
* {@code INVALID_TABLE_PROPERTY} rather than reading it some other way; see
|
||||
* {@link #assertLocationTemplatesComplete}.
|
||||
*
|
||||
* <p>An Iceberg table is never incomplete here: floci reads it through its own metadata, which a
|
||||
* template plays no part in (see {@link GlueTableResolver#isIcebergTable}).
|
||||
*/
|
||||
public static boolean hasIncompleteLocationTemplate(Table table) {
|
||||
if (GlueTableResolver.isIcebergTable(table) || !enabled(table)
|
||||
|| table.getPartitionKeys() == null || table.getPartitionKeys().isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
String template = parameter(table, LOCATION_TEMPLATE);
|
||||
if (template == null || template.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
Set<String> named = new HashSet<>();
|
||||
Matcher placeholder = TEMPLATE_PLACEHOLDER.matcher(template);
|
||||
while (placeholder.find()) {
|
||||
named.add(placeholderName(placeholder.group()));
|
||||
}
|
||||
return !named.containsAll(partitionKeyNames(table));
|
||||
}
|
||||
|
||||
/**
|
||||
* Fails a query that names a table whose {@code storage.location.template} omits one of its
|
||||
* partition keys, with the error Athena reports for it.
|
||||
*
|
||||
* <p>Athena fails the query rather than rejecting its submission, and only a query that reads
|
||||
* the table: the database's other tables stay queryable. floci matches both, which is why the
|
||||
* table gets no view at all ({@code GlueViewDdlBuilder} skips it) and this check reports it
|
||||
* instead. Tables are matched as {@link #assertInjectedColumnsFiltered} matches them.
|
||||
*/
|
||||
public static void assertLocationTemplatesComplete(String query, List<Table> tables) {
|
||||
if (query == null || tables == null) {
|
||||
return;
|
||||
}
|
||||
String code = maskLiteralsAndComments(query);
|
||||
for (Table table : tables) {
|
||||
if (table == null || table.getName() == null || !hasIncompleteLocationTemplate(table)
|
||||
|| tableAliases(code, table.getName()).isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
throw new AwsException("InvalidRequestException",
|
||||
"INVALID_TABLE_PROPERTY: The '" + LOCATION_TEMPLATE + "' table property must contain "
|
||||
+ "templates for all partition columns! Table: " + table.getDatabaseName() + "."
|
||||
+ table.getName() + " Template: " + parameter(table, LOCATION_TEMPLATE), 400);
|
||||
}
|
||||
}
|
||||
|
||||
/** The table's partition key names, lowercased. */
|
||||
private static Set<String> partitionKeyNames(Table table) {
|
||||
Set<String> keys = new HashSet<>();
|
||||
for (Column key : table.getPartitionKeys()) {
|
||||
if (key != null && key.getName() != null) {
|
||||
keys.add(key.getName().toLowerCase(Locale.ROOT));
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
/** The key a {@code ${key}} placeholder names, lowercased. */
|
||||
private static String placeholderName(String placeholder) {
|
||||
return placeholder.substring(2, placeholder.length() - 1).trim().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
/** The capture group for one placeholder, spanning the folders its value does. */
|
||||
private static String placeholderGroup(Table table, String key) {
|
||||
return "([^/]+" + "(?:/[^/]+)".repeat(placeholderFolders(table, key) - 1) + ")";
|
||||
}
|
||||
|
||||
/**
|
||||
* How many folders one placeholder's value spans: one, or as many as its key's projected value
|
||||
* does. {@link #readPath} and {@link #locationTemplate} both follow it, so the read glob and the
|
||||
* regex agree on where each value ends.
|
||||
*
|
||||
* <p>A {@code date} projection's {@code format} may itself hold slashes, as in the Firehose
|
||||
* layout AWS documents: a single {@code ${datehour}} placeholder with format
|
||||
* {@code yyyy/MM/dd/HH} stands for four folders, and Athena reports the whole
|
||||
* {@code 2026/11/10/05} as the value. Every other projection type yields a value within one
|
||||
* folder.
|
||||
*
|
||||
* <p>TODO: an {@code enum} value holding a slash spans folders too, and would need a group
|
||||
* per distinct depth among the listed values.
|
||||
*/
|
||||
private static int placeholderFolders(Table table, String key) {
|
||||
String type = parameter(table, "projection." + key + ".type");
|
||||
String format = parameter(table, "projection." + key + ".format");
|
||||
if ("date".equalsIgnoreCase(type == null ? null : type.trim()) && format != null) {
|
||||
return 1 + (int) format.chars().filter(c -> c == '/').count();
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
/** {@code literal} escaped for RE2, which takes a backslash before any punctuation. */
|
||||
private static String regexLiteral(String literal) {
|
||||
StringBuilder sb = new StringBuilder(literal.length());
|
||||
for (int i = 0; i < literal.length(); i++) {
|
||||
char c = literal.charAt(i);
|
||||
if ("\\.+*?()|[]{}^$".indexOf(c) >= 0) {
|
||||
sb.append('\\');
|
||||
}
|
||||
sb.append(c);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fails a query that names a projecting table but never constrains one of its {@code injected}
|
||||
* partition columns in a {@code WHERE} clause.
|
||||
@@ -412,6 +596,14 @@ public final class PartitionProjection {
|
||||
* The alias, or the table's own name, under which each {@code FROM}, {@code JOIN} or comma-separated
|
||||
* source naming {@code tableName} appears. The name must end at an identifier boundary, so
|
||||
* {@code events_daily} is not a reference to {@code events}.
|
||||
*
|
||||
* <p>TODO: this matches the query's text, not its resolved sources. A qualifier is not compared
|
||||
* with the table's database, so {@code other_db.events} counts as a reference to the context
|
||||
* database's {@code events}, and a common table expression named {@code events} counts too.
|
||||
* Its callers are also given only the query context database's tables
|
||||
* ({@code AthenaService.tablesForProjectionCheck}), so a table in another database is not
|
||||
* checked. {@link #assertInjectedColumnsFiltered} and {@link #assertLocationTemplatesComplete}
|
||||
* share these limits; resolving the sources the query reads would lift them for both.
|
||||
*/
|
||||
private static List<String> tableAliases(String code, String tableName) {
|
||||
String identifier = identifierPattern(tableName);
|
||||
|
||||
+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