fix(athena): run a query that ends in a semicolon or a comment, and reject a second statement (#8682)

This commit is contained in:
Ghassan Gedeon Achi authored and GitHub committed 2026-11-17 14:40:44 -04:00
1 parent f0b8368a9e
commit f64dea0ba5
8 files changed
+348 -7

No files matched your search

+8 -1
View File
@@ -113,9 +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 "<schema>"`) and, for each table the query names, creates qualified views (`CREATE OR REPLACE VIEW "<db>"."<table>"`) 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 "<table>"` 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.
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).
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
`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.
## Trino SQL on DuckDB
Athena engine version 3 runs Trino SQL; Floci runs it on DuckDB, so a few Trino constructs are bridged before the query reaches the sidecar:
@@ -154,10 +154,20 @@ public class AthenaService {
this.hiveDdlExecutor = new AthenaHiveDdlExecutor(glueService, s3Service, icebergStatements);
}
public String startQueryExecution(String query,
public String startQueryExecution(String submitted,
String workGroup,
QueryExecutionContext context,
ResultConfiguration resultConfiguration) {
// 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.
if (TrinoSqlCompatibility.holdsSeveralStatements(submitted)) {
throw new AwsException("InvalidRequestException", "Only one sql statement is allowed. Got: " + submitted,
400, Map.of("AthenaErrorCode", "MALFORMED_QUERY"));
}
// 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);
String id = UUID.randomUUID().toString();
String database = context != null && context.getDatabase() != null ? context.getDatabase() : "default";
QueryExecutionContext resolvedContext = context != null ? context : new QueryExecutionContext();
@@ -282,7 +292,9 @@ public class AthenaService {
if (outputLocation != null) {
ensureOutputBucket(outputLocation);
}
duckClient.execute(duckQuery, setupDdl, outputLocation, accountId);
// floci-duck runs a query that returns rows as COPY (<query>) TO ... on one line, so a line
// comment ending the query would comment out the ) TO ... after it; a line break ends it.
duckClient.execute(duckQuery + "\n", setupDdl, outputLocation, accountId);
if (outputLocation != null) {
resultColumnTypeStore.put(id, describeColumnTypes(duckQuery, setupDdl, accountId));
}
@@ -31,6 +31,9 @@ import java.util.regex.Pattern;
* <li>a multi-argument {@code UNNEST} source, which DuckDB's one-argument {@code unnest} rejects, into a
* lateral subquery holding one {@code unnest} per array (see {@link #multiArgumentUnnest}).</li>
* </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}).
*/
final class TrinoSqlCompatibility {
@@ -100,6 +103,83 @@ final class TrinoSqlCompatibility {
return out.toString();
}
// ---- the statement a query string holds ----
/**
* Whether {@code sql} holds more than one statement: anything but whitespace on both sides of a
* semicolon, a comment included. Athena (engine v3) rejects such a query at submission, so
* {@code SELECT 1; -- done} fails as {@code SELECT 1; SELECT 2} does, while {@code SELECT 1;;} and
* {@code ;SELECT 1} run. A semicolon in a literal, a quoted identifier (backticks included, as in
* Hive DDL) or a comment separates nothing. Athena reads Hive DDL by the same rules here, so a
* semicolon after a Hive {@code \'} escape in a literal separates statements on Athena too.
*
* <p>Trino ends a block comment at its first {@code *}{@code /}, but DuckDB, which runs the statement,
* nests them. A query is taken for several statements when either reading finds a second one, so text
* DuckDB would run as a second statement cannot pass for a comment or a literal here. Athena rejects such a
* query too, as a syntax error.
*/
static boolean holdsSeveralStatements(String sql) {
return sql != null && (bounds(sql, false).several() || bounds(sql, true).several());
}
/**
* {@code sql} as Athena (engine v3) records, returns and runs it: without the whitespace and semicolons
* around it. {@code SELECT 1 ;\n} and {@code ;SELECT 1} become {@code SELECT 1}, for DDL and DML as for
* queries. A comment at either end stays, as does a semicolon in a literal. A query holding nothing else
* is returned as given.
*/
static String recordedForm(String sql) {
if (sql == null) {
return null;
}
StatementBounds bounds = bounds(sql, false);
return bounds.start() >= 0 ? sql.substring(bounds.start(), bounds.end()) : sql;
}
/**
* 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)}).
*/
private record StatementBounds(int start, int end, boolean several) {
}
private static StatementBounds bounds(String sql, boolean nestedComments) {
int start = -1;
int end = 0;
boolean semicolonAfterStatement = false;
boolean several = false;
int i = 0;
while (i < sql.length()) {
char c = sql.charAt(i);
if (Character.isWhitespace(c)) {
i++;
continue;
}
if (c == ';') {
semicolonAfterStatement |= start >= 0;
i++;
continue;
}
several |= semicolonAfterStatement;
start = start < 0 ? i : start;
int next = skipLiteralOrComment(sql, i, nestedComments);
boolean comment = sql.startsWith("--", i) || sql.startsWith("/*", i);
if (next == i) {
next = i + 1;
}
// 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))) {
end--;
}
i = next;
}
return new StatementBounds(start, end, several);
}
private static String translateCast(String inner) {
int as = lastTopLevelAs(inner);
if (as < 0) {
@@ -474,18 +554,51 @@ final class TrinoSqlCompatibility {
}
private static int skipLiteralOrComment(String sql, int i) {
return skipLiteralOrComment(sql, i, false);
}
/**
* Index just past the literal, quoted identifier or comment starting at {@code i}, or {@code i} when none
* starts there. A backtick-quoted identifier is skipped like a double-quoted one: Trino's lexer reads it as
* one token (and rejects it in a query), and Hive DDL names columns with it. A block comment ends at its
* first {@code *}{@code /}, as in Trino, or, with {@code nestedComments}, at the one matching its opening,
* as in DuckDB.
*/
private static int skipLiteralOrComment(String sql, int i, boolean nestedComments) {
char c = sql.charAt(i);
if (c == '\'' || c == '"') {
if (c == '\'' || c == '"' || c == '`') {
return skipQuoted(sql, i);
}
if (sql.startsWith("--", i)) {
int end = sql.indexOf('\n', i);
return end < 0 ? sql.length() : end + 1;
// A line comment ends at a carriage return as at a line feed, in Trino as in DuckDB.
int end = i + 2;
while (end < sql.length() && sql.charAt(end) != '\n' && sql.charAt(end) != '\r') {
end++;
}
return end < sql.length() ? end + 1 : sql.length();
}
if (sql.startsWith("/*", i)) {
if (sql.startsWith("/*", i) && !nestedComments) {
int end = sql.indexOf("*/", i + 2);
return end < 0 ? sql.length() : end + 2;
}
if (sql.startsWith("/*", i)) {
int depth = 0;
int j = i;
while (j < sql.length()) {
if (sql.startsWith("/*", j)) {
depth++;
j += 2;
} else if (sql.startsWith("*/", j)) {
j += 2;
if (--depth == 0) {
return j;
}
} else {
j++;
}
}
return sql.length();
}
return i;
}
@@ -2,6 +2,7 @@ package io.floci.aws.services.athena;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.IamEnforcementFilter;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.RequestScopes;
@@ -41,6 +42,7 @@ import java.util.TreeMap;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
@@ -145,6 +147,23 @@ class AthenaIcebergSidecarIntegrationTest {
assertEquals("2", loadTable("events").path("metadata").path("properties").path("format-version").asText());
}
/**
* A query holding two writes is rejected before either runs, as on Athena (engine v3). Run, only the first would
* have reached the Iceberg catalog, and it would have committed before the second failed.
*/
@Test
void aQueryHoldingASecondWriteIsRejectedAndWritesNothing() {
run("CREATE TABLE events (id bigint) LOCATION 's3://" + bucket + "/lake/events/' "
+ "TBLPROPERTIES ('table_type'='ICEBERG');");
run("INSERT INTO events VALUES (1);");
AwsException rejected = assertThrows(AwsException.class,
() -> execute(null, database, "INSERT INTO events VALUES (3); INSERT INTO events VALUES (4)"));
assertEquals("InvalidRequestException", rejected.getErrorCode());
assertEquals(List.of(row("id", "1")), rows("SELECT id 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");
@@ -578,4 +578,44 @@ class AthenaIntegrationTest {
.statusCode(200)
.body("QueryExecution.WorkGroup", equalTo("primary"));
}
@Test
@Order(18)
void startQueryExecutionRecordsTheQueryWithoutItsTrailingSemicolons() {
String id = given()
.header("X-Amz-Target", "AmazonAthena.StartQueryExecution")
.contentType(CONTENT_TYPE)
.body("{ \"QueryString\": \"\\nSELECT 1 ;;\\n\" }")
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("QueryExecutionId");
given()
.header("X-Amz-Target", "AmazonAthena.GetQueryExecution")
.contentType(CONTENT_TYPE)
.body("{ \"QueryExecutionId\": \"" + id + "\" }")
.when()
.post("/")
.then()
.statusCode(200)
.body("QueryExecution.Query", equalTo("SELECT 1"));
}
@Test
@Order(19)
void startQueryExecutionRejectsASecondStatementAsMalformed() {
given()
.header("X-Amz-Target", "AmazonAthena.StartQueryExecution")
.contentType(CONTENT_TYPE)
.body("{ \"QueryString\": \"SELECT 1; -- done\" }")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"))
.body("message", equalTo("Only one sql statement is allowed. Got: SELECT 1; -- done"))
.body("AthenaErrorCode", equalTo("MALFORMED_QUERY"));
}
}
@@ -1,6 +1,7 @@
package io.floci.aws.services.athena;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.IamEnforcementFilter;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
@@ -26,6 +27,7 @@ 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.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
@@ -33,6 +35,8 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
@@ -254,6 +258,30 @@ class AthenaServiceTest {
.map(ResultSet.ColumnInfo::getType).toList());
}
@Test
void aQueryHoldingASecondStatementIsRejectedBeforeAnExecutionExists() {
String twoInserts = "INSERT INTO t VALUES (3); INSERT INTO t VALUES (4)";
AwsException rejected = assertThrows(AwsException.class,
() -> service.startQueryExecution(twoInserts, "primary", null, null));
assertEquals("InvalidRequestException", rejected.getErrorCode());
assertEquals("Only one sql statement is allowed. Got: " + twoInserts, rejected.getMessage());
assertEquals(Map.of("AthenaErrorCode", "MALFORMED_QUERY"), rejected.getExtendedData());
assertEquals(List.of(), service.listQueryExecutions());
verifyNoInteractions(duckClient);
}
@Test
void aQueryIsRecordedWithoutTheSemicolonsAroundItAndRunsWithItsLastLineEnded() throws Exception {
String id = service.startQueryExecution("\n;SELECT 1 AS a -- done\n;\n", "primary", null,
new ResultConfiguration("s3://athena-results/"));
awaitState(id, QueryExecutionState.SUCCEEDED);
assertEquals("SELECT 1 AS a -- done", service.getQueryExecution(id).getQuery());
verify(duckClient).execute(eq("SELECT 1 AS a -- done\n"), any(), any(), any());
}
private List<ResultSet.ColumnInfo> columnInfo(String query, String csv) throws Exception {
return results(query, csv).getMetadata().getColumnInfo();
}
@@ -0,0 +1,53 @@
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.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* A query that returns rows reaches the real floci-duck sidecar wrapped as {@code COPY (<query>) TO '<output>' ...},
* where a trailing semicolon or line comment left in the query breaks the statement. Athena runs such a query, so the
* form Floci gives the engine must survive the wrapping.
*/
@QuarkusTest
@TestProfile(SidecarContainersProfile.class)
class AthenaStatementEndSidecarIntegrationTest {
@Inject
FlociDuckClient duck;
@Inject
S3Service s3Service;
@BeforeAll
static void requireDocker() {
SidecarContainersProfile.requireDocker();
}
@ParameterizedTest
@ValueSource(strings = {"SELECT 1 AS a;", "SELECT 1 AS a ;;\n", ";SELECT 1 AS a", "SELECT 1 AS a -- done",
"SELECT 1 AS a -- done\n", "SELECT 1 AS a /* done */;", "SELECT 1 AS a -- done\n;", "SELECT 1 AS a -- done\r"})
void aQueryEndingInASemicolonOrACommentWritesItsResult(String submitted) {
try (AthenaSidecarFixture fixture = new AthenaSidecarFixture(duck, s3Service, "statementend")) {
String key = "results/out.csv";
fixture.wrote(key);
// As AthenaService gives it to the engine: the recorded form, its last line ended.
duck.execute(TrinoSqlCompatibility.recordedForm(submitted) + "\n", null,
"s3://" + fixture.bucket() + "/" + key);
assertEquals("a\n1\n", new String(s3Service.getObject(fixture.bucket(), key).getData(),
StandardCharsets.UTF_8));
}
}
}
@@ -5,6 +5,8 @@ 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.assertTrue;
class TrinoSqlCompatibilityTest {
@@ -190,4 +192,71 @@ class TrinoSqlCompatibilityTest {
void anUnbalancedCastIsReturnedAsWritten() {
assertEquals("SELECT CAST(x AS ARRAY<JSON>", TrinoSqlCompatibility.translate("SELECT CAST(x AS ARRAY<JSON>"));
}
@Test
void theRecordedFormDropsTrailingSemicolonsAndTheWhitespaceAroundTheStatement() {
assertEquals("SELECT 1", TrinoSqlCompatibility.recordedForm("SELECT 1;"));
assertEquals("SELECT 1", TrinoSqlCompatibility.recordedForm("SELECT 1 ;"));
assertEquals("SELECT 1", TrinoSqlCompatibility.recordedForm("\n SELECT 1;; ;\n"));
assertEquals("DROP TABLE t", TrinoSqlCompatibility.recordedForm("DROP TABLE t;;"));
assertEquals("SELECT 1", TrinoSqlCompatibility.recordedForm(";SELECT 1"));
assertEquals("SELECT 1", TrinoSqlCompatibility.recordedForm("SELECT 1"));
}
@Test
void aQueryHoldingNoStatementIsRecordedAsGiven() {
for (String sql : List.of("", " \n", ";", "; ;")) {
assertEquals(sql, TrinoSqlCompatibility.recordedForm(sql));
assertFalse(TrinoSqlCompatibility.holdsSeveralStatements(sql));
}
assertEquals("-- only a comment", TrinoSqlCompatibility.recordedForm(" -- only a comment\n;"));
}
@Test
void theRecordedFormKeepsCommentsAtEitherEndAndSemicolonsInsideTheStatement() {
assertEquals("SELECT 1 -- done", TrinoSqlCompatibility.recordedForm("SELECT 1 -- done\r\n"));
assertEquals("SELECT 1 -- done", TrinoSqlCompatibility.recordedForm("SELECT 1 -- done\r;"));
assertEquals("SELECT 1 /* c */", TrinoSqlCompatibility.recordedForm("SELECT 1 /* c */;"));
assertEquals("-- lead\nSELECT 1", TrinoSqlCompatibility.recordedForm("\n-- lead\nSELECT 1;"));
assertEquals("SELECT 'a;b' AS \"c;\"", TrinoSqlCompatibility.recordedForm("SELECT 'a;b' AS \"c;\";"));
}
@Test
void aSemicolonWithAStatementOnBothSidesSeparatesTwo() {
assertTrue(TrinoSqlCompatibility.holdsSeveralStatements("SELECT 1; SELECT 2"));
assertTrue(TrinoSqlCompatibility.holdsSeveralStatements("SELECT 1; -- done"));
assertTrue(TrinoSqlCompatibility.holdsSeveralStatements("SELECT 1; /* done */"));
assertTrue(TrinoSqlCompatibility.holdsSeveralStatements("-- lead\n; SELECT 1"));
assertTrue(TrinoSqlCompatibility.holdsSeveralStatements("INSERT INTO t VALUES (3);INSERT INTO t VALUES (4)"));
assertTrue(TrinoSqlCompatibility.holdsSeveralStatements("SELECT 1 -- a carriage return ends me\r; SELECT 2"));
assertFalse(TrinoSqlCompatibility.holdsSeveralStatements("SELECT 1;; ;\n"));
assertFalse(TrinoSqlCompatibility.holdsSeveralStatements(";SELECT 1"));
assertFalse(TrinoSqlCompatibility.holdsSeveralStatements(
"SELECT 'a; b' AS s, \"c;d\" AS q -- e; f\n/* g; h */"));
}
/** Athena (engine v3) runs this: a backtick-quoted name is one token, as in Trino's lexer. */
@Test
void aSemicolonInABacktickQuotedNameSeparatesNothing() {
assertFalse(TrinoSqlCompatibility.holdsSeveralStatements(
"CREATE EXTERNAL TABLE t (`a;b` int, `c``;d` int) LOCATION 's3://bucket/t/'"));
}
/**
* Trino ends the comment at its first close, leaving a literal holding the semicolon; DuckDB nests it, leaving a
* second INSERT. Either reading's second statement counts, and Athena (engine v3) rejects the query too.
*/
@Test
void aSecondStatementEitherTrinoOrDuckDbWouldReadCounts() {
assertTrue(TrinoSqlCompatibility.holdsSeveralStatements(
"INSERT INTO t VALUES (1) /* outer /* inner */ ' */; INSERT INTO t VALUES (2) -- '"));
assertFalse(TrinoSqlCompatibility.holdsSeveralStatements("SELECT /* a /* b */ 1 AS a"));
}
/** Athena (engine v3) splits Hive DDL by the same rules, so it rejects this as two statements too. */
@Test
void aSemicolonAfterAHiveBackslashEscapeSeparatesStatementsAsOnAthena() {
assertTrue(TrinoSqlCompatibility.holdsSeveralStatements(
"CREATE EXTERNAL TABLE t (id string COMMENT 'a\\'; b') LOCATION 's3://bucket/t/'"));
}
}