fix(athena): take templated partition values from the object path (#8242)

This commit is contained in:
Ghassan Gedeon Achi authored and GitHub committed 2026-11-13 23:16:19 -04:00
1 parent 4cd8ab991e
commit 01d61afd8a
9 files changed
+1042 -16

No files matched your search

@@ -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);