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

@@ -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<String> keys = new ArrayList<>();
private final List<Table> tables = new ArrayList<>();
private final Map<String, List<Partition>> 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<Map<String, String>> rows = query("SELECT id, name, dt, typeof(id) AS id_type FROM " + view("events")
List<Map<String, String>> 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<Map<String, String>> rows = query("SELECT id, name, name IS NULL AS name_null, note FROM "
+ view("evolved") + " ORDER BY id");
List<Map<String, String>> 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<string>"),
column("who", "struct<name:string,age:int>")));
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<Map<String, String>> query(String sql) {
String views = builder().build(null, sql);
List<Map<String, String>> rows = new ArrayList<>();
for (Map<String, Object> row : duck.query(sql, views)) {
Map<String, String> values = new LinkedHashMap<>();
row.forEach((column, value) -> values.put(column, String.valueOf(value)));
rows.add(values);
}
return rows;
}
private String view(String table) {
return "\"" + schema + "\".\"" + table + "\"";
}
private static Column column(String name, String type) {
Column column = new Column();
column.setName(name);
column.setType(type);
return column;
}
}
@@ -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;
* <p>Each table reads the same one-row Parquet file, which, like any partitioned dataset, holds no
* partition columns: {@code region} and {@code dt} exist only in the object paths. Athena derives
* them from the path through the template, so every table here returns {@code r1, eu, 2026-03-14};
* the default {@code column=value} layout is the control.
*
* <p>The views come from {@link GlueViewDdlBuilder} over these tables alone rather than from Athena
* end to end: the sidecar application is shared with other test classes, and Athena builds views
* for every Glue table it holds, so another class's tables would be in every query.
* 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<String> keys = new ArrayList<>();
private final List<Table> 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<Map<String, String>> rows = query("SELECT region, CAST(dt AS VARCHAR) AS dt "
+ "FROM " + view("sales_bare") + " ORDER BY region");
List<Map<String, String>> 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<Column> 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<String, String> parameters, List<Column> 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<Map<String, String>> 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<Map<String, String>> query(String sql) {
GlueService glue = Mockito.mock(GlueService.class);
Database database = new Database();
database.setName(schema);
when(glue.getDatabases()).thenReturn(List.of(database));
when(glue.getTables(schema)).thenReturn(tables);
String views = new GlueViewDdlBuilder(glue, s3Service).build(null);
List<Map<String, String>> rows = new ArrayList<>();
for (Map<String, Object> row : duck.query(sql, views)) {
Map<String, String> values = new LinkedHashMap<>();
row.forEach((column, value) -> values.put(column, String.valueOf(value)));
rows.add(values);
}
return rows;
}
private String view(String table) {
return "\"" + schema + "\".\"" + table + "\"";
}
private static Column column(String name, String type) {
Column column = new Column();
column.setName(name);
column.setType(type);
return column;
}
}
@@ -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<ResultSet.ColumnInfo> 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 {
@@ -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.
*
* <p>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<String> keys = new ArrayList<>();
private final List<Table> tables = new ArrayList<>();
private final Map<String, List<Partition>> 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<Map<String, String>> query(String sql) {
List<Map<String, String>> rows = new ArrayList<>();
for (Map<String, Object> row : duck.query(sql, builder().build(null, sql))) {
Map<String, String> 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;
}
}
@@ -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.
*
* <p>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<Map<String, String>> 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<Map<String, Object>> 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<Column> 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<Column> partitionKeys) {
Table table = new Table();
table.setName(name);
table.setStorageDescriptor(descriptor);
table.setPartitionKeys(partitionKeys);
return table;
}
private static Map<String, String> row(String id, String ts, String tsNs) {
return Map.of("id", id, "ts", ts, "ts_ns", tsNs, "ts_type", "TIMESTAMP", "ts_ns_type", "TIMESTAMP");
}
}
@@ -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<Table, String> 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
@@ -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));