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

@@ -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<String> 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<Map<String, String>> 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<Map<String, String>> rows = fixture.query(
TrinoSqlCompatibility.bindParameters("SELECT ? * 2 AS a", List.of("1 + 1")));
assertEquals(List.of(Map.of("a", "4")), rows);
}
}
}
@@ -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<String> 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
@@ -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"));
}
}
@@ -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<ResultSet.ColumnInfo> columnInfo(String query, String csv) throws Exception {
return results(query, csv).getMetadata().getColumnInfo();
}
@@ -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());
}
}