diff --git a/docs/services/athena.md b/docs/services/athena.md index 4cf44ab22c..5d7d55e19f 100644 --- a/docs/services/athena.md +++ b/docs/services/athena.md @@ -69,7 +69,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 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. 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. +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`. ## Format inference 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 71b8a3bd38..86cdf0384d 100644 --- a/src/main/java/io/floci/aws/services/athena/AthenaService.java +++ b/src/main/java/io/floci/aws/services/athena/AthenaService.java @@ -62,6 +62,8 @@ import java.util.regex.Pattern; 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); public static final String DEFAULT_CATALOG = "AwsDataCatalog"; private static final String DEFAULT_OUTPUT_BUCKET = "floci-athena-results"; private static final String DEFAULT_WORKGROUP = "primary"; @@ -97,6 +99,7 @@ public class AthenaService { private final StorageBackend queryStore; private final StorageBackend workGroupStore; private final StorageBackend dataCatalogStore; + private final StorageBackend> resultColumnTypeStore; private final FlociDuckClient duckClient; private final GlueService glueService; private final S3Service s3Service; @@ -120,6 +123,8 @@ public class AthenaService { new TypeReference<>() {}); this.dataCatalogStore = storageFactory.create("athena", "data-catalogs.json", new TypeReference<>() {}); + this.resultColumnTypeStore = storageFactory.create("athena", "query-result-column-types.json", + new TypeReference<>() {}); this.duckClient = duckClient; this.glueService = glueService; this.s3Service = s3Service; @@ -189,6 +194,9 @@ public class AthenaService { ensureOutputBucket(outputLocation); } duckClient.execute(query, setupDdl, outputLocation); + if (outputLocation != null) { + resultColumnTypeStore.put(id, describeColumnTypes(query, setupDdl)); + } return null; }).onSuccess(v -> { markSucceeded(id, execution); @@ -542,7 +550,8 @@ public class AthenaService { return new ResultSet(List.of(), new ResultSet.ResultSetMetadata(List.of())); } - return readResultsFromS3(execution.getResultConfiguration().getOutputLocation(), id); + List columnTypes = resultColumnTypeStore.get(id).orElse(List.of()); + return readResultsFromS3(execution.getResultConfiguration().getOutputLocation(), id, columnTypes); } // ── private helpers ─────────────────────────────────────────────────────── @@ -1091,7 +1100,60 @@ public class AthenaService { } } - private ResultSet readResultsFromS3(String outputLocation, String queryId) { + /** + * The DuckDB type of each result column, in order. The result CSV carries only the column names, + * so the types come from DuckDB describing the same query. The query has already succeeded, so a + * failure here only costs the types: its columns are reported as varchar. + */ + private List describeColumnTypes(String query, String setupDdl) { + try { + return duckClient.query("DESCRIBE " + query, setupDdl).stream() + .map(column -> String.valueOf(column.get("column_type"))) + .toList(); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not describe the result columns of {0}; reporting them as varchar", query); + return List.of(); + } + } + + private static ResultSet.ColumnInfo columnInfo(String name, String duckType) { + ResultSet.ColumnInfo column = new ResultSet.ColumnInfo(DEFAULT_CATALOG, "", "", name, athenaType(duckType)); + Matcher decimal = DECIMAL_TYPE.matcher(duckType.trim()); + if (decimal.matches()) { + column.setPrecision(Integer.parseInt(decimal.group(1))); + column.setScale(Integer.parseInt(decimal.group(2))); + } + return column; + } + + static String athenaType(String duckType) { + String type = duckType.toUpperCase(Locale.ROOT).trim(); + if (type.endsWith("[]")) { + return "array"; + } + int parameters = type.indexOf('('); + return switch (parameters < 0 ? type : type.substring(0, parameters)) { + case "BIGINT" -> "bigint"; + case "INTEGER" -> "integer"; + case "SMALLINT" -> "smallint"; + case "TINYINT" -> "tinyint"; + case "DOUBLE" -> "double"; + case "FLOAT" -> "float"; + case "DECIMAL" -> "decimal"; + case "BOOLEAN" -> "boolean"; + case "DATE" -> "date"; + case "TIMESTAMP", "TIMESTAMP_S", "TIMESTAMP_MS", "TIMESTAMP_NS" -> "timestamp"; + case "TIMESTAMP WITH TIME ZONE" -> "timestamp with time zone"; + case "TIME" -> "time"; + case "TIME WITH TIME ZONE" -> "time with time zone"; + case "BLOB" -> "varbinary"; + case "STRUCT" -> "row"; + case "MAP" -> "map"; + default -> "varchar"; + }; + } + + private ResultSet readResultsFromS3(String outputLocation, String queryId, List columnTypes) { try { String bucket = extractBucket(outputLocation); String prefix = extractKey(outputLocation); @@ -1109,14 +1171,14 @@ public class AthenaService { return emptyResultSet(); } - return parseCsv(csv.get().getData()); + return parseCsv(csv.get().getData(), columnTypes); } catch (Exception e) { LOG.warnv("Could not read query results for {0}: {1}", queryId, e.getMessage()); return emptyResultSet(); } } - private ResultSet parseCsv(byte[] data) { + private ResultSet parseCsv(byte[] data, List columnTypes) { List rows = new ArrayList<>(); List columns = new ArrayList<>(); @@ -1129,8 +1191,8 @@ public class AthenaService { } String[] headers = CsvParser.parseLine(headerLine).toArray(String[]::new); - for (String h : headers) { - columns.add(new ResultSet.ColumnInfo(DEFAULT_CATALOG, "", "", h, "varchar")); + for (int i = 0; i < headers.length; i++) { + columns.add(columnInfo(headers[i], i < columnTypes.size() ? columnTypes.get(i) : "VARCHAR")); } // Header row is included in GetQueryResults per AWS spec diff --git a/src/test/java/io/floci/aws/services/athena/AthenaColumnTypesSidecarIntegrationTest.java b/src/test/java/io/floci/aws/services/athena/AthenaColumnTypesSidecarIntegrationTest.java new file mode 100644 index 0000000000..a68a7a3bc1 --- /dev/null +++ b/src/test/java/io/floci/aws/services/athena/AthenaColumnTypesSidecarIntegrationTest.java @@ -0,0 +1,44 @@ +package io.floci.aws.services.athena; + +import io.floci.aws.services.floci.duck.FlociDuckClient; +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.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Athena reads its result column types from floci-duck describing the query, so this pins the shape + * of that answer and its mapping to Athena type names against the real sidecar. + */ +@QuarkusTest +@TestProfile(SidecarContainersProfile.class) +class AthenaColumnTypesSidecarIntegrationTest { + + @Inject + FlociDuckClient duck; + + @BeforeAll + static void requireDocker() { + SidecarContainersProfile.requireDocker(); + } + + @Test + void describedResultColumnsMapToAthenaTypeNames() { + List types = duck.query("DESCRIBE SELECT CAST(1 AS BIGINT) AS n, CAST(1.5 AS DOUBLE) AS d, " + + "true AS b, DATE '2026-01-01' AS dt, CAST(2.50 AS DECIMAL(10,2)) AS p, 'x' AS s, " + + "TIME '12:00:00' AS t, CAST(TIMESTAMP '2026-01-01 00:00:00' AS TIMESTAMP_MS) AS ts_ms, " + + "CAST(TIMESTAMP '2026-01-01 00:00:00' AS TIMESTAMPTZ) AS ts_tz", null) + .stream() + .map(column -> AthenaService.athenaType(String.valueOf(column.get("column_type")))) + .toList(); + + assertEquals(List.of("bigint", "double", "boolean", "date", "decimal", "varchar", "time", "timestamp", + "timestamp with time zone"), types); + } +} 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 0053d4d5b8..cfc92d3b3f 100644 --- a/src/test/java/io/floci/aws/services/athena/AthenaServiceTest.java +++ b/src/test/java/io/floci/aws/services/athena/AthenaServiceTest.java @@ -5,24 +5,30 @@ import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.athena.model.QueryExecutionState; +import io.floci.aws.services.athena.model.ResultConfiguration; +import io.floci.aws.services.athena.model.ResultSet; import io.floci.aws.services.floci.duck.FlociDuckClient; import io.floci.aws.services.glue.GlueService; import io.floci.aws.services.s3.S3Service; +import io.floci.aws.services.s3.model.S3Object; import io.vertx.core.Vertx; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.nio.charset.StandardCharsets; import java.util.List; +import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -35,6 +41,7 @@ class AthenaServiceTest { private Vertx vertx; private FlociDuckClient duckClient; + private S3Service s3Service; private AthenaService service; @BeforeEach @@ -43,12 +50,12 @@ class AthenaServiceTest { duckClient = mock(FlociDuckClient.class); StorageFactory storageFactory = mock(StorageFactory.class); - doReturn(AccountAwareStorageBackend.inMemory("000000000000")) + doAnswer(invocation -> AccountAwareStorageBackend.inMemory("000000000000")) .when(storageFactory).create(anyString(), anyString(), any()); GlueService glueService = mock(GlueService.class); when(glueService.getTables(anyString())).thenReturn(List.of()); - S3Service s3Service = mock(S3Service.class); + s3Service = mock(S3Service.class); GlueViewDdlBuilder ddlBuilder = mock(GlueViewDdlBuilder.class); EmulatorConfig config = mock(EmulatorConfig.class); @@ -139,6 +146,74 @@ class AthenaServiceTest { "a late stop must not cancel a failed query"); } + @Test + void getQueryResultsReportsTheSqlTypeOfEachColumn() throws Exception { + String query = "SELECT CAST(1 AS BIGINT) AS n, CAST(1.5 AS DOUBLE) AS d, true AS b, " + + "DATE '2026-01-01' AS dt, CAST(2.50 AS DECIMAL(10,2)) AS p, 'x' AS s"; + when(duckClient.query(eq("DESCRIBE " + query), any())).thenReturn(List.of( + Map.of("column_name", "n", "column_type", "BIGINT"), + Map.of("column_name", "d", "column_type", "DOUBLE"), + Map.of("column_name", "b", "column_type", "BOOLEAN"), + Map.of("column_name", "dt", "column_type", "DATE"), + Map.of("column_name", "p", "column_type", "DECIMAL(10,2)"), + Map.of("column_name", "s", "column_type", "VARCHAR"))); + + assertEquals(List.of("bigint", "double", "boolean", "date", "decimal", "varchar"), + columnInfo(query, "n,d,b,dt,p,s\n1,1.5,true,2026-01-01,2.50,x\n").stream() + .map(ResultSet.ColumnInfo::getType).toList()); + } + + @Test + void getQueryResultsReportsThePrecisionAndScaleOfADecimalColumn() throws Exception { + String query = "SELECT CAST(2.50 AS DECIMAL(10,2)) AS p"; + when(duckClient.query(eq("DESCRIBE " + query), any())).thenReturn(List.of( + Map.of("column_name", "p", "column_type", "DECIMAL(10,2)"))); + + ResultSet.ColumnInfo column = columnInfo(query, "p\n2.50\n").get(0); + + assertEquals("decimal", column.getType()); + assertEquals(10, column.getPrecision()); + assertEquals(2, column.getScale()); + } + + @Test + void getQueryResultsReportsTimeAndTimestampVariantsByTheirAthenaNames() throws Exception { + String query = "SELECT t, ts_s, ts_ms, ts_ns, ts_tz, t_tz FROM times"; + when(duckClient.query(eq("DESCRIBE " + query), any())).thenReturn(List.of( + Map.of("column_name", "t", "column_type", "TIME"), + Map.of("column_name", "ts_s", "column_type", "TIMESTAMP_S"), + Map.of("column_name", "ts_ms", "column_type", "TIMESTAMP_MS"), + Map.of("column_name", "ts_ns", "column_type", "TIMESTAMP_NS"), + Map.of("column_name", "ts_tz", "column_type", "TIMESTAMP WITH TIME ZONE"), + Map.of("column_name", "t_tz", "column_type", "TIME WITH TIME ZONE"))); + + assertEquals(List.of("time", "timestamp", "timestamp", "timestamp", "timestamp with time zone", + "time with time zone"), + columnInfo(query, "t,ts_s,ts_ms,ts_ns,ts_tz,t_tz\n,,,,,\n").stream() + .map(ResultSet.ColumnInfo::getType).toList()); + } + + @Test + void getQueryResultsReportsVarcharWhenTheTypesCannotBeDescribed() throws Exception { + when(duckClient.query(anyString(), any())).thenThrow(new IllegalStateException("not describable")); + + assertEquals(List.of("varchar", "varchar"), columnInfo("SELECT 1 AS a, 2 AS b", "a,b\n1,2\n").stream() + .map(ResultSet.ColumnInfo::getType).toList()); + } + + private List columnInfo(String query, String csv) throws Exception { + String id = service.startQueryExecution(query, "primary", null, + new ResultConfiguration("s3://athena-results/")); + awaitState(id, QueryExecutionState.SUCCEEDED); + String outputLocation = service.getQueryExecution(id).getResultConfiguration().getOutputLocation(); + String key = outputLocation.substring("s3://athena-results/".length()); + S3Object result = new S3Object("athena-results", key, csv.getBytes(StandardCharsets.UTF_8), "text/csv"); + 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(); + } + private void awaitState(String id, QueryExecutionState expected) throws InterruptedException { long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); while (System.nanoTime() < deadline) {