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

@@ -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/'"));
}
}