diff --git a/docs/services/athena.md b/docs/services/athena.md index dbefa0de7e..3abfb5ad7b 100644 --- a/docs/services/athena.md +++ b/docs/services/athena.md @@ -150,7 +150,7 @@ A table whose location holds no data, or only folder markers (keys ending in `/` 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, `/=*/...` 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. +- **Partition values**: in the default layout, DuckDB's Hive partitioning supplies each key's value, read as text and cast to the key's declared type, so a `string` key holding `2026-11-14` stays a string; a folder whose value the key's type cannot hold (`dt=latest` for a `date`) is not read. A `date` or `timestamp` key whose date projection sets a `format` is parsed with it in either layout (`dt=20261116` for `yyyyMMdd`); a format using pattern letters other than `yyyy`, `yy`, `MM`, `dd`, `HH`, `mm` and `ss` is cast as an ISO 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: diff --git a/src/main/java/io/floci/aws/services/glue/GlueTableResolver.java b/src/main/java/io/floci/aws/services/glue/GlueTableResolver.java index 7287ddcba6..9382e66daa 100644 --- a/src/main/java/io/floci/aws/services/glue/GlueTableResolver.java +++ b/src/main/java/io/floci/aws/services/glue/GlueTableResolver.java @@ -278,6 +278,7 @@ public final class GlueTableResolver { PartitionProjection.LocationTemplate template = locationTemplate(table); Map templatedKeys = templatedKeys(table, template); Map textColumns = readsDelimitedText(table) ? columnsByName(declared) : Map.of(); + Map hiveKeys = hivePartitionKeys(table, template); StringBuilder sb = new StringBuilder(); for (int i = 0; i < names.size(); i++) { if (i > 0) { @@ -285,8 +286,10 @@ public final class GlueTableResolver { } String name = names.get(i); Column key = templatedKeys.get(name.toLowerCase(Locale.ROOT)); + Column hiveKey = hiveKeys.get(name.toLowerCase(Locale.ROOT)); Column text = textColumns.get(name.toLowerCase(Locale.ROOT)); - String value = key != null ? partitionValue(template, key) + String value = key != null ? partitionValue(table, template, key) + : hiveKey != null ? typedKey(table, hiveKey, quote(name)) : text != null ? typedText(quote(name), text.getType()) : quote(name); sb.append(value).append(" AS ").append(quote(name)); @@ -503,7 +506,7 @@ public final class GlueTableResolver { public static String pathFilter(Table table) { PartitionProjection.LocationTemplate template = locationTemplate(table); if (template == null) { - return null; + return hiveValueFilter(table); } List terms = new ArrayList<>(); terms.add("regexp_matches(" + quote(OBJECT_PATH_COLUMN) + ", '" + escape(template.regex()) + "')"); @@ -514,12 +517,49 @@ public final class GlueTableResolver { + pathSegment(template, groups.get(occurrence))); } if (!"VARCHAR".equals(scalarType(key.getType()))) { - terms.add(partitionValue(template, key) + " IS NOT NULL"); + terms.add(partitionValue(table, template, key) + " IS NOT NULL"); } } return String.join(" AND ", terms); } + /** + * The condition a projecting table in the default {@code column=value} layout keeps rows by: that each typed + * key's value parses as its type. Athena builds each path from values its projection generates, so a folder whose + * value the type cannot hold ({@code dt=latest} for a date) is one no query addresses. Null when no key is typed. + */ + private static String hiveValueFilter(Table table) { + if (isIcebergTable(table) || !PartitionProjection.enabled(table)) { + return null; + } + List terms = new ArrayList<>(); + for (Column key : hivePartitionKeys(table, null).values()) { + if (!"VARCHAR".equals(scalarType(key.getType()))) { + terms.add(typedKey(table, key, quote(key.getName())) + " IS NOT NULL"); + } + } + return terms.isEmpty() ? null : String.join(" AND ", terms); + } + + /** + * The partition keys whose values DuckDB's Hive partitioning reads from {@code column=value} folders, by + * lowercased name: a Hive table's keys when it has no location template (an Iceberg table reads its own typed + * values). They are read as text and take their declared type, as Athena types a partition value, rather than the + * type DuckDB would guess from the folder name. + */ + private static Map hivePartitionKeys(Table table, PartitionProjection.LocationTemplate template) { + Map keys = new LinkedHashMap<>(); + if (template != null || isIcebergTable(table) || table.getPartitionKeys() == null) { + return keys; + } + for (Column key : table.getPartitionKeys()) { + if (key != null && key.getName() != null) { + keys.putIfAbsent(key.getName().toLowerCase(Locale.ROOT), key); + } + } + return keys; + } + /** * 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. @@ -569,18 +609,104 @@ public final class GlueTableResolver { * 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) { + private static String partitionValue(Table table, PartitionProjection.LocationTemplate template, Column key) { String text = pathSegment(template, template.groups().get(key.getName().toLowerCase(Locale.ROOT)).getFirst()); + return typedKey(table, key, text); + } + + /** + * A projected partition key's text as its declared type. A {@code date} or {@code timestamp} key whose date + * projection sets a {@code projection..format} is parsed with that format, as Athena reads the value it + * generated ({@code dt=20261116} for {@code yyyyMMdd}); any other key, or a format {@link #strptimeFormat} cannot + * translate, is cast as {@link #typedText} casts it. + */ + private static String typedKey(Table table, Column key, String text) { + String type = scalarType(key.getType()); + String projection = "projection." + key.getName() + "."; + if (("DATE".equals(type) || "TIMESTAMP".equals(type)) && PartitionProjection.enabled(table) + && "date".equalsIgnoreCase(PartitionProjection.parameter(table, projection + "type"))) { + String format = strptimeFormat(PartitionProjection.parameter(table, projection + "format")); + if (format != null) { + return "TRY_CAST(try_strptime(" + text + ", '" + escape(format) + "') AS " + type + ")"; + } + } return typedText(text, key.getType()); } + /** + * A Java date pattern ({@code projection..format}) as a {@code strptime} format: {@code yyyy}, {@code yy}, + * {@code MM}, {@code dd}, {@code HH}, {@code mm} and {@code ss}, quoted and other literal text kept. Null for a + * blank pattern or one with any other pattern letter. + */ + static String strptimeFormat(String pattern) { + if (pattern == null || pattern.isBlank()) { + return null; + } + StringBuilder format = new StringBuilder(); + int i = 0; + while (i < pattern.length()) { + char c = pattern.charAt(i); + if (c == '\'') { + // A quoted section is literal text, '' inside it standing for one quote; '' outside is a quote too. + int j = i + 1; + if (j < pattern.length() && pattern.charAt(j) == '\'') { + format.append('\''); + i = j + 1; + continue; + } + StringBuilder literal = new StringBuilder(); + while (true) { + if (j >= pattern.length()) { + return null; + } + if (pattern.charAt(j) == '\'') { + if (j + 1 < pattern.length() && pattern.charAt(j + 1) == '\'') { + literal.append('\''); + j += 2; + continue; + } + break; + } + literal.append(pattern.charAt(j++)); + } + format.append(literal.toString().replace("%", "%%")); + i = j + 1; + continue; + } + if (Character.isLetter(c)) { + int j = i; + while (j < pattern.length() && pattern.charAt(j) == c) { + j++; + } + String specifier = switch (pattern.substring(i, j)) { + case "yyyy" -> "%Y"; + case "yy" -> "%y"; + case "MM" -> "%m"; + case "dd" -> "%d"; + case "HH" -> "%H"; + case "mm" -> "%M"; + case "ss" -> "%S"; + default -> null; + }; + if (specifier == null) { + return null; + } + format.append(specifier); + i = j; + continue; + } + format.append(c == '%' ? "%%" : String.valueOf(c)); + i++; + } + return format.toString(); + } + /** * 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. * - *

TODO: a {@code date} or {@code timestamp} key projected with a {@code projection..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. + *

A {@code date} or {@code timestamp} key projected with a {@code projection..format} is parsed with that + * format instead ({@link #typedKey}). */ private static String scalarType(String glueType) { String type = glueType == null ? "" : glueType.trim().toLowerCase(Locale.ROOT); @@ -649,12 +775,15 @@ public final class GlueTableResolver { * 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. A table that declares CSV options (a delimiter, header lines) is read - * with them and its declared column names, as {@link #hasCsvOptions} explains. + * second, untyped column. Any other partitioned table reads its Hive partition values as text, which + * {@link #buildProjection} gives their declared types. A table that declares CSV options (a delimiter, header + * lines) is read with them and its declared column names, as {@link #hasCsvOptions} explains. */ public static String readExpression(Table table, String readFn, String normalizedLocation) { boolean templated = locationTemplate(table) != null; - String options = templated ? ", hive_partitioning = false, filename = '" + escape(OBJECT_PATH_COLUMN) + "'" : ""; + boolean partitioned = !hivePartitionKeys(table, null).isEmpty(); + String options = templated ? ", hive_partitioning = false, filename = '" + escape(OBJECT_PATH_COLUMN) + "'" + : partitioned ? ", hive_types_autocast = false" : ""; if ("read_csv_auto".equals(readFn) && hasCsvOptions(table)) { // Hive partition values stay text too, so they take their declared type like the data columns. return csvReadExpressionForInput(table, "'" + escape(normalizedLocation) + "/**'", diff --git a/src/test/java/io/floci/aws/services/athena/AthenaPartitionTemplateSidecarIntegrationTest.java b/src/test/java/io/floci/aws/services/athena/AthenaPartitionTemplateSidecarIntegrationTest.java index c08eb16dd8..e1ad4d95d5 100644 --- a/src/test/java/io/floci/aws/services/athena/AthenaPartitionTemplateSidecarIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/athena/AthenaPartitionTemplateSidecarIntegrationTest.java @@ -92,6 +92,37 @@ class AthenaPartitionTemplateSidecarIntegrationTest { assertEquals(EXPECTED_ROW, queryEuInMarch("sales_hive")); } + /** + * In the default layout each value takes its key's declared type, not the one DuckDB would guess from the folder + * name: a string key holding a date stays a string, and a date key's folder holding a value no date is is one + * projection never generates, so it is not read. + */ + @Test + void defaultLayoutTypesEachValueAsItsKeyDeclares() { + table("sales_typed", "typed", null, "typed/region=2026-03-14/dt=2026-03-14/part.parquet", + "typed/region=eu/dt=latest/part.parquet"); + + assertEquals(List.of(Map.of("region", "2026-03-14", "region_type", "VARCHAR", "dt_type", "DATE")), + query("SELECT region, typeof(region) AS region_type, typeof(dt) AS dt_type FROM " + + view("sales_typed"))); + } + + /** A date projected with a format in the default layout is read through that format: dt=20260314 is March 14. */ + @Test + void defaultLayoutParsesAFormattedDateProjection() { + Map 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", "yyyyMMdd"); + parameters.put("projection.dt.range", "20260101,NOW"); + register("sales_compact", "compact", parameters, List.of(column("region", "string"), column("dt", "date")), + "compact/region=eu/dt=20260314/part.parquet"); + + assertEquals(EXPECTED_ROW, queryEuInMarch("sales_compact")); + } + @Test void templateWithBareValuesMapsEachFolderToItsKey() { table("sales_bare", "bare", "bare/${region}/${dt}/", "bare/eu/2026-03-14/part.parquet"); diff --git a/src/test/java/io/floci/aws/services/athena/GlueViewDdlBuilderTest.java b/src/test/java/io/floci/aws/services/athena/GlueViewDdlBuilderTest.java index 252ea59138..6f38bc12a0 100644 --- a/src/test/java/io/floci/aws/services/athena/GlueViewDdlBuilderTest.java +++ b/src/test/java/io/floci/aws/services/athena/GlueViewDdlBuilderTest.java @@ -246,15 +246,39 @@ class GlueViewDdlBuilderTest { ddl); } - /** The default column=value layout is left to DuckDB's Hive partitioning, as before. */ + /** + * The default column=value layout takes its values from DuckDB's Hive partitioning, read as text and given each + * key's declared type rather than the one DuckDB would guess; a folder whose value the type cannot hold is one + * no projected query addresses, so its rows are not read. + */ @Test - void defaultLayoutStillReadsPartitionValuesThroughHivePartitioning() { + void defaultLayoutTypesEachPartitionValueAsItsKeyDeclares() { 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); + + "\"region\" AS \"region\", TRY_CAST(\"dt\" AS DATE) AS \"dt\" " + + "FROM read_parquet('s3://b/hive/region=*/dt=*/**', union_by_name = true, hive_types_autocast = false) " + + "WHERE TRY_CAST(\"dt\" AS DATE) IS NOT NULL;\n", ddl); + } + + /** + * A date key projected with a format is parsed with that format, in either layout, as Athena reads the value it + * generated: {@code dt=20261116} for {@code yyyyMMdd} is a date, not a value the key's type cannot hold. + */ + @Test + void aFormattedDateProjectionParsesItsValuesWithTheFormat() { + String parsed = "TRY_CAST(try_strptime(\"dt\", '%Y%m%d') AS DATE)"; + String hive = ddlFor(projectingParquetTable("s3://b/hive/", Map.of("projection.enabled", "true", + "projection.dt.type", "date", "projection.dt.format", "yyyyMMdd"))); + assertTrue(hive.contains(parsed + " AS \"dt\""), hive); + assertTrue(hive.contains("WHERE " + parsed + " IS NOT NULL"), hive); + + String templated = ddlFor(projectingParquetTable("s3://b/data/", Map.of("projection.enabled", "true", + "projection.dt.type", "date", "projection.dt.format", "yyyyMMdd", + "storage.location.template", "s3://b/data/${region}/${dt}/"))); + assertTrue(templated.contains("TRY_CAST(try_strptime(regexp_extract(\"$path\", " + + "'^s3://b/data/([^/]+)/([^/]+)/', 2), '%Y%m%d') AS DATE) AS \"dt\""), templated); } /** diff --git a/src/test/java/io/floci/aws/services/glue/GlueTableResolverTest.java b/src/test/java/io/floci/aws/services/glue/GlueTableResolverTest.java index 010fceec35..b33f29bbfe 100644 --- a/src/test/java/io/floci/aws/services/glue/GlueTableResolverTest.java +++ b/src/test/java/io/floci/aws/services/glue/GlueTableResolverTest.java @@ -261,4 +261,17 @@ class GlueTableResolverTest { assertThat(GlueTableResolver.readPlan(table).fromClause(), equalTo("read_csv_auto('s3://bucket/events/**')")); } + + @Test + void aJavaDatePatternTranslatesToAStrptimeFormat() { + assertThat(GlueTableResolver.strptimeFormat("yyyy/MM/dd/HH"), is("%Y/%m/%d/%H")); + assertThat(GlueTableResolver.strptimeFormat("yyyyMMdd'T'HHmmss"), is("%Y%m%dT%H%M%S")); + assertThat(GlueTableResolver.strptimeFormat("yy-MM-dd 100%"), is("%y-%m-%d 100%%")); + // A doubled quote is one quote, inside a quoted section or outside one, as Java's formatter reads it. + assertThat(GlueTableResolver.strptimeFormat("yyyy'foo''bar'MMdd"), is("%Yfoo'bar%m%d")); + assertThat(GlueTableResolver.strptimeFormat("yyyy''MM"), is("%Y'%m")); + assertThat(GlueTableResolver.strptimeFormat("yyyy'unclosed"), nullValue()); + assertThat(GlueTableResolver.strptimeFormat("EEE, dd MMM yyyy"), nullValue()); + assertThat(GlueTableResolver.strptimeFormat(" "), nullValue()); + } }