From 11864f6e81e446285d6fdb7bf9894e2157d59092 Mon Sep 17 00:00:00 2001 From: Ghassan Gedeon Achi Date: Mon, 16 Nov 2026 14:33:22 -0600 Subject: [PATCH] fix(athena): read a column declared timestamp as Athena's timestamp(3) (#8648) --- docs/services/athena.md | 4 +- .../aws/services/athena/AthenaService.java | 55 ++++- .../services/athena/GlueViewDdlBuilder.java | 58 +++-- .../aws/services/glue/GlueTableResolver.java | 116 ++++++++- ...naDelimitedTextSidecarIntegrationTest.java | 135 +++-------- ...rtitionTemplateSidecarIntegrationTest.java | 83 ++----- .../services/athena/AthenaServiceTest.java | 36 ++- .../services/athena/AthenaSidecarFixture.java | 122 ++++++++++ ...TimestampColumnSidecarIntegrationTest.java | 225 ++++++++++++++++++ .../athena/GlueViewDdlBuilderTest.java | 29 +++ .../services/glue/GlueTableResolverTest.java | 91 +++++++ 11 files changed, 766 insertions(+), 188 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/athena/AthenaSidecarFixture.java create mode 100644 src/test/java/io/floci/aws/services/athena/AthenaTimestampColumnSidecarIntegrationTest.java diff --git a/docs/services/athena.md b/docs/services/athena.md index 3abfb5ad7b..33de4529db 100644 --- a/docs/services/athena.md +++ b/docs/services/athena.md @@ -114,7 +114,7 @@ results storage. 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 ""`) and, for each table the query names, creates qualified views (`CREATE OR REPLACE VIEW "".""`) 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 "
"` 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. +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. A `timestamp` value is rendered as Athena renders it, with at least three fractional digits (`2026-03-14 09:30:00.000`); a timestamp literal written with fewer, which Athena renders at its own precision, is padded too. The result CSV object in S3 keeps DuckDB's form, as does `CAST(ts AS varchar)` inside a query. ## Trino SQL on DuckDB @@ -139,6 +139,8 @@ For every other table, the DuckDB read function is chosen from the Glue table's A delimited-text table that declares its CSV options (`field.delim` or `separatorChar`, `skip.header.line.count`) in its table, storage descriptor or SerDe parameters, such as a `LazySimpleSerDe` table over headerless TSV, is read with `read_csv` and exactly those options instead of being sniffed, its files' columns named after the declared data columns. Each data column and Hive partition value takes its declared type, and a value that type cannot hold reads as NULL, as with Hive's `LazySimpleSerDe`. A row with fewer fields than the declared columns (a file written before `ALTER TABLE ADD COLUMNS`) gets NULL for the rest, and fields past them are dropped. For a `LazySimpleSerDe` table, `\N` reads as NULL unless `serialization.null.format` says otherwise, an empty field is an empty string, and a quote is text. Compressed files (`.gz`, `.zst`) are read as they are. +A data column declared `timestamp` in a Parquet table, or in a delimited-text table that declares its CSV options (above), reads as Athena reads it, as a `timestamp(3)`: the UTC wall-clock time, truncated to milliseconds. That holds however a Parquet file stores it: UTC-adjusted (which DuckDB would otherwise read as a `timestamp with time zone`), in micro- or nanoseconds, or as INT96. A Parquet file whose column holds something else is read by its physical type, as Athena reads it: an INT64 without a logical type as epoch milliseconds, while a string (even an ISO one) or a date fails the query with Athena's `HIVE_BAD_DATA` or `SERIALIZATION_ERROR` (without the file's path). Any other physical type fails the query with DuckDB's cast error. A query that doesn't select such a column is unaffected. In a JSON table, or a delimited-text table read by sniffing, a `timestamp` column keeps the type DuckDB infers, and a `timestamp` partition key keeps its microseconds. + Only the tables a query names get views (by database and name; a name only a string literal or a comment holds doesn't count), since DuckDB binds every view of the batch before the query runs: a table whose view cannot be built (files that do not match its declared format or schema) then fails the queries that read it and no others. A query that reads `information_schema` or is a `SHOW` statement gets a view for every table. A partitioned table without partition projection is read through the partitions registered for it in Glue, as Athena reads it: each partition from its own location, with its values as the partition keys. The partitions come from `ALTER TABLE ADD PARTITION`, `MSCK REPAIR TABLE` or Glue's `CreatePartition` and `BatchCreatePartition`. A partition without a location of its own is read at `
/key=value/...`. A folder under the table's location that no partition names isn't read, a partition's location may lie outside it, a non-Hive layout (`2026/11/16/`) is read through the partitions added for it, and a table with no partitions registered answers no rows until they are loaded. The partitions are read together with their columns matched by name, so a partition written before a column was added reads NULL for it. A partition value its key's type cannot hold fails the query with Athena's `HIVE_INVALID_PARTITION_VALUE`, and a partition that does not give one value for each key, which Glue refuses on AWS, is not read. diff --git a/src/main/java/io/floci/aws/services/athena/AthenaService.java b/src/main/java/io/floci/aws/services/athena/AthenaService.java index 0be3059424..d7cf42d304 100644 --- a/src/main/java/io/floci/aws/services/athena/AthenaService.java +++ b/src/main/java/io/floci/aws/services/athena/AthenaService.java @@ -67,6 +67,13 @@ public class AthenaService { private static final Logger LOG = Logger.getLogger(AthenaService.class); private static final Pattern DECIMAL_TYPE = Pattern.compile("DECIMAL\\((\\d+),\\s*(\\d+)\\)", Pattern.CASE_INSENSITIVE); + + /** + * A timestamp as DuckDB writes it to a result CSV: the seconds, then an optional fraction. Anything + * else ({@code infinity}, a BC date) is not one {@link #athenaTimestamp} pads. + */ + private static final Pattern DUCKDB_TIMESTAMP = Pattern.compile( + "(\\d{4,}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2})(?:\\.(\\d+))?"); public static final String DEFAULT_CATALOG = "AwsDataCatalog"; private static final String DEFAULT_OUTPUT_BUCKET = "floci-athena-results"; private static final String DEFAULT_WORKGROUP = "primary"; @@ -1342,16 +1349,20 @@ public class AthenaService { } String[] headers = CsvParser.parseLine(headerLine).toArray(String[]::new); + List athenaTypes = new ArrayList<>(); for (int i = 0; i < headers.length; i++) { - columns.add(columnInfo(headers[i], i < columnTypes.size() ? columnTypes.get(i) : "VARCHAR")); + ResultSet.ColumnInfo column = columnInfo(headers[i], + i < columnTypes.size() ? columnTypes.get(i) : "VARCHAR"); + columns.add(column); + athenaTypes.add(column.getType()); } // Header row is included in GetQueryResults per AWS spec - rows.add(toRow(headers)); + rows.add(toRow(headers, List.of())); String line; while ((line = reader.readLine()) != null) { - rows.add(toRow(CsvParser.parseLine(line).toArray(String[]::new))); + rows.add(toRow(CsvParser.parseLine(line).toArray(String[]::new), athenaTypes)); } } catch (Exception e) { LOG.debugv("CSV parse error: {0}", e.getMessage()); @@ -1400,14 +1411,46 @@ public class AthenaService { return type; } - private ResultSet.Row toRow(String[] values) { + /** One result row, each value rendered as Athena renders a value of its column's type. */ + private ResultSet.Row toRow(String[] values, List athenaTypes) { List data = new ArrayList<>(); - for (String v : values) { - data.add(new ResultSet.Datum(v)); + for (int i = 0; i < values.length; i++) { + String type = i < athenaTypes.size() ? athenaTypes.get(i) : "varchar"; + data.add(new ResultSet.Datum("timestamp".equals(type) ? athenaTimestamp(values[i]) : values[i])); } return new ResultSet.Row(data); } + /** + * A {@code timestamp} value as Athena renders it: with at least three fractional digits. + * + *

DuckDB writes the shortest form, {@code 2026-03-14 09:30:00}, where Athena writes + * {@code 2026-03-14 09:30:00.000}. A timestamp's rendering follows its precision, and on Athena + * nearly every timestamp has precision 3: a Hive table's columns, {@code CAST(... AS timestamp)}, + * {@code current_timestamp}, and what {@code date_trunc} and interval arithmetic make of them. + * DuckDB's types don't carry that precision through expressions, so every {@code timestamp} + * result is padded alike. A value with more digits keeps them. + * + *

TODO: a literal has the precision it is written with, so Athena renders + * {@code TIMESTAMP '2026-03-14 09:30:00'} without a fraction, and this pads it. An Iceberg + * table's {@code timestamp} is {@code timestamp(6)} on Athena, which presumably renders six + * digits (unchecked). The result CSV object itself is written by floci-duck and keeps DuckDB's + * form, as does {@code CAST(ts AS varchar)} inside a query. + */ + static String athenaTimestamp(String value) { + if (value == null) { + return null; + } + Matcher timestamp = DUCKDB_TIMESTAMP.matcher(value); + if (!timestamp.matches()) { + return value; + } + String fraction = timestamp.group(2) == null ? "" : timestamp.group(2); + return fraction.length() >= 3 + ? value + : timestamp.group(1) + "." + fraction + "000".substring(fraction.length()); + } + private String extractBucket(String s3Path) { if (s3Path == null || !s3Path.startsWith("s3://")) { return null; diff --git a/src/main/java/io/floci/aws/services/athena/GlueViewDdlBuilder.java b/src/main/java/io/floci/aws/services/athena/GlueViewDdlBuilder.java index 64a5758570..23a2e9b0cb 100644 --- a/src/main/java/io/floci/aws/services/athena/GlueViewDdlBuilder.java +++ b/src/main/java/io/floci/aws/services/athena/GlueViewDdlBuilder.java @@ -12,23 +12,40 @@ import jakarta.inject.Inject; import org.jboss.logging.Logger; import java.util.ArrayList; +import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.NavigableSet; +import java.util.Set; @ApplicationScoped public class GlueViewDdlBuilder { private static final Logger LOG = Logger.getLogger(GlueViewDdlBuilder.class); - /** - * Iceberg tables are read through the {@code iceberg} extension rather than one of the - * Hive-format-sniffed {@code read_*} functions, so it is installed and loaded once, up - * front, only when the batch actually contains an Iceberg table. - */ - private static final String ICEBERG_EXTENSION_SETUP = "INSTALL iceberg; LOAD iceberg;\n"; + /** Statements a batch of views needs run first, each emitted once and only when a view needs it. */ + private enum SessionSetup { + /** + * Iceberg tables are read through the {@code iceberg} extension rather than one of the + * Hive-format-sniffed {@code read_*} functions, so it is installed and loaded once, up + * front, only when the batch actually contains an Iceberg table. + */ + ICEBERG_EXTENSION("INSTALL iceberg; LOAD iceberg;\n"), + /** + * A view reading a Parquet timestamp converts in the session's time zone, which must be + * Athena's, UTC: see {@link GlueTableResolver#readsParquetTimestamps}. floci-duck's sessions + * default to UTC only because its container does; this keeps the result from depending on it. + */ + UTC_SESSION("SET TimeZone = 'UTC';\n"); + + private final String sql; + + SessionSetup(String sql) { + this.sql = sql; + } + } private final GlueService glueService; private final S3Service s3Service; @@ -55,7 +72,7 @@ public class GlueViewDdlBuilder { // A table read through its registered partitions is built once for its qualified and unqualified views. Map partitionReads = new HashMap<>(); StringBuilder sb = new StringBuilder(); - boolean usesIceberg = false; + Set setup = EnumSet.noneOf(SessionSetup.class); boolean contextDbHandled = false; List databases = glueService.getDatabases(); if (databases != null) { @@ -70,9 +87,9 @@ public class GlueViewDdlBuilder { sb.append("CREATE SCHEMA IF NOT EXISTS ").append(quote(schema)).append(";\n"); try { List

tables = glueService.getTables(schema); - usesIceberg |= appendViews(sb, schema, tables, true, wanted, partitionReads); + appendViews(sb, setup, schema, tables, true, wanted, partitionReads); if (schema.equals(contextDatabase)) { - usesIceberg |= appendViews(sb, schema, tables, false, wanted, partitionReads); + appendViews(sb, setup, schema, tables, false, wanted, partitionReads); contextDbHandled = true; } } catch (Exception e) { @@ -84,26 +101,27 @@ public class GlueViewDdlBuilder { if (!contextDbHandled && contextDatabase != null && !contextDatabase.isBlank()) { try { List
tables = glueService.getTables(contextDatabase); - usesIceberg |= appendViews(sb, contextDatabase, tables, false, wanted, partitionReads); + appendViews(sb, setup, contextDatabase, tables, false, wanted, partitionReads); } catch (Exception e) { LOG.debugv("Could not fetch tables for context database {0}: {1}", contextDatabase, e.getMessage()); } } - if (usesIceberg) { - sb.insert(0, ICEBERG_EXTENSION_SETUP); + StringBuilder prefix = new StringBuilder(); + for (SessionSetup statement : setup) { + prefix.append(statement.sql); } + sb.insert(0, prefix); return sb.toString(); } - /** @return true if at least one of the appended views reads an Iceberg table. */ - private boolean appendViews(StringBuilder sb, String schemaOrNull, List
tables, boolean qualified, - ViewFilter wanted, Map partitionReads) { + /** Appends a view for each of {@code tables} that {@code wanted} names, adding to {@code setup} what they need. */ + private void appendViews(StringBuilder sb, Set setup, String schemaOrNull, List
tables, + boolean qualified, ViewFilter wanted, Map partitionReads) { if (tables == null) { - return false; + return; } - boolean usesIceberg = false; for (Table t : tables) { try { if (t == null) { @@ -133,11 +151,14 @@ public class GlueViewDdlBuilder { String target = qualified ? quote(schemaOrNull) + "." + quote(t.getName()) : quote(t.getName()); + if (GlueTableResolver.readsParquetTimestamps(t)) { + setup.add(SessionSetup.UTC_SESSION); + } String fromClause; if (GlueTableResolver.isIcebergTable(t) && GlueTableResolver.icebergMetadataLocation(t) != null && !GlueTableResolver.icebergMetadataLocation(t).isBlank()) { fromClause = GlueTableResolver.icebergReadExpression(GlueTableResolver.icebergMetadataLocation(t)); - usesIceberg = true; + setup.add(SessionSetup.ICEBERG_EXTENSION); } else if (GlueTableResolver.readsRegisteredPartitions(t)) { sb.append("CREATE OR REPLACE VIEW ").append(target).append(" AS ") .append(registeredPartitionsSelect(schemaOrNull, t, partitionReads)).append(";\n"); @@ -169,7 +190,6 @@ public class GlueViewDdlBuilder { LOG.debugv("skip Glue table {0}.{1}: {2}", schemaOrNull, t != null ? t.getName() : "unknown", e.getMessage()); } } - return usesIceberg; } /** 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 9382e66daa..b8850c3f6d 100644 --- a/src/main/java/io/floci/aws/services/glue/GlueTableResolver.java +++ b/src/main/java/io/floci/aws/services/glue/GlueTableResolver.java @@ -255,6 +255,9 @@ public final class GlueTableResolver { *

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. + * + *

A data column declared {@code timestamp} reads as Athena's {@code timestamp(3)}, whatever the file + * stores: see {@link #parquetTimestamps} and {@link #typedTextColumn}. */ public static String buildProjection(Table table) { List declared = declaredColumns(table); @@ -279,6 +282,7 @@ public final class GlueTableResolver { Map templatedKeys = templatedKeys(table, template); Map textColumns = readsDelimitedText(table) ? columnsByName(declared) : Map.of(); Map hiveKeys = hivePartitionKeys(table, template); + Map parquetTimestamps = parquetTimestamps(table); StringBuilder sb = new StringBuilder(); for (int i = 0; i < names.size(); i++) { if (i > 0) { @@ -288,9 +292,11 @@ public final class GlueTableResolver { Column key = templatedKeys.get(name.toLowerCase(Locale.ROOT)); Column hiveKey = hiveKeys.get(name.toLowerCase(Locale.ROOT)); Column text = textColumns.get(name.toLowerCase(Locale.ROOT)); + Column parquetTimestamp = parquetTimestamps.get(name.toLowerCase(Locale.ROOT)); String value = key != null ? partitionValue(table, template, key) : hiveKey != null ? typedKey(table, hiveKey, quote(name)) - : text != null ? typedText(quote(name), text.getType()) + : text != null ? typedTextColumn(quote(name), text.getType()) + : parquetTimestamp != null ? parquetTimestamp(quote(name), name) : quote(name); sb.append(value).append(" AS ").append(quote(name)); } @@ -343,6 +349,7 @@ public final class GlueTableResolver { Set keyNames = new HashSet<>(); keys.forEach(key -> keyNames.add(key.getName().toLowerCase(Locale.ROOT))); Map textColumns = readsDelimitedText(table) ? columnsByName(declaredColumns(table)) : Map.of(); + Map parquetTimestamps = parquetTimestamps(table); List projected = new ArrayList<>(); for (Column column : declaredColumns(table)) { String name = column.getName(); @@ -352,7 +359,10 @@ public final class GlueTableResolver { } Column text = textColumns.get(name.toLowerCase(Locale.ROOT)); String read = "r." + quote(name); - projected.add((text != null ? typedText(read, text.getType()) : read) + " AS " + quote(name)); + String value = text != null ? typedTextColumn(read, text.getType()) + : parquetTimestamps.containsKey(name.toLowerCase(Locale.ROOT)) ? parquetTimestamp(read, name) + : read; + projected.add(value + " AS " + quote(name)); } List rows = new ArrayList<>(); List globs = new ArrayList<>(); @@ -486,6 +496,108 @@ public final class GlueTableResolver { return "VARCHAR".equals(type) ? text : "TRY_CAST(" + text + " AS " + type + ")"; } + /** + * A delimited-text data column as its declared type ({@link #typedText}), a {@code timestamp} at + * Athena's millisecond precision ({@link #athenaTimestamp}): LazySimpleSerDe reads + * {@code 09:30:00.1235} as {@code 09:30:00.123} on Athena. + */ + private static String typedTextColumn(String text, String glueType) { + String typed = typedText(text, glueType); + return "TIMESTAMP".equals(scalarType(glueType)) ? athenaTimestamp(typed) : typed; + } + + /** + * Whether the view of {@code table} reads a Parquet column as a timestamp, which converts in the + * session's time zone and so is only correct in a UTC session, Athena's own: see + * {@link #parquetTimestamp}. + */ + public static boolean readsParquetTimestamps(Table table) { + return !parquetTimestamps(table).isEmpty(); + } + + /** + * The Parquet data columns {@code table} declares {@code timestamp}, by lowercased name. + * + *

Athena types such a column by its declaration, and DuckDB by what the file stores, which + * differs from it for most writers: a UTC-adjusted timestamp ({@code isAdjustedToUTC}, what + * Spark, pyarrow and DuckDB itself write for a zoned value) reads as + * {@code TIMESTAMP WITH TIME ZONE}, rendered {@code 2026-03-14 09:30:00+00}, and a NANOS one + * (pandas' unit) as {@code TIMESTAMP_NS}, rendered with nine digits. Partition keys are left out: + * their values come from paths or the catalog, not the files. + * + *

A name is resolved to its first declaration, as {@link #buildProjection} projects it. + * + *

TODO: a {@code timestamp} column of a JSON table, or of a delimited-text table read by + * sniffing (no CSV options, see {@link #hasCsvOptions}), is still typed as DuckDB infers it, and a + * {@code timestamp} partition key keeps a value's microseconds where Athena would presumably + * truncate them (unchecked; such values rarely carry a fraction). + */ + private static Map parquetTimestamps(Table table) { + if (table == null || table.getStorageDescriptor() == null || isIcebergTable(table) + || !"read_parquet".equals(inferReadFunction(table)) || table.getStorageDescriptor().getColumns() == null) { + return Map.of(); + } + Map columns = new HashMap<>(columnsByName(table.getStorageDescriptor().getColumns())); + columns.values().removeIf(column -> !"TIMESTAMP".equals(scalarType(column.getType()))); + return columns; + } + + /** + * A Parquet column declared {@code timestamp} as Athena reads it: the UTC wall-clock time at + * millisecond precision ({@link #athenaTimestamp}). {@code column} is the expression reading it, + * {@code name} its declared name. + * + *

A timestamp column is cast to a plain {@code TIMESTAMP}, which every timestamp DuckDB reads + * from Parquet converts to: a UTC-adjusted one (taken at UTC, the session's zone, see + * {@link #readsParquetTimestamps}), MICROS, NANOS and the legacy INT96. A NANOS one that is not + * UTC-adjusted ({@code TIMESTAMP_NS}, pandas' naive unit) is floored to milliseconds first, + * because that cast truncates towards zero, which before 1970 is towards the future: the floor is + * integer arithmetic on {@code epoch_ns}, since DuckDB divides a {@code DECIMAL} as a + * {@code DOUBLE}, which cannot place every nanosecond value in its millisecond. + * + *

A file whose column holds something else reads as on Athena (engine v3), which goes by the + * file's physical type: an INT64 without a logical type is epoch milliseconds, and a string + * (even an ISO one, which DuckDB would cast; DuckDB reads one without the UTF8 annotation as a + * {@code BLOB}) or a {@code DATE} fails the query. DuckDB raises + * neither its own cast's error nor these until it reads a row, and the {@code CASE} on the + * column's type folds away when the query is planned, so a query that does not select the column + * is unaffected, as on Athena, and a timestamp column pays nothing for it. + * + *

TODO: Athena's messages name the file, which this read does not carry, and Athena may fail + * such a query even when no row is selected (unchecked). Other physical types (INT32, DOUBLE, + * BOOLEAN, ...) fail with DuckDB's cast error, where {@code main} read them as that type; what + * Athena makes of them is unchecked. + */ + private static String parquetTimestamp(String column, String name) { + String type = "typeof(" + column + ")"; + String binary = "HIVE_BAD_DATA: Malformed Parquet file. Field " + name + + "'s type BINARY in parquet file is incompatible with type timestamp(3) defined in table schema"; + String date = "SERIALIZATION_ERROR: Could not serialize column '" + name + "' of type 'timestamp(3)'"; + String nanos = "epoch_ns(TRY_CAST(" + column + " AS TIMESTAMP_NS))"; + return athenaTimestamp("CASE WHEN " + type + " = 'BIGINT' THEN epoch_ms(TRY_CAST(" + column + " AS BIGINT))" + + " WHEN " + type + " = 'TIMESTAMP_NS' THEN epoch_ms(" + nanos + " // 1000000 - CASE WHEN " + nanos + + " % 1000000 < 0 THEN 1 ELSE 0 END)" + + " WHEN " + type + " IN ('VARCHAR', 'BLOB') THEN error('" + escape(binary) + "')" + + " WHEN " + type + " = 'DATE' THEN error('" + escape(date) + "')" + + " ELSE CAST(" + column + " AS TIMESTAMP) END"); + } + + /** + * A {@code TIMESTAMP} value at Athena's precision. A Hive table's {@code timestamp} is Trino's + * {@code timestamp(3)} on Athena, which truncates what a file stores to milliseconds, towards + * the past (engine v3: {@code .1235} reads as {@code .123}, {@code 1969-12-31 23:59:59.9995} as + * {@code .999}), as {@code date_trunc} does. DuckDB's {@code TIMESTAMP_MS} would round instead, + * and has no cast from {@code TIMESTAMP_NS}. + * + *

TODO: DuckDB's Parquet reader converts a UTC-adjusted NANOS value to micros towards zero, + * before any SQL sees it, so such a value before 1970 less than a microsecond past a millisecond + * reads one millisecond late. A NANOS value that is not UTC-adjusted is floored exactly + * ({@link #parquetTimestamp}). + */ + private static String athenaTimestamp(String timestamp) { + return "date_trunc('millisecond', " + timestamp + ")"; + } + /** * 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. diff --git a/src/test/java/io/floci/aws/services/athena/AthenaDelimitedTextSidecarIntegrationTest.java b/src/test/java/io/floci/aws/services/athena/AthenaDelimitedTextSidecarIntegrationTest.java index 37e3b56998..aaae12c421 100644 --- a/src/test/java/io/floci/aws/services/athena/AthenaDelimitedTextSidecarIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/athena/AthenaDelimitedTextSidecarIntegrationTest.java @@ -1,10 +1,6 @@ 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.Partition; import io.floci.aws.services.glue.model.StorageDescriptor; import io.floci.aws.services.glue.model.Table; import io.floci.aws.services.s3.S3Service; @@ -16,22 +12,15 @@ 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.nio.charset.StandardCharsets; -import java.util.ArrayList; import java.util.Base64; -import java.util.HashMap; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import static io.floci.aws.services.athena.AthenaSidecarFixture.column; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; /** * Headerless delimited text, the layout Spark writes with {@code partitionBy} and a ZSTD codec, read @@ -52,11 +41,7 @@ class AthenaDelimitedTextSidecarIntegrationTest { @Inject S3Service s3Service; - private String bucket; - private String schema; - private final List keys = new ArrayList<>(); - private final List

tables = new ArrayList<>(); - private final Map> partitions = new HashMap<>(); + private AthenaSidecarFixture glue; @BeforeAll static void requireDocker() { @@ -65,27 +50,23 @@ class AthenaDelimitedTextSidecarIntegrationTest { @BeforeEach void createBucket() { - bucket = "athena-tsv-" + System.nanoTime(); - schema = "tsv_" + System.nanoTime(); - s3Service.createBucket(bucket, "us-east-1"); - put("events/dt=2026-11-14/part-00000.tsv", "1\talice\n2\tbob\n".getBytes(StandardCharsets.UTF_8)); - put("events/dt=2026-11-15/part-00001.tsv.zst", ZSTD_ROW); - tables.add(tsvTable("events", "events")); + glue = new AthenaSidecarFixture(duck, s3Service, "tsv"); + glue.put("events/dt=2026-11-14/part-00000.tsv", "1\talice\n2\tbob\n"); + glue.put("events/dt=2026-11-15/part-00001.tsv.zst", ZSTD_ROW); + glue.add(tsvTable("events", "events")); register("events", "2026-11-14", null); register("events", "2026-11-15", null); } @AfterEach void deleteBucket() { - for (String key : keys) { - s3Service.deleteObject(bucket, key); - } - s3Service.deleteBucket(bucket); + glue.close(); } @Test void headerlessTsvReturnsRowsUnderTheGlueColumnNamesAndTypes() { - List> rows = query("SELECT id, name, dt, typeof(id) AS id_type FROM " + view("events") + List> rows = glue.query("SELECT id, name, dt, typeof(id) AS id_type FROM " + + glue.view("events") + " ORDER BY id"); assertEquals(List.of( @@ -104,13 +85,13 @@ class AthenaDelimitedTextSidecarIntegrationTest { broken.getStorageDescriptor().setInputFormat("org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat"); broken.getStorageDescriptor().getSerdeInfo() .setSerializationLibrary("org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe"); - tables.add(broken); + glue.add(broken); register("not_parquet", "2026-11-14", null); - String sql = "SELECT count(*) AS n FROM " + view("events"); + String sql = "SELECT count(*) AS n FROM " + glue.view("events"); - assertThrows(RuntimeException.class, () -> duck.query(sql, builder().build(null)), + assertThrows(RuntimeException.class, () -> duck.query(sql, glue.builder().build(null)), "with every table's view in the batch, the broken one fails the query"); - assertEquals(List.of(Map.of("n", "3")), query(sql)); + assertEquals(List.of(Map.of("n", "3")), glue.query(sql)); } /** @@ -119,16 +100,16 @@ class AthenaDelimitedTextSidecarIntegrationTest { */ @Test void delimitedTextRowsReadAsLazySimpleSerDeReadsThem() { - put("evolved/dt=2026-11-16/part-00000.tsv", - "1\talice\n2\t\\N\tx\n3\t\tx\n4\tdave\tn\textra\n".getBytes(StandardCharsets.UTF_8)); + glue.put("evolved/dt=2026-11-16/part-00000.tsv", + "1\talice\n2\t\\N\tx\n3\t\tx\n4\tdave\tn\textra\n"); Table evolved = tsvTable("evolved", "evolved"); evolved.getStorageDescriptor().setColumns(List.of(column("id", "bigint"), column("name", "string"), column("note", "string"))); - tables.add(evolved); + glue.add(evolved); register("evolved", "2026-11-16", null); - List> rows = query("SELECT id, name, name IS NULL AS name_null, note FROM " - + view("evolved") + " ORDER BY id"); + List> rows = glue.query("SELECT id, name, name IS NULL AS name_null, note FROM " + + glue.view("evolved") + " ORDER BY id"); assertEquals(List.of( Map.of("id", "1", "name", "alice", "name_null", "false", "note", "null"), @@ -143,26 +124,27 @@ class AthenaDelimitedTextSidecarIntegrationTest { */ @Test void aTableWhoseLocationHoldsNoDataAnswersNoRows() { - put("marked/", new byte[0]); + glue.put("marked/", new byte[0]); for (String name : List.of("nothing", "marked")) { Table table = tsvTable(name, name); table.setPartitionKeys(List.of()); - tables.add(table); + glue.add(table); } for (String table : List.of("nothing", "marked")) { - assertEquals(List.of(Map.of("n", "0", "id_type", "BIGINT", "name_type", "VARCHAR")), query( + assertEquals(List.of(Map.of("n", "0", "id_type", "BIGINT", "name_type", "VARCHAR")), glue.query( "SELECT count(*) AS n, typeof(max(id)) AS id_type, typeof(max(name)) AS name_type FROM " - + view(table)), table); + + glue.view(table)), table); } Table nested = tsvTable("nested", "nested"); nested.setPartitionKeys(List.of()); nested.getStorageDescriptor().setColumns(List.of(column("tags", "array"), column("who", "struct"))); - tables.add(nested); + glue.add(nested); assertEquals(List.of(Map.of("tags_type", "VARCHAR[]", "age_type", "INTEGER")), - query("SELECT typeof(any_value(tags)) AS tags_type, typeof(any_value(who).age) AS age_type FROM " - + view("nested"))); + glue.query("SELECT typeof(any_value(tags)) AS tags_type, typeof(any_value(who).age) AS age_type" + + " FROM " + + glue.view("nested"))); } /** @@ -172,26 +154,26 @@ class AthenaDelimitedTextSidecarIntegrationTest { */ @Test void aPartitionedTableIsReadThroughItsRegisteredPartitions() { - put("loaded/dt=2026-11-14/part-0.tsv", "1\talice\n".getBytes(StandardCharsets.UTF_8)); - put("loaded/dt=2026-11-15/part-0.tsv", "2\tbob\n".getBytes(StandardCharsets.UTF_8)); - put("archive/2026/11/16/part-0.tsv", "3\tcarol\n".getBytes(StandardCharsets.UTF_8)); - tables.add(tsvTable("loaded", "loaded")); + glue.put("loaded/dt=2026-11-14/part-0.tsv", "1\talice\n"); + glue.put("loaded/dt=2026-11-15/part-0.tsv", "2\tbob\n"); + glue.put("archive/2026/11/16/part-0.tsv", "3\tcarol\n"); + glue.add(tsvTable("loaded", "loaded")); register("loaded", "2026-11-14", null); - register("loaded", "2026-11-16", "s3://" + bucket + "/archive/2026/11/16/"); + register("loaded", "2026-11-16", "s3://" + glue.bucket() + "/archive/2026/11/16/"); assertEquals(List.of(Map.of("id", "1", "name", "alice", "dt", "2026-11-14"), Map.of("id", "3", "name", "carol", "dt", "2026-11-16")), - query("SELECT id, name, dt FROM " + view("loaded") + " ORDER BY id")); - tables.add(tsvTable("unloaded", "loaded")); - assertEquals(List.of(Map.of("n", "0")), query("SELECT count(*) AS n FROM " + view("unloaded"))); + glue.query("SELECT id, name, dt FROM " + glue.view("loaded") + " ORDER BY id")); + glue.add(tsvTable("unloaded", "loaded")); + assertEquals(List.of(Map.of("n", "0")), glue.query("SELECT count(*) AS n FROM " + glue.view("unloaded"))); // A value its key's type cannot hold fails the query as Athena's does. Table typed = tsvTable("typed", "loaded"); typed.setPartitionKeys(List.of(column("dt", "date"))); - tables.add(typed); - register("typed", "soon", "s3://" + bucket + "/archive/2026/11/16/"); + glue.add(typed); + register("typed", "soon", "s3://" + glue.bucket() + "/archive/2026/11/16/"); RuntimeException invalid = assertThrows(RuntimeException.class, - () -> query("SELECT count(*) AS n FROM " + view("typed"))); + () -> glue.query("SELECT count(*) AS n FROM " + glue.view("typed"))); assertTrue(invalid.getMessage().contains( "HIVE_INVALID_PARTITION_VALUE: Invalid partition value 'soon' for DATE partition key: dt=soon"), invalid.getMessage()); @@ -201,17 +183,12 @@ class AthenaDelimitedTextSidecarIntegrationTest { /** Registers a partition of {@code table} for {@code dt}, at {@code location} or, when null, its default folder. */ private void register(String table, String dt, String location) { - partitions.computeIfAbsent(table, ignored -> new ArrayList<>()).add(GluePartitions.partition(location, dt)); - } - - private void put(String key, byte[] content) { - s3Service.putObject(bucket, key, content, "application/octet-stream", null); - keys.add(key); + glue.register(table, GluePartitions.partition(location, dt)); } private Table tsvTable(String name, String root) { StorageDescriptor descriptor = new StorageDescriptor(); - descriptor.setLocation("s3://" + bucket + "/" + root + "/"); + descriptor.setLocation("s3://" + glue.bucket() + "/" + root + "/"); descriptor.setInputFormat("org.apache.hadoop.mapred.TextInputFormat"); StorageDescriptor.SerDeInfo serde = new StorageDescriptor.SerDeInfo(); serde.setSerializationLibrary("org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe"); @@ -224,38 +201,4 @@ class AthenaDelimitedTextSidecarIntegrationTest { table.setPartitionKeys(List.of(column("dt", "string"))); return table; } - - private GlueViewDdlBuilder builder() { - 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); - when(glue.getPartitions(eq(schema), anyString())) - .thenAnswer(call -> partitions.getOrDefault(call.getArgument(1), List.of())); - return new GlueViewDdlBuilder(glue, s3Service); - } - - private List> query(String sql) { - String views = builder().build(null, sql); - - List> rows = new ArrayList<>(); - for (Map row : duck.query(sql, views)) { - Map 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; - } } 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 e1ad4d95d5..47b0f6dbf5 100644 --- a/src/test/java/io/floci/aws/services/athena/AthenaPartitionTemplateSidecarIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/athena/AthenaPartitionTemplateSidecarIntegrationTest.java @@ -1,9 +1,7 @@ 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; @@ -15,7 +13,6 @@ 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; @@ -23,8 +20,8 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import static io.floci.aws.services.athena.AthenaSidecarFixture.column; 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 @@ -33,11 +30,8 @@ import static org.mockito.Mockito.when; *

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. - * - *

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. + * the default {@code column=value} layout is the control. The tables are queried through + * {@link AthenaSidecarFixture}. */ @QuarkusTest @TestProfile(SidecarContainersProfile.class) @@ -60,10 +54,7 @@ class AthenaPartitionTemplateSidecarIntegrationTest { @Inject S3Service s3Service; - private String bucket; - private String schema; - private final List keys = new ArrayList<>(); - private final List

tables = new ArrayList<>(); + private AthenaSidecarFixture glue; @BeforeAll static void requireDocker() { @@ -72,17 +63,12 @@ class AthenaPartitionTemplateSidecarIntegrationTest { @BeforeEach void createBucket() { - bucket = "athena-template-" + System.nanoTime(); - schema = "template_" + System.nanoTime(); - s3Service.createBucket(bucket, "us-east-1"); + glue = new AthenaSidecarFixture(duck, s3Service, "template"); } @AfterEach void deleteBucket() { - for (String key : keys) { - s3Service.deleteObject(bucket, key); - } - s3Service.deleteBucket(bucket); + glue.close(); } @Test @@ -103,8 +89,8 @@ class AthenaPartitionTemplateSidecarIntegrationTest { "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"))); + glue.query("SELECT region, typeof(region) AS region_type, typeof(dt) AS dt_type FROM " + + glue.view("sales_typed"))); } /** A date projected with a format in the default layout is read through that format: dt=20260314 is March 14. */ @@ -161,8 +147,8 @@ class AthenaPartitionTemplateSidecarIntegrationTest { "bare/eu/2026-03-14/part.parquet", "bare/us/2026-03-15/part.parquet", "bare/eu/latest/part.parquet"); - List> rows = query("SELECT region, CAST(dt AS VARCHAR) AS dt " - + "FROM " + view("sales_bare") + " ORDER BY region"); + List> rows = glue.query("SELECT region, CAST(dt AS VARCHAR) AS dt " + + "FROM " + glue.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); @@ -184,12 +170,12 @@ class AthenaPartitionTemplateSidecarIntegrationTest { 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}/"); + parameters.put("storage.location.template", "s3://" + glue.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") + glue.query("SELECT id, datehour FROM " + glue.view("sales_firehose") + " WHERE datehour = '2026/11/10/05'")); } @@ -206,13 +192,13 @@ class AthenaPartitionTemplateSidecarIntegrationTest { 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}/"); + parameters.put("storage.location.template", "s3://" + glue.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'")); + glue.query("SELECT id, region, dt FROM " + glue.view("sales_nested") + " WHERE region = 'eu'")); } /** @@ -229,7 +215,7 @@ class AthenaPartitionTemplateSidecarIntegrationTest { 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/"); + StringBuilder template = new StringBuilder("s3://" + glue.bucket() + "/deep/"); List partitionKeys = new ArrayList<>(); for (String key : hierarchy) { template.append("${").append(key).append("}/"); @@ -259,7 +245,7 @@ class AthenaPartitionTemplateSidecarIntegrationTest { 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); + parameters.put("storage.location.template", "s3://" + glue.bucket() + "/" + template); } register(name, root, parameters, List.of(column("region", "string"), column("dt", "date")), objectKeys); } @@ -268,11 +254,10 @@ class AthenaPartitionTemplateSidecarIntegrationTest { private void register(String name, String root, Map parameters, List partitionKeys, String... objectKeys) { for (String key : objectKeys) { - s3Service.putObject(bucket, key, PARQUET, "application/octet-stream", null); - keys.add(key); + glue.put(key, PARQUET); } StorageDescriptor descriptor = new StorageDescriptor(); - descriptor.setLocation("s3://" + bucket + "/" + root + "/"); + descriptor.setLocation("s3://" + glue.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"); @@ -283,40 +268,12 @@ class AthenaPartitionTemplateSidecarIntegrationTest { table.setStorageDescriptor(descriptor); table.setPartitionKeys(partitionKeys); table.setParameters(parameters); - tables.add(table); + glue.add(table); } /** A typical projected-partition query, with the equality filter an injected key requires. */ private List> queryEuInMarch(String table) { - return query("SELECT id, region, CAST(dt AS VARCHAR) AS dt FROM " + view(table) + return glue.query("SELECT id, region, CAST(dt AS VARCHAR) AS dt FROM " + glue.view(table) + " WHERE region = 'eu' AND dt BETWEEN DATE '2026-03-01' AND DATE '2026-03-31'"); } - - private List> 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, s3Service).build(null); - - List> rows = new ArrayList<>(); - for (Map row : duck.query(sql, views)) { - Map 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; - } } diff --git a/src/test/java/io/floci/aws/services/athena/AthenaServiceTest.java b/src/test/java/io/floci/aws/services/athena/AthenaServiceTest.java index df0ba85907..9019f79e31 100644 --- a/src/test/java/io/floci/aws/services/athena/AthenaServiceTest.java +++ b/src/test/java/io/floci/aws/services/athena/AthenaServiceTest.java @@ -214,6 +214,36 @@ class AthenaServiceTest { .map(ResultSet.ColumnInfo::getType).toList()); } + /** + * Athena (engine v3) renders a timestamp column as {@code 2026-03-14 09:30:00.000}; DuckDB writes + * {@code 2026-03-14 09:30:00}. Every timestamp variant is padded to milliseconds, a longer + * fraction is kept, and other types, a timestamp with a time zone among them, are left alone. + */ + @Test + void getQueryResultsRendersTimestampsWithAtLeastMilliseconds() throws Exception { + String query = "SELECT ts, ts_ms, ts_us, ts_tz, s FROM times"; + when(duckClient.query(eq("DESCRIBE " + query), any(), any())).thenReturn(List.of( + Map.of("column_name", "ts", "column_type", "TIMESTAMP"), + Map.of("column_name", "ts_ms", "column_type", "TIMESTAMP_MS"), + Map.of("column_name", "ts_us", "column_type", "TIMESTAMP"), + Map.of("column_name", "ts_tz", "column_type", "TIMESTAMP WITH TIME ZONE"), + Map.of("column_name", "s", "column_type", "VARCHAR"))); + + ResultSet results = results(query, "ts,ts_ms,ts_us,ts_tz,s\n" + + "2026-03-14 09:30:00,2026-11-12 20:22:54.3,2026-11-12 20:22:54.385678," + + "2026-03-14 09:30:00+00,2026-03-14 09:30:00\n" + + ",infinity,,,\n"); + + assertEquals(List.of( + List.of("ts", "ts_ms", "ts_us", "ts_tz", "s"), + List.of("2026-03-14 09:30:00.000", "2026-11-12 20:22:54.300", "2026-11-12 20:22:54.385678", + "2026-03-14 09:30:00+00", "2026-03-14 09:30:00"), + List.of("", "infinity", "", "", "")), + results.getRows().stream() + .map(row -> row.getData().stream().map(ResultSet.Datum::getVarCharValue).toList()) + .toList()); + } + @Test void getQueryResultsReportsVarcharWhenTheTypesCannotBeDescribed() throws Exception { when(duckClient.query(anyString(), any(), any())).thenThrow(new IllegalStateException("not describable")); @@ -223,6 +253,10 @@ class AthenaServiceTest { } private List columnInfo(String query, String csv) throws Exception { + return results(query, csv).getMetadata().getColumnInfo(); + } + + private ResultSet results(String query, String csv) throws Exception { String id = service.startQueryExecution(query, "primary", null, new ResultConfiguration("s3://athena-results/")); awaitState(id, QueryExecutionState.SUCCEEDED); @@ -232,7 +266,7 @@ class AthenaServiceTest { when(s3Service.listObjects(eq("athena-results"), anyString(), any(), anyInt())).thenReturn(List.of(result)); when(s3Service.getObject("athena-results", key)).thenReturn(result); - return service.getQueryResults(id).getMetadata().getColumnInfo(); + return service.getQueryResults(id); } private void awaitState(String id, QueryExecutionState expected) throws InterruptedException { diff --git a/src/test/java/io/floci/aws/services/athena/AthenaSidecarFixture.java b/src/test/java/io/floci/aws/services/athena/AthenaSidecarFixture.java new file mode 100644 index 0000000000..e89aa0e083 --- /dev/null +++ b/src/test/java/io/floci/aws/services/athena/AthenaSidecarFixture.java @@ -0,0 +1,122 @@ +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.Partition; +import io.floci.aws.services.glue.model.Table; +import io.floci.aws.services.s3.S3Service; +import org.mockito.Mockito; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +/** + * A bucket and one Glue database of tables for the Athena sidecar tests, queried through the real floci-duck sidecar + * with the views {@link GlueViewDdlBuilder} builds for them. + * + *

The views come from the builder 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. Each test creates its own fixture and closes it, which deletes what it put. + */ +final class AthenaSidecarFixture implements AutoCloseable { + + private final FlociDuckClient duck; + private final S3Service s3Service; + private final String bucket; + private final String schema; + private final List keys = new ArrayList<>(); + private final List

tables = new ArrayList<>(); + private final Map> partitions = new HashMap<>(); + + /** Creates a bucket and names a database, both unique to this fixture and starting with {@code name}. */ + AthenaSidecarFixture(FlociDuckClient duck, S3Service s3Service, String name) { + this.duck = duck; + this.s3Service = s3Service; + this.bucket = "athena-" + name + "-" + System.nanoTime(); + this.schema = name + "_" + System.nanoTime(); + s3Service.createBucket(bucket, "us-east-1"); + } + + String bucket() { + return bucket; + } + + /** Puts {@code content} at {@code key} in the bucket. */ + void put(String key, byte[] content) { + s3Service.putObject(bucket, key, content, "application/octet-stream", null); + keys.add(key); + } + + void put(String key, String content) { + put(key, content.getBytes(StandardCharsets.UTF_8)); + } + + /** Records an object something other than {@link #put} wrote to the bucket, so that it is deleted too. */ + void wrote(String key) { + keys.add(key); + } + + /** Adds {@code table} to the database. */ + void add(Table table) { + tables.add(table); + } + + /** Registers {@code partition} for {@code table}. */ + void register(String table, Partition partition) { + partitions.computeIfAbsent(table, ignored -> new ArrayList<>()).add(partition); + } + + /** A view builder over the database's tables and their registered partitions. */ + GlueViewDdlBuilder builder() { + 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); + when(glue.getPartitions(eq(schema), anyString())) + .thenAnswer(call -> partitions.getOrDefault(call.getArgument(1), List.of())); + return new GlueViewDdlBuilder(glue, s3Service); + } + + /** Runs {@code sql} with the views Athena builds for it, each value as text ({@code "null"} for NULL). */ + List> query(String sql) { + List> rows = new ArrayList<>(); + for (Map row : duck.query(sql, builder().build(null, sql))) { + Map values = new LinkedHashMap<>(); + row.forEach((column, value) -> values.put(column, String.valueOf(value))); + rows.add(values); + } + return rows; + } + + /** The qualified name of {@code table}'s view. */ + String view(String table) { + return "\"" + schema + "\".\"" + table + "\""; + } + + /** Deletes the objects put in the bucket, then the bucket. */ + @Override + public void close() { + for (String key : keys) { + s3Service.deleteObject(bucket, key); + } + s3Service.deleteBucket(bucket); + } + + static Column column(String name, String type) { + Column column = new Column(); + column.setName(name); + column.setType(type); + return column; + } +} diff --git a/src/test/java/io/floci/aws/services/athena/AthenaTimestampColumnSidecarIntegrationTest.java b/src/test/java/io/floci/aws/services/athena/AthenaTimestampColumnSidecarIntegrationTest.java new file mode 100644 index 0000000000..c8577c7570 --- /dev/null +++ b/src/test/java/io/floci/aws/services/athena/AthenaTimestampColumnSidecarIntegrationTest.java @@ -0,0 +1,225 @@ +package io.floci.aws.services.athena; + +import io.floci.aws.services.floci.duck.FlociDuckClient; +import io.floci.aws.services.glue.model.Column; +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 java.util.List; +import java.util.Map; + +import static io.floci.aws.services.athena.AthenaSidecarFixture.column; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Reads columns declared {@code timestamp} through the real floci-duck sidecar, with the views Athena builds, and + * checks them against what Athena (engine v3) returns for the same values: a Hive table's {@code timestamp} is + * Trino's {@code timestamp(3)}, the UTC wall-clock time truncated to milliseconds towards the past, whatever the file + * stores. + * + *

The Parquet file is written by DuckDB, as writers commonly store a timestamp: {@code ts} UTC-adjusted + * ({@code isAdjustedToUTC}, MICROS), which DuckDB reads as {@code TIMESTAMP WITH TIME ZONE}, and {@code ts_ns} with + * nanoseconds (pandas' unit), which it reads as {@code TIMESTAMP_NS}. + */ +@QuarkusTest +@TestProfile(SidecarContainersProfile.class) +class AthenaTimestampColumnSidecarIntegrationTest { + + /** + * The rows of every table here, by id: whole seconds, a half millisecond, before the epoch, NULL, and a value one + * nanosecond (and one millisecond and one nanosecond) before the epoch, which truncating towards zero would put + * in the following millisecond. Row 2's {@code .123999999} is a nanosecond short of the next millisecond. + */ + private static final String ROWS = """ + SELECT * FROM (VALUES + (1, TIMESTAMPTZ '2026-03-14 09:30:00+00', TIMESTAMP_NS '2026-03-14 09:30:00'), + (2, TIMESTAMPTZ '2026-03-14 09:30:00.1235+00', TIMESTAMP_NS '2026-03-14 09:30:00.123999999'), + (3, TIMESTAMPTZ '1969-12-31 23:59:59.9995+00', TIMESTAMP_NS '1969-12-31 23:59:59.9995'), + (4, CAST(NULL AS TIMESTAMPTZ), CAST(NULL AS TIMESTAMP_NS)), + (5, TIMESTAMPTZ '1969-12-31 23:59:59.999999+00', TIMESTAMP_NS '1969-12-31 23:59:59.999999999'), + (6, TIMESTAMPTZ '1969-12-31 23:59:59.998999+00', TIMESTAMP_NS '1969-12-31 23:59:59.998999999') + ) AS t (id, ts, ts_ns)"""; + + /** + * The values Athena returns for {@link #ROWS}, read here with DuckDB's {@code CAST(... AS VARCHAR)}, which drops a + * zero fraction that {@code GetQueryResults} pads ({@code 09:30:00.000} on Athena), and each column's type. + */ + private static final List> EXPECTED = List.of( + row("1", "2026-03-14 09:30:00", "2026-03-14 09:30:00"), + row("2", "2026-03-14 09:30:00.123", "2026-03-14 09:30:00.123"), + row("3", "1969-12-31 23:59:59.999", "1969-12-31 23:59:59.999"), + row("4", "null", "null"), + row("5", "1969-12-31 23:59:59.999", "1969-12-31 23:59:59.999"), + row("6", "1969-12-31 23:59:59.998", "1969-12-31 23:59:59.998")); + + private static final String SELECT = "SELECT id, CAST(ts AS VARCHAR) AS ts, CAST(ts_ns AS VARCHAR) AS ts_ns," + + " typeof(ts) AS ts_type, typeof(ts_ns) AS ts_ns_type FROM "; + + @Inject + FlociDuckClient duck; + + @Inject + S3Service s3Service; + + private AthenaSidecarFixture glue; + + @BeforeAll + static void requireDocker() { + SidecarContainersProfile.requireDocker(); + } + + @BeforeEach + void createBucket() { + glue = new AthenaSidecarFixture(duck, s3Service, "timestamp"); + } + + @AfterEach + void deleteBucket() { + glue.close(); + } + + @Test + void parquetColumnsDeclaredTimestampReadAsAthenasTimestamp() { + writeParquet("events/part-0.parquet"); + glue.add(parquetTable("events", List.of())); + + assertEquals(EXPECTED, glue.query(SELECT + glue.view("events") + " ORDER BY id")); + } + + /** The views pin the session to UTC, so a session that starts in another zone still reads UTC. */ + @Test + void theUtcWallClockTimeDoesNotDependOnTheSessionsZone() { + writeParquet("events/part-0.parquet"); + glue.add(parquetTable("events", List.of())); + String sql = "SELECT CAST(ts AS VARCHAR) AS ts FROM " + glue.view("events") + " WHERE id = 1"; + + List> rows = duck.query(sql, "SET TimeZone = 'America/Toronto';\n" + + glue.builder().build(null, sql)); + + assertEquals("2026-03-14 09:30:00", rows.getFirst().get("ts")); + } + + /** A partitioned table, read through its registered partitions, types its data columns the same way. */ + @Test + void aPartitionedTableReadsItsTimestampsTheSameWay() { + writeParquet("events/dt=2026-03-14/part-0.parquet"); + glue.add(parquetTable("events", List.of(column("dt", "string")))); + glue.register("events", GluePartitions.partition(null, "2026-03-14")); + + assertEquals(EXPECTED, glue.query(SELECT + glue.view("events") + " ORDER BY id")); + } + + /** An empty table, which reads no files, gives its columns the type a full one does. */ + @Test + void anEmptyTableTypesItsTimestampsAsAFullOneDoes() { + glue.add(parquetTable("events", List.of())); + + assertEquals(List.of(Map.of("ts_type", "TIMESTAMP", "ts_ns_type", "TIMESTAMP")), glue.query( + "SELECT typeof(any_value(ts)) AS ts_type, typeof(any_value(ts_ns)) AS ts_ns_type FROM " + + glue.view("events"))); + } + + /** Delimited text has the same precision: LazySimpleSerDe reads {@code .1235} as {@code .123} on Athena too. */ + @Test + void delimitedTextTimestampsReadAtMillisecondPrecision() { + glue.put("text/part-0.tsv", "1\t2026-03-14 09:30:00.1235\n2\t1969-12-31 23:59:59.9995\n3\t\\N\n"); + StorageDescriptor descriptor = descriptor("text"); + descriptor.setInputFormat("org.apache.hadoop.mapred.TextInputFormat"); + StorageDescriptor.SerDeInfo serde = new StorageDescriptor.SerDeInfo(); + serde.setSerializationLibrary("org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe"); + serde.setParameters(Map.of("field.delim", "\t")); + descriptor.setSerdeInfo(serde); + descriptor.setColumns(List.of(column("id", "int"), column("ts", "timestamp"))); + glue.add(table("text", descriptor, List.of())); + + assertEquals(List.of( + Map.of("id", "1", "ts", "2026-03-14 09:30:00.123", "ts_type", "TIMESTAMP"), + Map.of("id", "2", "ts", "1969-12-31 23:59:59.999", "ts_type", "TIMESTAMP"), + Map.of("id", "3", "ts", "null", "ts_type", "TIMESTAMP")), + glue.query("SELECT id, CAST(ts AS VARCHAR) AS ts, typeof(ts) AS ts_type FROM " + glue.view("text") + + " ORDER BY id")); + } + + /** + * A file whose column declared {@code timestamp} holds something else reads as on Athena (engine v3), which goes + * by the file's physical type: an INT64 without a logical type is epoch milliseconds, and a string, even an ISO + * one, binary or a date fails the query that selects it, and only that query. + */ + @Test + void aColumnStoredAsAnotherTypeReadsAsOnAthena() { + writeParquet("mismatch/part-0.parquet", "SELECT 1 AS id, CAST(1773480600000 AS BIGINT) AS epoch," + + " '2026-03-14 09:30:00' AS iso, DATE '2026-03-14' AS day, CAST('raw' AS BLOB) AS raw"); + Table table = parquetTable("mismatch", List.of()); + table.getStorageDescriptor().setColumns(List.of(column("id", "int"), column("epoch", "timestamp"), + column("iso", "timestamp"), column("day", "timestamp"), column("raw", "timestamp"))); + glue.add(table); + + assertEquals(List.of(Map.of("id", "1")), glue.query("SELECT id FROM " + glue.view("mismatch"))); + assertEquals(List.of(Map.of("epoch", "2026-03-14 09:30:00")), + glue.query("SELECT CAST(epoch AS VARCHAR) AS epoch FROM " + glue.view("mismatch"))); + RuntimeException iso = assertThrows(RuntimeException.class, + () -> glue.query("SELECT iso FROM " + glue.view("mismatch"))); + assertTrue(iso.getMessage().contains("HIVE_BAD_DATA: Malformed Parquet file. Field iso's type BINARY in parquet" + + " file is incompatible with type timestamp(3) defined in table schema"), iso.getMessage()); + RuntimeException raw = assertThrows(RuntimeException.class, + () -> glue.query("SELECT raw FROM " + glue.view("mismatch"))); + assertTrue(raw.getMessage().contains("HIVE_BAD_DATA: Malformed Parquet file. Field raw's type BINARY"), + raw.getMessage()); + RuntimeException day = assertThrows(RuntimeException.class, + () -> glue.query("SELECT day FROM " + glue.view("mismatch"))); + assertTrue(day.getMessage().contains( + "SERIALIZATION_ERROR: Could not serialize column 'day' of type 'timestamp(3)'"), day.getMessage()); + } + + // ---- helpers ---- + + /** Writes {@link #ROWS} to {@code key} as Parquet, through the sidecar. */ + private void writeParquet(String key) { + writeParquet(key, ROWS); + } + + /** Writes the rows {@code select} gives to {@code key} as Parquet, through the sidecar. */ + private void writeParquet(String key, String select) { + duck.query("COPY (" + select + ") TO 's3://" + glue.bucket() + "/" + key + "' (FORMAT PARQUET)", null); + glue.wrote(key); + } + + private Table parquetTable(String name, List partitionKeys) { + StorageDescriptor descriptor = descriptor(name); + 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", "int"), column("ts", "timestamp"), column("ts_ns", "timestamp"))); + return table(name, descriptor, partitionKeys); + } + + private StorageDescriptor descriptor(String root) { + StorageDescriptor descriptor = new StorageDescriptor(); + descriptor.setLocation("s3://" + glue.bucket() + "/" + root + "/"); + return descriptor; + } + + private static Table table(String name, StorageDescriptor descriptor, List partitionKeys) { + Table table = new Table(); + table.setName(name); + table.setStorageDescriptor(descriptor); + table.setPartitionKeys(partitionKeys); + return table; + } + + private static Map row(String id, String ts, String tsNs) { + return Map.of("id", id, "ts", ts, "ts_ns", tsNs, "ts_type", "TIMESTAMP", "ts_ns_type", "TIMESTAMP"); + } +} 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 6f38bc12a0..f7ab7d5848 100644 --- a/src/test/java/io/floci/aws/services/athena/GlueViewDdlBuilderTest.java +++ b/src/test/java/io/floci/aws/services/athena/GlueViewDdlBuilderTest.java @@ -176,6 +176,35 @@ class GlueViewDdlBuilderTest { return table; } + /** + * Reading a Parquet timestamp converts in the session's time zone, so a batch holding such a view pins Athena's, + * UTC, whether the table is read whole, through its registered partitions, or is empty; others leave it alone. + */ + @Test + void viewsReadingParquetTimestampsRunInAUtcSession() { + Table plain = projectingParquetTable("s3://b/data/", Map.of()); + plain.setPartitionKeys(List.of()); + plain.getStorageDescriptor().setColumns(List.of(column("id"), column("created_at", "timestamp"))); + Table registered = projectingParquetTable("s3://b/data/", Map.of()); + registered.getStorageDescriptor().setColumns(List.of(column("id"), column("created_at", "timestamp"))); + when(glueService.getPartitions("audit", "events")).thenReturn(List.of(partition(null, "a", "b"))); + Table empty = projectingParquetTable("s3://empty/data/", Map.of()); + empty.setPartitionKeys(List.of()); + empty.getStorageDescriptor().setColumns(List.of(column("created_at", "timestamp"))); + holds("empty", "data/"); + + Map paths = Map.of(plain, "FROM read_parquet('s3://b/data/**'", registered, "JOIN (VALUES", + empty, "LIMIT 0"); + for (Table table : List.of(plain, registered, empty)) { + String ddl = ddlFor(table); + assertTrue(ddl.contains(paths.get(table)), ddl); + assertTrue(ddl.startsWith("SET TimeZone = 'UTC';\nCREATE SCHEMA"), ddl); + assertEquals(1, ddl.split("TimeZone", -1).length - 1, ddl); + } + assertTrue(ddlFor(plain).contains("ELSE CAST(\"created_at\" AS TIMESTAMP) END) AS \"created_at\"")); + assertFalse(ddlFor(projectingParquetTable("s3://b/data/", Map.of())).contains("TimeZone")); + } + /** * 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 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 b33f29bbfe..1a7d2ec34f 100644 --- a/src/test/java/io/floci/aws/services/glue/GlueTableResolverTest.java +++ b/src/test/java/io/floci/aws/services/glue/GlueTableResolverTest.java @@ -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.not; import static org.hamcrest.Matchers.nullValue; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -206,6 +207,96 @@ class GlueTableResolverTest { assertThat(GlueTableResolver.buildProjection(iceberg), equalTo("\"id\" AS \"id\", \"region\" AS \"region\"")); } + private static final String PARQUET_FORMAT = "org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat"; + + /** + * How the view reads Parquet column {@code name} declared {@code timestamp}, through {@code column}: by the file's + * physical type, as Athena does, a timestamp truncated to milliseconds, an INT64 as epoch milliseconds, and a + * string or a date failing with Athena's error. + */ + private static String parquetTimestamp(String column, String name) { + String nanos = "epoch_ns(TRY_CAST(" + column + " AS TIMESTAMP_NS))"; + return "date_trunc('millisecond', CASE WHEN typeof(" + column + ") = 'BIGINT' THEN epoch_ms(TRY_CAST(" + column + + " AS BIGINT)) WHEN typeof(" + column + ") = 'TIMESTAMP_NS' THEN epoch_ms(" + nanos + " // 1000000 -" + + " CASE WHEN " + nanos + " % 1000000 < 0 THEN 1 ELSE 0 END)" + + " WHEN typeof(" + column + ") IN ('VARCHAR', 'BLOB') THEN error('HIVE_BAD_DATA: Malformed" + + " Parquet file." + + " Field " + name + "''s type BINARY in parquet file is incompatible with type timestamp(3) defined in" + + " table schema') WHEN typeof(" + column + ") = 'DATE' THEN error('SERIALIZATION_ERROR: Could not" + + " serialize column ''" + name + "'' of type ''timestamp(3)''') ELSE CAST(" + column + " AS TIMESTAMP)" + + " END)"; + } + + /** + * Athena reads a column declared {@code timestamp} as {@code timestamp(3)}, the UTC wall-clock time truncated to + * milliseconds, where DuckDB types a Parquet column by what the file stores (a UTC-adjusted one as + * {@code TIMESTAMP WITH TIME ZONE}, a NANOS one as {@code TIMESTAMP_NS}). + */ + @Test + void parquetColumnsDeclaredTimestampReadAsAthenasTimestamp() { + Table table = table(PARQUET_FORMAT, "s3://bucket/events/", + List.of(column("id", "string"), column("created_at", "TIMESTAMP"), column("day", "date"))); + + assertThat(GlueTableResolver.buildProjection(table), equalTo("\"id\" AS \"id\", " + + parquetTimestamp("\"created_at\"", "created_at") + " AS \"created_at\", \"day\" AS \"day\"")); + assertThat(GlueTableResolver.readsParquetTimestamps(table), is(true)); + } + + /** A name declared twice, in two cases, resolves to its first declaration, which is the column projected. */ + @Test + void aNameDeclaredTwiceIsTypedByItsFirstDeclaration() { + Table table = table(PARQUET_FORMAT, "s3://bucket/events/", + List.of(column("ts", "string"), column("TS", "timestamp"))); + + assertThat(GlueTableResolver.buildProjection(table), equalTo("\"ts\" AS \"ts\"")); + assertThat(GlueTableResolver.readsParquetTimestamps(table), is(false)); + } + + /** A table read through its registered partitions types its data columns the same way; its keys come from Glue. */ + @Test + void registeredPartitionReadsTypeParquetTimestampsTheSameWay() { + Table table = table(PARQUET_FORMAT, "s3://bucket/events/", List.of(column("created_at", "timestamp"))); + table.setPartitionKeys(List.of(column("dt", "string"))); + + String select = GlueTableResolver.registeredPartitionsSelect(table, + List.of(new GlueTableResolver.RegisteredPartition("s3://bucket/events/dt=a", List.of("a")))); + + assertThat(select, containsString( + "SELECT " + parquetTimestamp("r.\"created_at\"", "created_at") + " AS \"created_at\", " + + "p.\"dt\" AS \"dt\" FROM read_parquet(")); + } + + /** Delimited text, which is read as text and cast to the declared types, has the same precision on Athena. */ + @Test + void delimitedTextTimestampsReadAtMillisecondPrecision() { + Table table = table("org.apache.hadoop.mapred.TextInputFormat", "s3://bucket/events/", + List.of(column("id", "int"), column("created_at", "timestamp"))); + table.getStorageDescriptor().setSerdeInfo(new StorageDescriptor.SerDeInfo()); + table.getStorageDescriptor().getSerdeInfo().setParameters(Map.of("field.delim", "\t")); + + assertThat(GlueTableResolver.buildProjection(table), equalTo("TRY_CAST(\"id\" AS INTEGER) AS \"id\", " + + "date_trunc('millisecond', TRY_CAST(\"created_at\" AS TIMESTAMP)) AS \"created_at\"")); + assertThat(GlueTableResolver.readsParquetTimestamps(table), is(false)); + } + + /** JSON, Iceberg tables and partition keys keep their projection. */ + @Test + void timestampsOutsideParquetAndTextDataColumnsKeepTheirProjection() { + Table json = table("org.apache.hadoop.mapred.TextInputFormat", "s3://bucket/events/", + List.of(column("created_at", "timestamp"))); + json.getStorageDescriptor().setSerdeInfo(new StorageDescriptor.SerDeInfo()); + json.getStorageDescriptor().getSerdeInfo().setSerializationLibrary("org.openx.data.jsonserde.JsonSerDe"); + Table iceberg = table(PARQUET_FORMAT, "s3://bucket/events/", List.of(column("created_at", "timestamp"))); + iceberg.setParameters(Map.of("table_type", "ICEBERG")); + Table partitioned = table(PARQUET_FORMAT, "s3://bucket/events/", List.of(column("id", "string"))); + partitioned.setPartitionKeys(List.of(column("hour", "timestamp"))); + + for (Table table : List.of(json, iceberg, partitioned)) { + assertThat(GlueTableResolver.buildProjection(table), not(containsString("date_trunc"))); + assertThat(GlueTableResolver.readsParquetTimestamps(table), is(false)); + } + } + @Test void isIcebergTableFalseWhenParametersMissing() { assertThat(GlueTableResolver.isIcebergTable(new Table()), is(false));