From 87a93ebe9257d84ef80ed19700ce22416f969fd2 Mon Sep 17 00:00:00 2001 From: Ghassan Gedeon Achi Date: Tue, 17 Nov 2026 17:16:51 -0600 Subject: [PATCH] fix(athena): bind a query's ExecutionParameters (#8763) StartQueryExecution ignored ExecutionParameters, so a parameterized query failed with "Expected N parameters, but none were supplied". Each value is now bound to its ? placeholder as Athena reads it, as the SQL text of one expression: in parentheses, or bare when it is a lone literal. A value that isn't one expression, such as a lone name, an open quote or brackets that don't pair, is bound as a string, so it cannot add a statement, and the bound statement goes through the one-statement check again. The partition-projection checks, the Glue view and S3 Tables setup and the translation to DuckDB all read the bound statement, and a parameter count that doesn't match fails the query with Athena's INVALID_PARAMETER_USAGE message. Closes #8679 --- docs/services/athena.md | 5 +- .../services/athena/AthenaJsonHandler.java | 18 +- .../aws/services/athena/AthenaService.java | 42 +++- .../athena/TrinoSqlCompatibility.java | 187 +++++++++++++++++- ...utionParametersSidecarIntegrationTest.java | 85 ++++++++ .../AthenaIcebergSidecarIntegrationTest.java | 18 +- .../athena/AthenaJsonHandlerTest.java | 57 ++++++ .../services/athena/AthenaServiceTest.java | 92 ++++++++- .../athena/TrinoSqlCompatibilityTest.java | 102 ++++++++++ 9 files changed, 579 insertions(+), 27 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/athena/AthenaExecutionParametersSidecarIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/athena/AthenaJsonHandlerTest.java diff --git a/docs/services/athena.md b/docs/services/athena.md index 5e5c6daae5..983676e070 100644 --- a/docs/services/athena.md +++ b/docs/services/athena.md @@ -113,15 +113,16 @@ 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. How the query string is read is described in [Query strings](#query-strings). +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. How the query string and its `ExecutionParameters` are read is described in [Query strings and parameters](#query-strings-and-parameters). 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. -## Query strings +## Query strings and parameters `StartQueryExecution` reads a query string as Athena engine version 3 does: - The whitespace and semicolons around the statement are dropped: `GetQueryExecution` returns `SELECT 1 ;` and `;SELECT 1` as `SELECT 1`. A comment at either end stays. - A query holding more than one statement, meaning anything (a comment included) on both sides of a semicolon, is rejected with an `InvalidRequestException` whose `AthenaErrorCode` is `MALFORMED_QUERY`. A semicolon inside a literal, a quoted identifier (backtick-quoted included) or a comment separates nothing; as on Athena, Hive's backslash escapes are not read here. Where Trino and DuckDB end a nested block comment at different places, a second statement under either reading counts. +- When the query runs on DuckDB (so not in mock mode, nor for Hive DDL, `CREATE DATABASE` or `VACUUM`), its `ExecutionParameters` are bound to its `?` placeholders in order. Each value is the SQL text of an expression: a string is passed quoted (`'eu'`), a number bare (`10`), and `SELECT ? * 2` with `1 + 1` gives `4`. A value that is not one expression, because it holds a semicolon, a comma outside parentheses or brackets, or ones that don't balance or pair up (`(1]`), or leaves a quote open, is bound as a string of its text with whitespace and comments dropped, as Athena binds it; so is a lone name (`x`, `"x"`), even where a column has it, while `TRUE`, `NULL`, `CURRENT_DATE` and the like stay expressions. A `?` inside a literal, a quoted identifier or a comment is not a placeholder. A query without placeholders runs whatever parameters it is given; otherwise a count that does not match, no parameters at all included, fails the query with `INVALID_PARAMETER_USAGE: line 1:1: Incorrect number of parameters: expected 2 but found 1`. `GetQueryExecution` does not return the parameters, and named prepared statements (`PREPARE` / `EXECUTE ... USING`) are not supported. ## Trino SQL on DuckDB diff --git a/src/main/java/io/floci/aws/services/athena/AthenaJsonHandler.java b/src/main/java/io/floci/aws/services/athena/AthenaJsonHandler.java index 666aafd4cf..d6aac52c09 100644 --- a/src/main/java/io/floci/aws/services/athena/AthenaJsonHandler.java +++ b/src/main/java/io/floci/aws/services/athena/AthenaJsonHandler.java @@ -94,7 +94,8 @@ public class AthenaJsonHandler { resultConfiguration = mapper.treeToValue(request.get("ResultConfiguration"), ResultConfiguration.class); } - String id = athenaService.startQueryExecution(query, workGroup, context, resultConfiguration); + String id = athenaService.startQueryExecution(query, workGroup, context, resultConfiguration, + strings(request, "ExecutionParameters")); yield Response.ok(Map.of("QueryExecutionId", id)).build(); } case "GetQueryExecution" -> { @@ -194,7 +195,7 @@ public class AthenaJsonHandler { yield Response.ok(Map.of()).build(); } case "UntagResource" -> { - athenaService.untagResource(text(request, "ResourceARN"), tagKeys(request)); + athenaService.untagResource(text(request, "ResourceARN"), strings(request, "TagKeys")); yield Response.ok(Map.of()).build(); } case "ListDatabases" -> { @@ -260,15 +261,16 @@ public class AthenaJsonHandler { return tags; } - private static List tagKeys(JsonNode request) { - JsonNode node = request.get("TagKeys"); + /** The strings of the list member {@code field}, such as {@code TagKeys}; none when it is absent. */ + private static List strings(JsonNode request, String field) { + JsonNode node = request.get(field); if (node == null || !node.isArray()) { return List.of(); } - List keys = new ArrayList<>(); - for (JsonNode key : node) { - keys.add(key.asText()); + List strings = new ArrayList<>(); + for (JsonNode string : node) { + strings.add(string.asText()); } - return keys; + return strings; } } 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 a011d4906f..d3d9120df3 100644 --- a/src/main/java/io/floci/aws/services/athena/AthenaService.java +++ b/src/main/java/io/floci/aws/services/athena/AthenaService.java @@ -158,6 +158,19 @@ public class AthenaService { String workGroup, QueryExecutionContext context, ResultConfiguration resultConfiguration) { + return startQueryExecution(submitted, workGroup, context, resultConfiguration, List.of()); + } + + /** + * Starts a query, binding {@code executionParameters} to its {@code ?} placeholders when it runs on the + * engine. They are not kept on the execution: AWS documents that "the list of parameters is not returned + * in the response". + */ + public String startQueryExecution(String submitted, + String workGroup, + QueryExecutionContext context, + ResultConfiguration resultConfiguration, + List executionParameters) { // Athena takes one statement per query and rejects any other before an execution exists, with the // AthenaErrorCode its InvalidRequestException carries for malformed SQL. The engine would otherwise run // every statement of one that returns no rows, so a query that failed could still have written a table. @@ -168,6 +181,8 @@ public class AthenaService { // Athena records, returns and runs the statement without the semicolons around it, so everything below, // the execution's record included, reads that form. String query = TrinoSqlCompatibility.recordedForm(submitted); + // Read when the query runs, on another thread, so a caller changing its list later changes nothing. + List parameters = executionParameters == null ? List.of() : List.copyOf(executionParameters); String id = UUID.randomUUID().toString(); String database = context != null && context.getDatabase() != null ? context.getDatabase() : "default"; QueryExecutionContext resolvedContext = context != null ? context : new QueryExecutionContext(); @@ -273,22 +288,35 @@ public class AthenaService { icebergStatements.vacuum(vacuum.ref(), database); return null; } + // The parameters are bound into the statement, so the Iceberg rewrite and the engine both read + // literals. A count that doesn't match fails the query here, before the checks below, as Trino + // checks parameters before it analyzes a statement. Hive DDL never gets this far, and binds none. + // Everything after this reads the bound statement, as if the values had been written in place: a + // value bound as an expression can name a column, which must not pass the projection checks as + // the `?` would, or a table, whose view the engine needs. + String statement = TrinoSqlCompatibility.bindParameters(query, parameters); + // A value bound as Athena binds it cannot add a statement (see bindParameters). The engine runs + // every statement of a write, so the bound statement is checked again rather than trusted. + if (TrinoSqlCompatibility.holdsSeveralStatements(statement)) { + throw new AwsException("InvalidRequestException", + "Only one sql statement is allowed. Got: " + statement, 400); + } List
projectionTables = tablesForProjectionCheck(database); - PartitionProjection.assertLocationTemplatesComplete(query, projectionTables); - PartitionProjection.assertInjectedColumnsFiltered(query, projectionTables); + PartitionProjection.assertLocationTemplatesComplete(statement, projectionTables); + PartitionProjection.assertInjectedColumnsFiltered(statement, projectionTables); // S3 Tables catalogs the query names are attached under their own names; a write to an Iceberg // table of the default catalog goes through the engine's attachment of Glue's Iceberg catalog. - AthenaIcebergStatements.S3TablesAttachment s3Tables = icebergStatements.s3TablesAttachment(query, - resolvedContext.getCatalog(), database); + AthenaIcebergStatements.S3TablesAttachment s3Tables = icebergStatements.s3TablesAttachment( + statement, resolvedContext.getCatalog(), database); AthenaIcebergStatements.IcebergWrite icebergWrite = null; try { - icebergWrite = icebergStatements.write(query, resolvedContext.getCatalog(), database); + icebergWrite = icebergStatements.write(statement, resolvedContext.getCatalog(), database); String setupDdl = (s3Tables != null ? s3Tables.attachSql() : "") + (icebergWrite != null ? icebergWrite.setupSql() : "") - + TrinoSqlCompatibility.FUNCTION_MACROS + ddlBuilder.build(database, query) + + TrinoSqlCompatibility.FUNCTION_MACROS + ddlBuilder.build(database, statement) + (s3Tables != null ? s3Tables.searchPathSql() : ""); String duckQuery = TrinoSqlCompatibility.translate( - icebergWrite != null ? icebergWrite.query() : query); + icebergWrite != null ? icebergWrite.query() : statement); if (outputLocation != null) { ensureOutputBucket(outputLocation); } diff --git a/src/main/java/io/floci/aws/services/athena/TrinoSqlCompatibility.java b/src/main/java/io/floci/aws/services/athena/TrinoSqlCompatibility.java index 59616ba756..788c231000 100644 --- a/src/main/java/io/floci/aws/services/athena/TrinoSqlCompatibility.java +++ b/src/main/java/io/floci/aws/services/athena/TrinoSqlCompatibility.java @@ -1,5 +1,7 @@ package io.floci.aws.services.athena; +import io.floci.aws.core.common.AwsException; + import java.util.ArrayList; import java.util.List; import java.util.Locale; @@ -33,7 +35,8 @@ import java.util.regex.Pattern; * * *

