fix(athena): read a column declared timestamp as Athena's timestamp(3) (#8648)

This commit is contained in:
Ghassan Gedeon Achi authored and GitHub committed 2026-11-16 16:33:22 -04:00
1 parent 30f8a9985e
commit 11864f6e81
11 files changed
+766 -188

No files matched your search

@@ -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<String> 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<String> athenaTypes) {
List<ResultSet.Datum> 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.
*
* <p>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.
*
* <p>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;
@@ -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<String, String> partitionReads = new HashMap<>();
StringBuilder sb = new StringBuilder();
boolean usesIceberg = false;
Set<SessionSetup> setup = EnumSet.noneOf(SessionSetup.class);
boolean contextDbHandled = false;
List<Database> 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<Table> 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<Table> 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<Table> tables, boolean qualified,
ViewFilter wanted, Map<String, String> 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<SessionSetup> setup, String schemaOrNull, List<Table> tables,
boolean qualified, ViewFilter wanted, Map<String, String> 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;
}
/**
@@ -255,6 +255,9 @@ public final class GlueTableResolver {
* <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.
*
* <p>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<Column> declared = declaredColumns(table);
@@ -279,6 +282,7 @@ public final class GlueTableResolver {
Map<String, Column> templatedKeys = templatedKeys(table, template);
Map<String, Column> textColumns = readsDelimitedText(table) ? columnsByName(declared) : Map.of();
Map<String, Column> hiveKeys = hivePartitionKeys(table, template);
Map<String, Column> 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<String> keyNames = new HashSet<>();
keys.forEach(key -> keyNames.add(key.getName().toLowerCase(Locale.ROOT)));
Map<String, Column> textColumns = readsDelimitedText(table) ? columnsByName(declaredColumns(table)) : Map.of();
Map<String, Column> parquetTimestamps = parquetTimestamps(table);
List<String> 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<String> rows = new ArrayList<>();
List<String> 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.
*
* <p>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.
*
* <p>A name is resolved to its first declaration, as {@link #buildProjection} projects it.
*
* <p>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<String, Column> parquetTimestamps(Table table) {
if (table == null || table.getStorageDescriptor() == null || isIcebergTable(table)
|| !"read_parquet".equals(inferReadFunction(table)) || table.getStorageDescriptor().getColumns() == null) {
return Map.of();
}
Map<String, Column> 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.
*
* <p>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.
*
* <p>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.
*
* <p>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}.
*
* <p>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.