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
This commit is contained in:
Ghassan Gedeon Achi authored and GitHub committed 2026-11-17 19:16:51 -04:00
1 parent 6a92129c2f
commit 87a93ebe92
9 files changed
+579 -27

No files matched your search

@@ -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<String> 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<String> strings(JsonNode request, String field) {
JsonNode node = request.get(field);
if (node == null || !node.isArray()) {
return List.of();
}
List<String> keys = new ArrayList<>();
for (JsonNode key : node) {
keys.add(key.asText());
List<String> strings = new ArrayList<>();
for (JsonNode string : node) {
strings.add(string.asText());
}
return keys;
return strings;
}
}
@@ -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<String> 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<String> 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<Table> 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);
}
@@ -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;
* </ul>
*
* <p>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<String> 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.
*
* <p>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.
*
* <p>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:
*
* <pre>INVALID_PARAMETER_USAGE: line 1:1: Incorrect number of parameters: expected 2 but found 1</pre>
*
* A {@code ?} in a literal, a quoted identifier or a comment is not a placeholder.
*
* <p>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<String> parameters) {
if (statement == null) {
return null;
}
List<Integer> 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<String> 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.
*
* <p>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.
*
* <p>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) {