It also reads a query string's statement, by the same lexical rules, for - * {@code StartQueryExecution}: where it ends ({@link #holdsSeveralStatements} and {@link #recordedForm}). + * {@code StartQueryExecution}: where it ends ({@link #holdsSeveralStatements} and {@link #recordedForm}) + * and its {@code ?} placeholders ({@link #bindParameters}). */ final class TrinoSqlCompatibility { @@ -62,6 +65,10 @@ final class TrinoSqlCompatibility { private static final Pattern MULTI_WORD_TYPE = Pattern.compile( "DOUBLE\\s+PRECISION|(TIMESTAMP|TIME)(\\s*\\(\\s*\\d+\\s*\\))?\\s+WITH(OUT)?\\s+TIME\\s+ZONE", Pattern.CASE_INSENSITIVE); + /** Trino's reserved words that are an expression on their own, so a parameter value, not a name. */ + private static final Set EXPRESSION_KEYWORDS = Set.of("TRUE", "FALSE", "NULL", "CURRENT_DATE", + "CURRENT_TIME", "CURRENT_TIMESTAMP", "LOCALTIME", "LOCALTIMESTAMP", "CURRENT_USER", "CURRENT_CATALOG", + "CURRENT_SCHEMA", "CURRENT_PATH"); private TrinoSqlCompatibility() { } @@ -136,19 +143,184 @@ final class TrinoSqlCompatibility { return bounds.start() >= 0 ? sql.substring(bounds.start(), bounds.end()) : sql; } + /** + * {@code statement}, in its {@link #recordedForm}, with its {@code ?} placeholders bound to a query's + * {@code ExecutionParameters}, as Athena (engine v3) binds them. + * + *

Athena reads the values as the SQL text of an {@code EXECUTE ... USING} list: joined with commas, + * then read as expressions, one per placeholder in order. So a string arrives quoted ({@code 'eu'}) and + * a number bare ({@code 10}); {@code 1 + 1} is one expression, so {@code SELECT ? * 2} gives 4; and a + * line comment in a value runs on over the values after it, so {@code 1 -- x} and {@code 2} count as + * one. A value that is not one expression is read as a string instead (see {@link #usingListEntry}). + * Each expression replaces its placeholder in parentheses, with its comments blanked, so it keeps its + * precedence inside the statement; a lone literal goes in bare, so the statement reads as if it had been + * written there, a JSON path for {@link #translate} included. + * + *

A statement without placeholders runs as written, whatever parameters it is given, as on Athena. + * Otherwise the counts must match. If they don't, with no parameters at all included, Athena fails the + * query with Trino's error at where the statement starts: + * + *

INVALID_PARAMETER_USAGE: line 1:1: Incorrect number of parameters: expected 2 but found 1
+ * + * A {@code ?} in a literal, a quoted identifier or a comment is not a placeholder. + * + *

TODO: named prepared statements ({@code PREPARE} / {@code EXECUTE ... USING}) bind the same way + * but are not supported. + * + * @throws AwsException when the counts differ, which fails the query + */ + static String bindParameters(String statement, List parameters) { + if (statement == null) { + return null; + } + List placeholders = new ArrayList<>(); + int i = 0; + while (i < statement.length()) { + int skipped = skipLiteralOrComment(statement, i); + if (skipped > i) { + i = skipped; + continue; + } + if (statement.charAt(i) == '?') { + placeholders.add(i); + } + i++; + } + if (placeholders.isEmpty()) { + return statement; + } + List values = parameters == null || parameters.isEmpty() + ? List.of() + : splitTopLevel(String.join(", ", parameters.stream().map(TrinoSqlCompatibility::usingListEntry) + .toList()), true); + if (values.size() != placeholders.size()) { + throw new AwsException("InvalidRequestException", "INVALID_PARAMETER_USAGE: " + statementPosition(statement) + + ": Incorrect number of parameters: expected " + placeholders.size() + " but found " + values.size(), + 400); + } + StringBuilder bound = new StringBuilder(statement.length()); + int last = 0; + for (int k = 0; k < placeholders.size(); k++) { + int at = placeholders.get(k); + String expression = withoutComments(values.get(k)).strip(); + boolean literal = !expression.isEmpty() && (skipLiteralOrComment(expression, 0) == expression.length() + || expression.chars().allMatch(c -> Character.isDigit(c) || c == '.')); + // Spaced where it would run into the text around it: 1 bound in SELECT ?e2 is not 1e2. + String before = at > 0 && runsInto(statement.charAt(at - 1)) ? " " : ""; + String after = at + 1 < statement.length() && runsInto(statement.charAt(at + 1)) ? " " : ""; + bound.append(statement, last, at).append(before).append(literal ? expression : "(" + expression + ")") + .append(after); + last = at + 1; + } + return bound.append(statement, last, statement.length()).toString(); + } + + /** Whether a bound value next to {@code c} would join the token {@code c} belongs to. */ + private static boolean runsInto(char c) { + return isIdentifierChar(c) || c == '.' || c == '\'' || c == '"' || c == '`'; + } + + /** + * {@code value} as Athena (engine v3) puts it in the {@code USING} list: as written when it is one + * expression, and otherwise as a string of its tokens, whitespace and comments dropped. Athena returns + * {@code 1); SELECT (2} as the string {@code 1);SELECT(2}, {@code 1; SELECT 2} as {@code 1;SELECT2} and + * {@code 1, 2} as the one parameter {@code 1,2}, so a value can neither end the statement nor add a + * parameter. A value is taken for more than one expression when, outside its literals and comments, it + * holds a semicolon or a comma outside brackets, its brackets don't balance or pair up ({@code (1]}, + * {@code ([)]}), or it leaves a quote open: + * Athena returns {@code 'a} as the string {@code 'a}, and bound as written it would turn the literals after + * the placeholder inside out. + * + *

A lone name is not a value either: Athena returns {@code x} as the string {@code x} and {@code "x"} as + * {@code "x"}, even where a column has that name. The words that are expressions on their own, such as + * {@code TRUE}, {@code NULL} and {@code CURRENT_DATE} ({@link #EXPRESSION_KEYWORDS}), stay expressions, as + * on Athena. + * + *

TODO: Athena reads any value naming a column as a string ({@code x + 1} as {@code x+1}); only a lone + * name is here, and a longer expression naming one is bound as written. Nor is a value whose tokens make no + * expression ({@code 1 +}, {@code 1 2}) told apart, which takes a Trino expression parser: it is bound as + * written, and the query fails on DuckDB. + */ + private static String usingListEntry(String value) { + StringBuilder tokens = new StringBuilder(value.length()); + // The brackets still open, innermost last, so a close must match the latest open of its kind. + StringBuilder open = new StringBuilder(); + boolean expression = true; + int i = 0; + while (i < value.length()) { + char c = value.charAt(i); + int skipped = skipLiteralOrComment(value, i); + if (skipped > i) { + if (c == '\'' || c == '"' || c == '`') { + expression &= closedQuote(value, i); + tokens.append(value, i, skipped); + } + i = skipped; + continue; + } + if (c == '(' || c == '[') { + open.append(c); + } else if (c == ')' || c == ']') { + boolean pairs = !open.isEmpty() && open.charAt(open.length() - 1) == (c == ')' ? '(' : '['); + expression &= pairs; + if (pairs) { + open.setLength(open.length() - 1); + } + } else if (c == ';' || c == ',' && open.isEmpty()) { + expression = false; + } + if (!Character.isWhitespace(c)) { + tokens.append(c); + } + i++; + } + String text = tokens.toString(); + boolean bareName = !text.isEmpty() && !Character.isDigit(text.charAt(0)) + && text.chars().allMatch(ch -> isIdentifierChar((char) ch)) + && !EXPRESSION_KEYWORDS.contains(text.toUpperCase(Locale.ROOT)); + boolean quotedName = !text.isEmpty() && (text.charAt(0) == '"' || text.charAt(0) == '`') + && skipQuoted(text, 0) == text.length(); + return expression && open.isEmpty() && !bareName && !quotedName ? value : "'" + text.replace("'", "''") + "'"; + } + + /** Whether the literal or quoted name starting at {@code i} is closed; {@link #skipQuoted} runs off an open one. */ + private static boolean closedQuote(String sql, int i) { + // A character after the text tells a quote closed at the very end from one left open. + return skipQuoted(sql + " ", i) <= sql.length(); + } + + /** + * Where {@code statement} starts, as Trino locates an error on it: {@code line L:C}, both counted from 1, + * at its first token that is not a comment. {@code -- lead\nSELECT ?} is at {@code line 2:1}. + */ + private static String statementPosition(String statement) { + int at = Math.max(bounds(statement, false).codeStart(), 0); + int line = 1; + int lineStart = 0; + for (int i = 0; i < at; i++) { + if (statement.charAt(i) == '\n') { + line++; + lineStart = i + 1; + } + } + return "line " + line + ":" + (at - lineStart + 1); + } + /** * Where the statement of a query string lies. {@code start} is its first character that is neither * whitespace nor a semicolon, -1 when there is none, and {@code end} is just past its last such token: a - * trailing comment included, the line break that ends a line comment not. {@code several} is whether such - * a token follows a semicolon that follows one. With {@code nestedComments}, block comments are read as - * DuckDB reads them (see {@link #skipLiteralOrComment(String, int, boolean)}). + * trailing comment included, the line break that ends a line comment not. {@code codeStart} is its first + * token that is not a comment either, -1 when it is all comments. {@code several} is whether such a token + * follows a semicolon that follows one. With {@code nestedComments}, block comments are read as DuckDB + * reads them (see {@link #skipLiteralOrComment(String, int, boolean)}). */ - private record StatementBounds(int start, int end, boolean several) { + private record StatementBounds(int start, int end, int codeStart, boolean several) { } private static StatementBounds bounds(String sql, boolean nestedComments) { int start = -1; int end = 0; + int codeStart = -1; boolean semicolonAfterStatement = false; boolean several = false; int i = 0; @@ -170,6 +342,9 @@ final class TrinoSqlCompatibility { if (next == i) { next = i + 1; } + if (!comment && codeStart < 0) { + codeStart = i; + } // A line comment runs to its line break, which is whitespace after the statement, not part of it. end = next; while (comment && end > i && Character.isWhitespace(sql.charAt(end - 1))) { @@ -177,7 +352,7 @@ final class TrinoSqlCompatibility { } i = next; } - return new StatementBounds(start, end, several); + return new StatementBounds(start, end, codeStart, several); } private static String translateCast(String inner) { diff --git a/src/test/java/io/floci/aws/services/athena/AthenaExecutionParametersSidecarIntegrationTest.java b/src/test/java/io/floci/aws/services/athena/AthenaExecutionParametersSidecarIntegrationTest.java new file mode 100644 index 0000000000..fd00452f1e --- /dev/null +++ b/src/test/java/io/floci/aws/services/athena/AthenaExecutionParametersSidecarIntegrationTest.java @@ -0,0 +1,85 @@ +package io.floci.aws.services.athena; + +import io.floci.aws.services.floci.duck.FlociDuckClient; +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.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * A query's {@code ExecutionParameters}, bound as Athena binds them, run on the real floci-duck sidecar as the + * expressions Athena reads them as. + */ +@QuarkusTest +@TestProfile(SidecarContainersProfile.class) +class AthenaExecutionParametersSidecarIntegrationTest { + + @Inject + FlociDuckClient duck; + + @Inject + S3Service s3Service; + + @BeforeAll + static void requireDocker() { + SidecarContainersProfile.requireDocker(); + } + + /** + * An event search binds a date range, a tenant, a time range and a keyset to resume after, each value the text of + * a Trino expression: quoted strings and {@code timestamp '...'} literals. + */ + @Test + void anEventSearchRunsWithItsDatesTenantTimesAndKeysetBound() { + String search = "SELECT uid FROM (VALUES " + + "(DATE '2026-11-10', 't1', TIMESTAMP '2026-11-10 09:00:00', 'a'), " + + "(DATE '2026-11-10', 't1', TIMESTAMP '2026-11-10 10:00:00', 'b'), " + + "(DATE '2026-11-10', 't1', TIMESTAMP '2026-11-10 10:00:00', 'c'), " + + "(DATE '2026-11-10', 't2', TIMESTAMP '2026-11-10 11:00:00', 'd'), " + + "(DATE '2026-11-11', 't1', TIMESTAMP '2026-11-11 08:00:00', 'e')" + + ") AS events (event_date, tenant_id, event_time, uid)" + + " WHERE event_date BETWEEN date(?) AND date(?) AND tenant_id = ?" + + " AND event_time BETWEEN ? and ? AND (event_time, uid) > (?,?)" + + " ORDER BY event_time ASC, uid ASC LIMIT 10"; + List parameters = List.of("'2026-11-10'", "'2026-11-10'", "'t1'", + "timestamp '2026-11-10 00:00:00'", "timestamp '2026-11-10 23:59:59.999'", + "timestamp '2026-11-10 10:00:00'", "'b'"); + + try (AthenaSidecarFixture fixture = new AthenaSidecarFixture(duck, s3Service, "parameters")) { + List> rows = fixture.query(TrinoSqlCompatibility.bindParameters(search, parameters)); + + assertEquals(List.of(Map.of("uid", "c")), rows); + } + } + + /** Athena (engine v3) returns 2 and 3 for this, and 1 for the JSON path given as a parameter. */ + @Test + void rowCountsAndAJsonPathRunAsBound() { + try (AthenaSidecarFixture fixture = new AthenaSidecarFixture(duck, s3Service, "parameters")) { + assertEquals(List.of(Map.of("x", "2"), Map.of("x", "3")), fixture.query(TrinoSqlCompatibility.bindParameters( + "SELECT x FROM UNNEST(ARRAY[1, 2, 3, 4]) AS t (x) ORDER BY x OFFSET ? LIMIT ?", List.of("1", "2")))); + } + String jsonPath = TrinoSqlCompatibility.translate(TrinoSqlCompatibility.bindParameters( + "SELECT json_extract_scalar('{\"a b\":1}', ?) AS v", List.of("'$[\"a b\"]'"))); + assertEquals("1", String.valueOf(duck.query(jsonPath, TrinoSqlCompatibility.FUNCTION_MACROS).getFirst().get("v"))); + } + + /** A value is an expression of its own, so it keeps its precedence inside the statement. */ + @Test + void aValueKeepsItsPrecedenceInsideTheStatement() { + try (AthenaSidecarFixture fixture = new AthenaSidecarFixture(duck, s3Service, "parameters")) { + List> rows = fixture.query( + TrinoSqlCompatibility.bindParameters("SELECT ? * 2 AS a", List.of("1 + 1"))); + + assertEquals(List.of(Map.of("a", "4")), rows); + } + } +} diff --git a/src/test/java/io/floci/aws/services/athena/AthenaIcebergSidecarIntegrationTest.java b/src/test/java/io/floci/aws/services/athena/AthenaIcebergSidecarIntegrationTest.java index 47f881134c..4f431ee82c 100644 --- a/src/test/java/io/floci/aws/services/athena/AthenaIcebergSidecarIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/athena/AthenaIcebergSidecarIntegrationTest.java @@ -164,6 +164,18 @@ class AthenaIcebergSidecarIntegrationTest { assertEquals(List.of(row("id", "1")), rows("SELECT id FROM events ORDER BY id")); } + @Test + void anIcebergInsertWritesItsBoundParameters() { + run("CREATE TABLE events (id bigint, name string) LOCATION 's3://" + bucket + "/lake/events/' " + + "TBLPROPERTIES ('table_type'='ICEBERG')"); + + QueryExecution insert = execute(null, database, "INSERT INTO events VALUES (?, ?)", List.of("5", "'e'")); + + assertEquals(QueryExecutionState.SUCCEEDED, insert.getStatus().getState(), + insert.getStatus().getStateChangeReason()); + assertEquals(List.of(row("id", "5", "name", "e")), rows("SELECT id, name FROM events ORDER BY id")); + } + /** Runs a write and checks its commit landed on the Glue table, moving its {@code metadata_location}. */ private void committed(String sql) { String before = metadataLocation("events"); @@ -274,11 +286,15 @@ class AthenaIcebergSidecarIntegrationTest { } private QueryExecution execute(String catalogName, String contextDatabase, String sql) { + return execute(catalogName, contextDatabase, sql, List.of()); + } + + private QueryExecution execute(String catalogName, String contextDatabase, String sql, List parameters) { QueryExecutionContext context = new QueryExecutionContext(); context.setCatalog(catalogName); context.setDatabase(contextDatabase); String id = RequestScopes.callAs(ACCOUNT, REGION, () -> athena.startQueryExecution(sql, "primary", context, - new ResultConfiguration("s3://" + bucket + "/results/"))); + new ResultConfiguration("s3://" + bucket + "/results/"), parameters)); return await().atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofMillis(100)) .until(() -> RequestScopes.callAs(ACCOUNT, REGION, () -> athena.getQueryExecution(id)), found -> found.getStatus().getState() != QueryExecutionState.RUNNING diff --git a/src/test/java/io/floci/aws/services/athena/AthenaJsonHandlerTest.java b/src/test/java/io/floci/aws/services/athena/AthenaJsonHandlerTest.java new file mode 100644 index 0000000000..ba072fed71 --- /dev/null +++ b/src/test/java/io/floci/aws/services/athena/AthenaJsonHandlerTest.java @@ -0,0 +1,57 @@ +package io.floci.aws.services.athena; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** A request's list members reach the service as the strings they hold, in order, and as none when absent. */ +class AthenaJsonHandlerTest { + + private final ObjectMapper mapper = new ObjectMapper(); + private AthenaService athenaService; + private AthenaJsonHandler handler; + + @BeforeEach + void setUp() { + athenaService = mock(AthenaService.class); + when(athenaService.startQueryExecution(anyString(), anyString(), any(), any(), anyList())).thenReturn("query-id"); + handler = new AthenaJsonHandler(athenaService, mock(AthenaNamedQueryService.class), mapper); + } + + @Test + void aQueryIsStartedWithItsExecutionParametersInOrder() throws Exception { + handler.handle("StartQueryExecution", mapper.readTree( + "{\"QueryString\": \"SELECT ? AS region, ? AS n\", \"ExecutionParameters\": [\"'eu'\", \"10\"]}"), + "us-east-1"); + + verify(athenaService).startQueryExecution(eq("SELECT ? AS region, ? AS n"), eq("primary"), isNull(), + isNull(), eq(List.of("'eu'", "10"))); + } + + @Test + void aQueryWithoutExecutionParametersIsStartedWithNone() throws Exception { + handler.handle("StartQueryExecution", mapper.readTree("{\"QueryString\": \"SELECT 1\"}"), "us-east-1"); + + verify(athenaService).startQueryExecution(eq("SELECT 1"), eq("primary"), isNull(), isNull(), eq(List.of())); + } + + @Test + void aResourceIsUntaggedOfTheKeysTheRequestNames() throws Exception { + String arn = "arn:aws:athena:us-east-1:000000000000:workgroup/analytics"; + handler.handle("UntagResource", mapper.readTree( + "{\"ResourceARN\": \"" + arn + "\", \"TagKeys\": [\"Owner\", \"Environment\"]}"), "us-east-1"); + + verify(athenaService).untagResource(arn, List.of("Owner", "Environment")); + } +} 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 3d176cbcaa..ac8649cfbc 100644 --- a/src/test/java/io/floci/aws/services/athena/AthenaServiceTest.java +++ b/src/test/java/io/floci/aws/services/athena/AthenaServiceTest.java @@ -7,12 +7,16 @@ 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.CreateWorkGroupRequest; +import io.floci.aws.services.athena.model.QueryExecutionContext; 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.athena.model.WorkGroupTag; 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.StorageDescriptor; +import io.floci.aws.services.glue.model.Table; import io.floci.aws.services.s3.S3Service; import io.floci.aws.services.s3.model.S3Object; import io.vertx.core.Vertx; @@ -48,6 +52,9 @@ class AthenaServiceTest { private Vertx vertx; private FlociDuckClient duckClient; + private GlueService glueService; + private GlueViewDdlBuilder ddlBuilder; + private AthenaIcebergStatements icebergStatements; private S3Service s3Service; private AthenaService service; @@ -60,10 +67,11 @@ class AthenaServiceTest { doAnswer(invocation -> AccountAwareStorageBackend.inMemory("000000000000")) .when(storageFactory).create(anyString(), anyString(), any()); - GlueService glueService = mock(GlueService.class); + glueService = mock(GlueService.class); when(glueService.getTables(anyString())).thenReturn(List.of()); s3Service = mock(S3Service.class); - GlueViewDdlBuilder ddlBuilder = mock(GlueViewDdlBuilder.class); + ddlBuilder = mock(GlueViewDdlBuilder.class); + icebergStatements = mock(AthenaIcebergStatements.class); EmulatorConfig config = mock(EmulatorConfig.class); EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class); @@ -73,7 +81,7 @@ class AthenaServiceTest { when(athena.mock()).thenReturn(false); service = new AthenaService(storageFactory, duckClient, glueService, s3Service, - config, vertx, ddlBuilder, mock(RegionResolver.class), mock(AthenaIcebergStatements.class), + config, vertx, ddlBuilder, mock(RegionResolver.class), icebergStatements, mock(IamEnforcementFilter.class)); } @@ -282,6 +290,84 @@ class AthenaServiceTest { verify(duckClient).execute(eq("SELECT 1 AS a -- done\n"), any(), any(), any()); } + @Test + void aQueryRunsWithItsExecutionParametersBoundAndIsRecordedWithItsPlaceholders() throws Exception { + String id = service.startQueryExecution("SELECT ? AS region, ? AS n", "primary", null, + new ResultConfiguration("s3://athena-results/"), List.of("'eu'", "10")); + awaitState(id, QueryExecutionState.SUCCEEDED); + + assertEquals("SELECT ? AS region, ? AS n", service.getQueryExecution(id).getQuery()); + verify(duckClient).execute(eq("SELECT 'eu' AS region, 10 AS n\n"), any(), any(), any()); + } + + @Test + void aParameterCountThatDoesNotMatchFailsTheQueryWithAthenasMessage() throws Exception { + String id = service.startQueryExecution("SELECT ? AS a, ? AS b", "primary", null, null, List.of("1")); + awaitState(id, QueryExecutionState.FAILED); + + assertEquals("INVALID_PARAMETER_USAGE: line 1:1: Incorrect number of parameters: expected 2 but found 1", + service.getQueryExecution(id).getStatus().getStateChangeReason()); + verifyNoInteractions(duckClient); + } + + /** + * A value naming a column is bound as written (a TODO at {@code usingListEntry}), so the projection checks read + * the bound statement: {@code tenant = ?} would pass as a static equality, while {@code tenant = (tenant || '')} + * filters nothing and fails as written in place would. A string holding the column's name is a + * literal, and passes. + */ + @Test + void anInjectedPartitionColumnIsCheckedAgainstTheBoundValue() throws Exception { + Table events = new Table(); + events.setName("audit_events"); + StorageDescriptor storage = new StorageDescriptor(); + storage.setLocation("s3://lake/audit_events/"); + storage.setColumns(List.of(column("id"))); + events.setStorageDescriptor(storage); + events.setPartitionKeys(List.of(column("tenant"))); + events.setParameters(Map.of("projection.enabled", "true", "projection.tenant.type", "injected")); + when(glueService.getTables("analytics")).thenReturn(List.of(events)); + String query = "SELECT id FROM audit_events WHERE tenant = ?"; + + String unfiltered = service.startQueryExecution(query, "primary", context("analytics"), + new ResultConfiguration("s3://athena-results/"), List.of("tenant || ''")); + awaitState(unfiltered, QueryExecutionState.FAILED); + assertTrue(service.getQueryExecution(unfiltered).getStatus().getStateChangeReason() + .startsWith("CONSTRAINT_VIOLATION: For the injected projected partition column tenant")); + verifyNoInteractions(duckClient); + + String filtered = service.startQueryExecution(query, "primary", context("analytics"), + new ResultConfiguration("s3://athena-results/"), List.of("'tenant'")); + awaitState(filtered, QueryExecutionState.SUCCEEDED); + verify(duckClient).execute(eq("SELECT id FROM audit_events WHERE tenant = 'tenant'\n"), any(), any(), any()); + } + + /** A value bound as an expression can name a table the query doesn't, and its view is set up all the same. */ + @Test + void theEngineIsSetUpForTheTablesTheBoundStatementNames() throws Exception { + String id = service.startQueryExecution("SELECT ? AS n", "primary", context("analytics"), + new ResultConfiguration("s3://athena-results/"), List.of("(SELECT count(*) FROM events)")); + awaitState(id, QueryExecutionState.SUCCEEDED); + + String bound = "SELECT ((SELECT count(*) FROM events)) AS n"; + verify(ddlBuilder).build("analytics", bound); + verify(icebergStatements).s3TablesAttachment(eq(bound), any(), eq("analytics")); + verify(duckClient).execute(eq(bound + "\n"), any(), any(), any()); + } + + private static QueryExecutionContext context(String database) { + QueryExecutionContext context = new QueryExecutionContext(); + context.setDatabase(database); + return context; + } + + private static Column column(String name) { + Column column = new Column(); + column.setName(name); + column.setType("string"); + return column; + } + private List columnInfo(String query, String csv) throws Exception { return results(query, csv).getMetadata().getColumnInfo(); } diff --git a/src/test/java/io/floci/aws/services/athena/TrinoSqlCompatibilityTest.java b/src/test/java/io/floci/aws/services/athena/TrinoSqlCompatibilityTest.java index 6fa0effa18..8eeeeaf5c6 100644 --- a/src/test/java/io/floci/aws/services/athena/TrinoSqlCompatibilityTest.java +++ b/src/test/java/io/floci/aws/services/athena/TrinoSqlCompatibilityTest.java @@ -1,11 +1,13 @@ package io.floci.aws.services.athena; +import io.floci.aws.core.common.AwsException; import org.junit.jupiter.api.Test; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; class TrinoSqlCompatibilityTest { @@ -259,4 +261,104 @@ class TrinoSqlCompatibilityTest { assertTrue(TrinoSqlCompatibility.holdsSeveralStatements( "CREATE EXTERNAL TABLE t (id string COMMENT 'a\\'; b') LOCATION 's3://bucket/t/'")); } + + @Test + void parametersAreBoundInOrderEachAsAnExpressionOfItsOwn() { + assertEquals("SELECT 'eu' AS s, (1 + 1) * 2 AS n FROM t WHERE d = date('2026-11-10')", + TrinoSqlCompatibility.bindParameters("SELECT ? AS s, ? * 2 AS n FROM t WHERE d = date(?)", + List.of("'eu'", "1 + 1", "'2026-11-10'"))); + assertEquals("SELECT (ARRAY[1, 2]), (f(a, b)), 'x, y', 10, (-1)", + TrinoSqlCompatibility.bindParameters("SELECT ?, ?, ?, ?, ?", + List.of("ARRAY[1, 2]", "f(a, b)", "'x, y'", "10", "-1"))); + } + + /** As on Athena (engine v3), which returns these values as the strings 1);SELECT(2, 1;SELECT2 and 1,2. */ + @Test + void aValueThatIsNotOneExpressionIsBoundAsAStringOfItsTokens() { + assertEquals("SELECT '1);SELECT(2' AS a, '1;SELECT2' AS b, '1,2' AS c, '''a b'',1' AS d", + TrinoSqlCompatibility.bindParameters("SELECT ? AS a, ? AS b, ? AS c, ? AS d", + List.of("1); SELECT (2", "1; SELECT 2", "1, 2", "'a b', 1"))); + } + + /** Brackets as many as they close but not pairing up make no expression either; nested ones that pair do. */ + @Test + void aValueWhoseBracketsDoNotPairUpIsBoundAsAStringOfItsTokens() { + assertEquals("SELECT '(1]' AS a, '([)]' AS b, (f([1], (2))) AS c", + TrinoSqlCompatibility.bindParameters("SELECT ? AS a, ? AS b, ? AS c", + List.of("(1]", "([ ) ]", "f([1], (2))"))); + } + + /** + * An open quote would turn the literals after the placeholder inside out, so the semicolons in them would end + * the statement. Athena (engine v3) returns {@code 'a} as the string {@code 'a}. + */ + @Test + void aValueLeavingAQuoteOpenIsBoundAsAStringAndAddsNoStatement() { + String bound = TrinoSqlCompatibility.bindParameters( + "INSERT INTO t VALUES (?, '); INSERT INTO t2 VALUES (9); --')", List.of("'a")); + + assertEquals("INSERT INTO t VALUES ('''a', '); INSERT INTO t2 VALUES (9); --')", bound); + assertFalse(TrinoSqlCompatibility.holdsSeveralStatements(bound)); + assertEquals("INSERT INTO t VALUES ('''' || '); INSERT INTO t VALUES (9); --')", + TrinoSqlCompatibility.bindParameters("INSERT INTO t VALUES (? || '); INSERT INTO t VALUES (9); --')", + List.of("'"))); + } + + /** As on Athena (engine v3): a lone name is a string, even where a column has it; TRUE, NULL and the like are not. */ + @Test + void aLoneNameIsBoundAsAStringAndAKeywordAsAnExpression() { + assertEquals("SELECT 'x' AS a, '\"x\"' AS b, (true) AS c, (null) AS d, (current_date) AS e, (abs(-3)) AS f", + TrinoSqlCompatibility.bindParameters("SELECT ? AS a, ? AS b, ? AS c, ? AS d, ? AS e, ? AS f", + List.of("x", "\"x\"", "true", "null", "current_date", "abs(-3)"))); + } + + /** Athena (engine v3) returns 1 for both: the value is a token of its own. */ + @Test + void aBoundValueIsSpacedFromTheTokensAroundIt() { + assertEquals("SELECT 1 e2", TrinoSqlCompatibility.bindParameters("SELECT ?e2", List.of("1"))); + assertEquals("SELECT 1", TrinoSqlCompatibility.bindParameters("SELECT?", List.of("1"))); + assertEquals("SELECT (1 + 1)", TrinoSqlCompatibility.bindParameters("SELECT?", List.of("1 + 1"))); + assertEquals("SELECT 'a' || 'b'", TrinoSqlCompatibility.bindParameters("SELECT ? || 'b'", List.of("'a'"))); + } + + /** A literal goes in as if written in place, so a JSON path given as a parameter is translated too. */ + @Test + void aLiteralValueIsBoundBareAndTranslatedAsIfWrittenInPlace() { + assertEquals("SELECT json_extract_scalar(j, '/a b') AS v", TrinoSqlCompatibility.translate( + TrinoSqlCompatibility.bindParameters("SELECT json_extract_scalar(j, ?) AS v", + List.of("'$[\"a b\"]'")))); + } + + @Test + void aQuestionMarkInALiteralAQuotedIdentifierOrACommentIsNotAPlaceholder() { + assertEquals("SELECT '?' AS \"?\", 'x' AS v -- ?\n/* ? */", + TrinoSqlCompatibility.bindParameters("SELECT '?' AS \"?\", ? AS v -- ?\n/* ? */", List.of("'x'"))); + } + + @Test + void aStatementWithoutPlaceholdersRunsAsWrittenWhateverItsParameters() { + assertEquals("SELECT 1 AS a", TrinoSqlCompatibility.bindParameters("SELECT 1 AS a", List.of("1"))); + assertEquals("SELECT 1 AS a", TrinoSqlCompatibility.bindParameters("SELECT 1 AS a", null)); + } + + @Test + void aLineCommentInAValueRunsOnOverTheValuesAfterIt() { + assertEquals("SELECT 1 AS a", TrinoSqlCompatibility.bindParameters("SELECT ? AS a", List.of("1 -- x"))); + assertEquals("INVALID_PARAMETER_USAGE: line 1:1: Incorrect number of parameters: expected 2 but found 1", + assertThrows(AwsException.class, () -> TrinoSqlCompatibility.bindParameters("SELECT ? AS a, ? AS b", + List.of("1 -- x", "2"))).getMessage()); + } + + @Test + void aParameterCountThatDoesNotMatchFailsAtWhereTheStatementStarts() { + assertEquals("INVALID_PARAMETER_USAGE: line 1:1: Incorrect number of parameters: expected 1 but found 2", + assertThrows(AwsException.class, () -> TrinoSqlCompatibility.bindParameters("SELECT ? AS a", + List.of("1", "2"))).getMessage()); + assertEquals("INVALID_PARAMETER_USAGE: line 1:1: Incorrect number of parameters: expected 1 but found 0", + assertThrows(AwsException.class, () -> TrinoSqlCompatibility.bindParameters("SELECT ? AS a", + List.of())).getMessage()); + assertEquals("INVALID_PARAMETER_USAGE: line 2:1: Incorrect number of parameters: expected 1 but found 0", + assertThrows(AwsException.class, () -> TrinoSqlCompatibility.bindParameters("-- lead\nSELECT ? AS a", + null)).getMessage()); + } }