feat(dsql): speak DSQL's dialect and keep its transaction limits (#6185)

* feat(dsql): speak DSQL's dialect and keep its transaction limits

The third part of the DSQL data plane, after #6102 and #6143: the cluster's
database answers the way Aurora DSQL does, as measured on AWS.

CREATE [UNIQUE] INDEX ASYNC answers a job_id, with sys.jobs and
sys.wait_for_job; a plain CREATE INDEX is refused. What DSQL refuses is
refused with its SQLSTATE and message: what the statement shows (TRUNCATE,
DO, LISTEN, VACUUM, sequence caches, isolation levels, locking clauses,
advisory locks, ADD CONSTRAINT) in DsqlStatements, and what only the catalog
can tell (column types, a function's language, temporary and partitioned
tables, triggers) inside the database, by event triggers, since the
statement alone cannot say.

A transaction runs one DDL statement, never with DML, and modifies at most
3,000 rows, a cascade's included. Its age follows what was measured with a
client that only reads: the client's next message after 300 seconds ends it
with 54000 and closes the connection with 08P01, an idle one is ended unasked
15 seconds later, a statement running across the limit completes and then
fails with 54000, and a failed transaction left idle as long is closed with
25P03. A first model, the age checked at the next statement, was dropped once
the reading client showed DSQL's own timer.

A write conflict is DSQL's 40001 OC000, and an error's context keeps the
statement a cascade ran while dropping what sys functions ran.

* fix(dsql): close the dialect's gaps found in review, as measured on DSQL

Measured on Aurora DSQL before each change:
- set_config of default_transaction_isolation or transaction_isolation, a
  quoted SET of one and ALTER ROLE ... SET of one answer 0A000 "not
  supported"; ALTER DATABASE ... SET or RESET is AlterDatabaseSet.
- CREATE TABLE AS, SELECT INTO and materialized views are CreateTableAs,
  refused by the event trigger so a function body cannot reach them either.
- An expression key, or a domain over jsonb or bytea, is refused like the
  type itself, named as declared: the check reads the index's own columns
  and follows a domain to its base type.
- CREATE, ALTER and DROP ROLE and GRANT or REVOKE of a role are DDL.
  PostgreSQL fires no event trigger for them, so they run through
  sys.run_role_ddl, which counts them first, under PostgreSQL's tags.
- A statement past the transaction age limit fails with 54000, in a
  transaction block or not, nothing its transaction wrote is kept, and the
  rest of its query, a COMMIT included, does not run.

The age limit is reworked as the review asked. Each session has one check
scheduled at a time, on the endpoint's scheduler and by the injected Clock,
cancelled when the transaction or the connection ends; a failed
transaction's idle wait restarts after every client message. At the limit
a statement still running is cancelled with the client's own cancel
request, and its 57014 reaches the client as DSQL's 54000. DSQL lets the
statement finish and fails it then; stopping it at the limit ends the same
way. Two other ways were tried and dropped: dropping a late statement's
answer in the relay let a COMMIT in the same query commit, and a mark the
endpoint writes for the database to check is invisible to the client's
repeatable read snapshot. The age test now moves the clock and holds a row
instead of sleeping, and shares its cluster setup with the data plane test
through DsqlClusterFixture.

Also fixed: a -- comment ends at a carriage return, a quoted advisory lock
name is refused, CACHE is read from tokens rather than the raw text, a
BEGIN queued behind a long statement starts once that statement is
answered, tables that predate the counting triggers get them, and
sys.create_index_async runs one index statement and nothing else.

sys.wait_for_job with an unknown id keeps waiting, as DSQL's does.
This commit is contained in:
Alessandro Lattao authored and GitHub committed 2026-10-21 21:18:17 -04:00
1 parent 6355474ad2
commit 42fd858311
12 files changed
+2220 -309

No files matched your search

@@ -0,0 +1,103 @@
package io.github.hectorvent.floci.services.dsql;
import com.github.dockerjava.api.DockerClient;
import io.github.hectorvent.floci.services.dsql.dataplane.DsqlEndpoint;
import io.github.hectorvent.floci.testutil.SigV4TokenTestHelper;
import io.restassured.specification.RequestSpecification;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.Properties;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* A DSQL cluster a test class creates through Floci's control plane, with a real database behind
* it, and the ways a client reaches that database: JDBC over TLS with an IAM token, or the wire
* protocol written by hand.
*/
public final class DsqlClusterFixture {
public static final String ACCOUNT = "111122223333";
public static final String REGION = "eu-west-1";
private static final String AUTH = "AWS4-HMAC-SHA256 Credential=" + ACCOUNT
+ "/20261016/" + REGION + "/dsql/aws4_request, SignedHeaders=host, Signature=abc";
private final int httpPort;
private final DsqlEndpoint endpoint;
private String identifier;
private String host;
public DsqlClusterFixture(int httpPort, DsqlEndpoint endpoint) {
this.httpPort = httpPort;
this.endpoint = endpoint;
}
/** Creates the cluster and waits until it is ACTIVE; skips the test class when Docker is not there. */
public void create(DockerClient dockerClient) {
try {
dockerClient.pingCmd().exec();
} catch (Exception e) {
assumeTrue(false, "Docker is not available: " + e.getMessage());
}
identifier = dsql().body(Map.of("deletionProtectionEnabled", false))
.post("/cluster").then().statusCode(200).extract().path("identifier");
host = identifier + ".dsql." + REGION + ".localhost.floci.io";
await().atMost(Duration.ofMinutes(3)).pollInterval(Duration.ofMillis(500)).until(() ->
"ACTIVE".equals(dsql().get("/cluster/" + identifier).then().extract().path("status")));
}
public void delete() {
if (identifier != null) {
dsql().delete("/cluster/" + identifier);
await().atMost(Duration.ofMinutes(1)).until(() ->
dsql().get("/cluster/" + identifier).then().extract().statusCode() == 404);
}
}
public String host() {
return host;
}
public String url() {
return "jdbc:postgresql://127.0.0.1:" + endpoint.port() + "/postgres";
}
/** What JDBC needs to sign in as {@code user}: TLS, without checking Floci's certificate. */
public Properties properties(String user, String password) {
Properties properties = new Properties();
properties.setProperty("user", user);
properties.setProperty("password", password);
properties.setProperty("sslmode", "require");
properties.setProperty("sslfactory", "org.postgresql.ssl.NonValidatingFactory");
return properties;
}
public Connection connect(String user, String password) throws SQLException {
return DriverManager.getConnection(url(), properties(user, password));
}
public DsqlWireClient wireClient(String user, String password) throws Exception {
return new DsqlWireClient(endpoint.port(), host, user, password);
}
public String adminToken() throws Exception {
return token("DbConnectAdmin", "test", "test", Instant.now(), 900, null);
}
public String token(String action, String accessKeyId, String secret, Instant at, int expires,
String sessionToken) throws Exception {
return SigV4TokenTestHelper.createDsqlToken(host, REGION, action, accessKeyId, secret, at, expires,
sessionToken);
}
private RequestSpecification dsql() {
return given().port(httpPort).header("Authorization", AUTH).contentType("application/json");
}
}
@@ -1,15 +1,12 @@
package io.github.hectorvent.floci.services.dsql;
import com.github.dockerjava.api.DockerClient;
import io.github.hectorvent.floci.core.common.PostgresWire;
import io.github.hectorvent.floci.services.dsql.dataplane.DsqlEndpoint;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.github.hectorvent.floci.testutil.SigV4TokenTestHelper;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.junit.jupiter.api.AfterAll;
@@ -18,36 +15,30 @@ import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.postgresql.ssl.NonValidatingFactory;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLWarning;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static io.github.hectorvent.floci.services.dsql.DsqlWireClient.bind;
import static io.github.hectorvent.floci.services.dsql.DsqlWireClient.close;
import static io.github.hectorvent.floci.services.dsql.DsqlWireClient.execute;
import static io.github.hectorvent.floci.services.dsql.DsqlWireClient.parse;
import static io.github.hectorvent.floci.services.dsql.DsqlWireClient.query;
import static io.github.hectorvent.floci.services.dsql.DsqlWireClient.sync;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* Aurora DSQL's data plane against a real PostgreSQL container: a client connects to the cluster
@@ -59,11 +50,8 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue;
@Tag("docker")
class DsqlDataPlaneIntegrationTest {
private static final String ACCOUNT = "111122223333";
private static final String REGION = "eu-west-1";
private static final String ACCOUNT = DsqlClusterFixture.ACCOUNT;
private static final String ROLE_ARN = "arn:aws:iam::" + ACCOUNT + ":role/service/app-role";
private static final String AUTH = "AWS4-HMAC-SHA256 Credential=" + ACCOUNT
+ "/20261016/" + REGION + "/dsql/aws4_request, SignedHeaders=host, Signature=abc";
@Inject
DockerClient dockerClient;
@@ -80,35 +68,22 @@ class DsqlDataPlaneIntegrationTest {
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
private String identifier;
private String host;
private DsqlClusterFixture cluster;
@BeforeAll
void createCluster() {
try {
dockerClient.pingCmd().exec();
} catch (Exception e) {
assumeTrue(false, "Docker is not available: " + e.getMessage());
}
identifier = dsql().body(Map.of("deletionProtectionEnabled", false))
.post("/cluster").then().statusCode(200).extract().path("identifier");
host = identifier + ".dsql." + REGION + ".localhost.floci.io";
await().atMost(Duration.ofMinutes(3)).pollInterval(Duration.ofMillis(500)).until(() ->
"ACTIVE".equals(dsql().get("/cluster/" + identifier).then().extract().path("status")));
cluster = new DsqlClusterFixture(httpPort, endpoint);
cluster.create(dockerClient);
}
@AfterAll
void deleteCluster() {
if (identifier != null) {
dsql().delete("/cluster/" + identifier);
await().atMost(Duration.ofMinutes(1)).until(() ->
dsql().get("/cluster/" + identifier).then().extract().statusCode() == 404);
}
cluster.delete();
}
@Test
void adminConnectsWithAnAdminTokenToDsqlsDatabase() throws Exception {
try (Connection connection = connect("admin", adminToken());
try (Connection connection = admin();
Statement statement = connection.createStatement();
ResultSet row = statement.executeQuery("SELECT current_user, current_setting('transaction_isolation'),"
+ " (SELECT nspowner::regrole::text FROM pg_namespace WHERE nspname = 'public'),"
@@ -125,9 +100,9 @@ class DsqlDataPlaneIntegrationTest {
@Test
void aConnectionIsRefusedAsDsqlRefusesIt() throws Exception {
PSQLException plain = assertThrows(PSQLException.class, () -> {
Properties properties = properties("admin", adminToken());
Properties properties = cluster.properties("admin", cluster.adminToken());
properties.setProperty("sslmode", "disable");
DriverManager.getConnection(url(), properties).close();
DriverManager.getConnection(cluster.url(), properties).close();
});
assertEquals("unable to accept connection, SSL is mandatory. AWS Authentication is required.",
plain.getServerErrorMessage().getMessage());
@@ -135,24 +110,25 @@ class DsqlDataPlaneIntegrationTest {
assertTrue(plain.getServerErrorMessage().getDetail().startsWith("Session Id: "));
PSQLException wrongAction = assertThrows(PSQLException.class, () ->
connect("admin", token("DbConnect", "test", "test", Instant.now(), 900, null)).close());
cluster.connect("admin", cluster.token("DbConnect", "test", "test", Instant.now(), 900, null)).close());
assertEquals("unable to accept connection, access denied", wrongAction.getServerErrorMessage().getMessage());
assertEquals("08006", wrongAction.getSQLState());
assertTrue(wrongAction.getServerErrorMessage().getDetail().startsWith("Session Id: "));
assertEquals("Wrong user to action mapping. user: admin, action: DbConnect",
wrongAction.getServerErrorMessage().getHint());
PSQLException expired = assertThrows(PSQLException.class, () -> connect("admin",
token("DbConnectAdmin", "test", "test", Instant.now().minusSeconds(120), 60, null)).close());
PSQLException expired = assertThrows(PSQLException.class, () -> cluster.connect("admin",
cluster.token("DbConnectAdmin", "test", "test", Instant.now().minusSeconds(120), 60, null)).close());
assertTrue(expired.getServerErrorMessage().getHint().startsWith("Signature expired: "),
expired.getServerErrorMessage().getHint());
PSQLException garbage = assertThrows(PSQLException.class, () -> connect("admin", "not-a-token").close());
PSQLException garbage = assertThrows(PSQLException.class, () ->
cluster.connect("admin", "not-a-token").close());
assertEquals("unable to accept connection, access denied", garbage.getServerErrorMessage().getMessage());
assertEquals(null, garbage.getServerErrorMessage().getHint());
PSQLException otherDatabase = assertThrows(PSQLException.class, () -> {
Properties properties = properties("admin", adminToken());
Properties properties = cluster.properties("admin", cluster.adminToken());
DriverManager.getConnection("jdbc:postgresql://127.0.0.1:" + endpoint.port() + "/other", properties)
.close();
});
@@ -167,23 +143,28 @@ class DsqlDataPlaneIntegrationTest {
String secret = "app+session/secret=key";
String sessionToken = "IQoJb3JpZ2luX2VjEJr+app/role+session==";
iamService.registerLambdaExecutionRoleSession(ACCOUNT, accessKeyId, secret, sessionToken, ROLE_ARN);
try (Connection admin = connect("admin", adminToken()); Statement statement = admin.createStatement()) {
try (Connection admin = admin(); Statement statement = admin.createStatement()) {
statement.execute("CREATE ROLE app_role WITH LOGIN");
PSQLException unmapped = assertThrows(PSQLException.class, () -> connect("app_role",
token("DbConnect", accessKeyId, secret, Instant.now(), 900, sessionToken)).close());
PSQLException unmapped = assertThrows(PSQLException.class, () -> cluster.connect("app_role",
cluster.token("DbConnect", accessKeyId, secret, Instant.now(), 900, sessionToken)).close());
assertEquals("unable to accept connection, access denied", unmapped.getServerErrorMessage().getMessage());
assertEquals("28000", unmapped.getSQLState());
statement.execute("AWS IAM GRANT app_role TO '" + ROLE_ARN + "'");
try (Connection app = connect("app_role", token("DbConnect", accessKeyId, secret, Instant.now(), 900,
sessionToken));
statement.execute("CREATE TABLE owned_by_admin (id int PRIMARY KEY, n int)");
statement.executeQuery("CREATE INDEX ASYNC owned_by_admin_n ON owned_by_admin (n)").close();
try (Connection app = cluster.connect("app_role",
cluster.token("DbConnect", accessKeyId, secret, Instant.now(), 900, sessionToken));
Statement query = app.createStatement()) {
try (ResultSet row = query.executeQuery("SELECT current_user, sys.iam_session_user()")) {
assertTrue(row.next());
assertEquals("app_role", row.getString(1));
assertEquals(ROLE_ARN, row.getString(2));
}
PSQLException notOwner = assertThrows(PSQLException.class, () -> query.executeQuery(
"SELECT sys._invalidate_index('public.owned_by_admin_n'::regclass)").close());
assertEquals("42501", notOwner.getSQLState());
}
statement.execute("AWS IAM GRANT app_role TO '" + ROLE_ARN + "'");
@@ -197,8 +178,8 @@ class DsqlDataPlaneIntegrationTest {
mapped.getServerErrorMessage().getDetail());
assertNull(mapped.getServerErrorMessage().getWhere());
PSQLException adminAction = assertThrows(PSQLException.class, () -> connect("app_role",
token("DbConnectAdmin", accessKeyId, secret, Instant.now(), 900, sessionToken)).close());
PSQLException adminAction = assertThrows(PSQLException.class, () -> cluster.connect("app_role",
cluster.token("DbConnectAdmin", accessKeyId, secret, Instant.now(), 900, sessionToken)).close());
assertEquals("Wrong user to action mapping. user: app_role, action: DbConnectAdmin",
adminAction.getServerErrorMessage().getHint());
@@ -211,12 +192,12 @@ class DsqlDataPlaneIntegrationTest {
assertEquals("42501", itself.getSQLState());
assertEquals("Only roles with the ADMIN option on role \"admin\" may grant IAM trust to this role.",
itself.getServerErrorMessage().getDetail());
assertThrows(PSQLException.class, () -> connect("dbowner",
token("DbConnect", accessKeyId, secret, Instant.now(), 900, sessionToken)).close());
assertThrows(PSQLException.class, () -> cluster.connect("dbowner",
cluster.token("DbConnect", accessKeyId, secret, Instant.now(), 900, sessionToken)).close());
statement.execute("AWS IAM REVOKE app_role FROM '" + ROLE_ARN + "'");
assertThrows(PSQLException.class, () -> connect("app_role",
token("DbConnect", accessKeyId, secret, Instant.now(), 900, sessionToken)).close());
assertThrows(PSQLException.class, () -> cluster.connect("app_role",
cluster.token("DbConnect", accessKeyId, secret, Instant.now(), 900, sessionToken)).close());
statement.execute("DROP ROLE app_role");
} finally {
iamService.unregisterSession(ACCOUNT, accessKeyId);
@@ -229,11 +210,11 @@ class DsqlDataPlaneIntegrationTest {
EnforcementFixtures.UserCredentials user = EnforcementFixtures.createUser(cleanup, httpPort,
EnforcementFixtures.auth(ACCOUNT, "iam"), userName);
String userArn = "arn:aws:iam::" + ACCOUNT + ":user/" + userName;
try (Connection admin = connect("admin", adminToken()); Statement statement = admin.createStatement()) {
try (Connection admin = admin(); Statement statement = admin.createStatement()) {
statement.execute("CREATE ROLE user_role WITH LOGIN");
statement.execute("AWS IAM GRANT user_role TO '" + userArn + "'");
try (Connection app = connect("user_role", token("DbConnect", user.accessKeyId(), user.secretAccessKey(),
Instant.now(), 900, null));
try (Connection app = cluster.connect("user_role", cluster.token("DbConnect", user.accessKeyId(),
user.secretAccessKey(), Instant.now(), 900, null));
Statement query = app.createStatement();
ResultSet row = query.executeQuery("SELECT current_user, sys.iam_session_user()")) {
assertTrue(row.next());
@@ -251,7 +232,7 @@ class DsqlDataPlaneIntegrationTest {
@Test
void nothingASessionRunsChangesWhoItIs() throws Exception {
try (Connection connection = connect("admin", adminToken()); Statement statement = connection.createStatement()) {
try (Connection connection = admin(); Statement statement = connection.createStatement()) {
statement.execute("CREATE FUNCTION spoof() RETURNS text LANGUAGE sql AS"
+ " $$ SELECT set_config('dsql.iam_session_user', 'spoofed', false) $$");
statement.execute("SELECT spoof()");
@@ -268,7 +249,7 @@ class DsqlDataPlaneIntegrationTest {
@Test
void aRoleDroppedInsideAFunctionTakesItsMappingsWithIt() throws Exception {
try (Connection connection = connect("admin", adminToken()); Statement statement = connection.createStatement()) {
try (Connection connection = admin(); Statement statement = connection.createStatement()) {
statement.execute("CREATE ROLE dropped_role");
statement.execute("AWS IAM GRANT dropped_role TO '" + ROLE_ARN + "'");
statement.execute("CREATE FUNCTION drop_it() RETURNS void LANGUAGE sql AS 'DROP ROLE dropped_role'");
@@ -301,12 +282,12 @@ class DsqlDataPlaneIntegrationTest {
*/
@Test
void pipelinedStatementsShowTheirOwnCommandTags() throws Exception {
try (Connection admin = connect("admin", adminToken()); Statement statement = admin.createStatement()) {
try (Connection admin = admin(); Statement statement = admin.createStatement()) {
statement.execute("CREATE ROLE pipelined_role");
}
String grant = "AWS IAM GRANT pipelined_role TO '" + ROLE_ARN + "'";
String revoke = "AWS IAM REVOKE pipelined_role FROM '" + ROLE_ARN + "'";
try (WireClient client = new WireClient("admin", adminToken())) {
try (DsqlWireClient client = cluster.wireClient("admin", cluster.adminToken())) {
client.send(query("SELECT 1"), query(grant), query(revoke + "; SELECT 2"));
assertEquals(List.of("SELECT 1"), client.untilReady());
assertEquals(List.of("AWS IAM GRANT"), client.untilReady());
@@ -318,19 +299,41 @@ class DsqlDataPlaneIntegrationTest {
assertEquals(List.of("ERROR 42P05"), client.untilReady());
assertEquals(List.of("SELECT 1"), client.untilReady());
client.send(close("s1"), parse("s1", grant), bind("s1"), execute(), parse("s2", revoke), bind("s2"),
execute(), sync(), query("SELECT 3"));
assertEquals(List.of("AWS IAM GRANT", "AWS IAM REVOKE"), client.untilReady());
// Each grant is DDL, of which DSQL runs one per transaction, so each has a Sync of its own.
client.send(close("s1"), parse("s1", grant), bind("s1"), execute(), sync(), parse("s2", revoke),
bind("s2"), execute(), sync(), query("SELECT 3"));
assertEquals(List.of("AWS IAM GRANT"), client.untilReady());
assertEquals(List.of("AWS IAM REVOKE"), client.untilReady());
assertEquals(List.of("SELECT 1"), client.untilReady());
}
try (Connection admin = connect("admin", adminToken()); Statement statement = admin.createStatement()) {
try (Connection admin = admin(); Statement statement = admin.createStatement()) {
statement.execute("DROP ROLE pipelined_role");
}
}
/** Floci's own index function runs one index statement and nothing else, whoever calls it. */
@Test
void theAsyncIndexFunctionRunsNothingButAnIndex() throws Exception {
try (Connection connection = admin(); Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE direct_call (id int PRIMARY KEY)");
statement.execute("INSERT INTO direct_call VALUES (1)");
for (String sql : List.of("TRUNCATE direct_call",
"CREATE INDEX x ON direct_call (id); TRUNCATE direct_call")) {
PSQLException refused = assertThrows(PSQLException.class, () -> statement.execute(
"SELECT * FROM sys.create_index_async('" + sql + "', 'x', 'direct_call')"), sql);
assertEquals("42883", refused.getSQLState(), sql);
}
try (ResultSet row = statement.executeQuery("SELECT count(*) FROM direct_call")) {
assertTrue(row.next());
assertEquals(1, row.getInt(1));
}
statement.execute("DROP TABLE direct_call");
}
}
@Test
void dsqlsParametersAreReservedAsDsqlReservesThem() throws Exception {
try (Connection connection = connect("admin", adminToken()); Statement statement = connection.createStatement()) {
try (Connection connection = admin(); Statement statement = connection.createStatement()) {
for (String sql : List.of("SET dsql.x = 1", "RESET dsql.x", "SELECT set_config('dsql.x', '1', false)",
"ALTER ROLE admin SET dsql.x = 1",
"CREATE FUNCTION reserved() RETURNS int LANGUAGE sql SET dsql.x = 1 AS 'SELECT 1'")) {
@@ -357,30 +360,30 @@ class DsqlDataPlaneIntegrationTest {
@Test
void aStartupSettingIsReadAsDsqlReadsIt() throws Exception {
for (String name : List.of("dsql.iam_session_user", "myapp.foo")) {
Properties custom = properties("admin", adminToken());
Properties custom = cluster.properties("admin", cluster.adminToken());
custom.setProperty("options", "-c " + name + "=x");
PSQLException refused = assertThrows(PSQLException.class, () ->
DriverManager.getConnection(url(), custom).close());
DriverManager.getConnection(cluster.url(), custom).close());
assertEquals("42704", refused.getSQLState());
assertEquals("unrecognized configuration parameter \"" + name + "\"",
refused.getServerErrorMessage().getMessage());
assertTrue(refused.getServerErrorMessage().getDetail().startsWith("Session Id: "));
}
Properties unknown = properties("admin", adminToken());
Properties unknown = cluster.properties("admin", cluster.adminToken());
unknown.setProperty("options", "-c nosuch_parameter=1");
PSQLException fromTheDatabase = assertThrows(PSQLException.class, () ->
DriverManager.getConnection(url(), unknown).close());
DriverManager.getConnection(cluster.url(), unknown).close());
assertEquals("42704", fromTheDatabase.getSQLState());
assertEquals("unrecognized configuration parameter \"nosuch_parameter\"",
fromTheDatabase.getServerErrorMessage().getMessage());
assertTrue(fromTheDatabase.getServerErrorMessage().getDetail().startsWith("Session Id: "));
assertEquals(null, fromTheDatabase.getServerErrorMessage().getFile());
Properties ignored = properties("admin", adminToken());
Properties ignored = cluster.properties("admin", cluster.adminToken());
ignored.setProperty("options", "--dsql.iam_session_user=spoofed --search_path=elsewhere"
+ " -c search_path=first -c search_path=second");
try (Connection connection = DriverManager.getConnection(url(), ignored);
try (Connection connection = DriverManager.getConnection(cluster.url(), ignored);
Statement statement = connection.createStatement();
ResultSet row = statement.executeQuery("SELECT current_setting('search_path'), sys.iam_session_user()")) {
assertTrue(row.next());
@@ -389,6 +392,213 @@ class DsqlDataPlaneIntegrationTest {
}
}
@Test
void theDatabaseSpeaksDsqlsDialect() throws Exception {
try (Connection connection = admin(); Statement statement = connection.createStatement()) {
statement.execute("CREATE SCHEMA dialect");
statement.execute("CREATE TABLE dialect.t (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), n int)");
String jobId;
try (ResultSet job = statement.executeQuery("CREATE INDEX ASYNC t_n ON dialect.t (n)")) {
assertTrue(job.next());
jobId = job.getString("job_id");
}
assertEquals(26, jobId.length());
try (ResultSet waited = statement.executeQuery("CALL sys.wait_for_job('" + jobId + "')")) {
assertTrue(waited.next());
assertTrue(waited.getBoolean(1));
}
SQLException plainIndex = assertThrows(SQLException.class, () ->
statement.execute("CREATE INDEX t_plain ON dialect.t (n)"));
assertEquals("0A000", plainIndex.getSQLState());
assertEquals("unsupported mode. please use CREATE INDEX ASYNC.",
((PSQLException) plainIndex).getServerErrorMessage().getMessage());
assertEquals(null, ((PSQLException) plainIndex).getServerErrorMessage().getWhere());
SQLException truncate = assertThrows(SQLException.class, () -> statement.execute("TRUNCATE dialect.t"));
assertEquals("0A000", truncate.getSQLState());
assertEquals("unsupported statement: Truncate",
((PSQLException) truncate).getServerErrorMessage().getMessage());
connection.setAutoCommit(false);
statement.execute("CREATE TABLE dialect.a (id int PRIMARY KEY)");
SQLException twoDdl = assertThrows(SQLException.class, () ->
statement.execute("CREATE TABLE dialect.b (id int PRIMARY KEY)"));
assertEquals("multiple ddl statements not supported in a transaction",
((PSQLException) twoDdl).getServerErrorMessage().getMessage());
connection.rollback();
SQLException rowLimit = assertThrows(SQLException.class, () ->
statement.execute("INSERT INTO dialect.t (n) SELECT g FROM generate_series(1, 3001) g"));
assertEquals("54000", rowLimit.getSQLState());
assertEquals("transaction row limit exceeded",
((PSQLException) rowLimit).getServerErrorMessage().getMessage());
connection.rollback();
}
}
/**
* Measured on DSQL (2026-10-21): table copies refused, every key's type checked, role statements
* counted as DDL.
*/
@Test
void tableCopiesKeysAndRolesAreReadAsDsqlReadsThem() throws Exception {
try (Connection connection = admin(); Statement statement = connection.createStatement()) {
for (String sql : List.of("CREATE TABLE copied AS SELECT 1 AS n", "SELECT 1 AS n INTO copied",
"CREATE MATERIALIZED VIEW copied AS SELECT 1 AS n")) {
PSQLException refused = assertThrows(PSQLException.class, () -> statement.execute(sql), sql);
assertEquals("unsupported statement: CreateTableAs", refused.getServerErrorMessage().getMessage(), sql);
}
statement.execute("CREATE TABLE keyed (id int PRIMARY KEY, j jsonb)");
PSQLException expression = assertThrows(PSQLException.class, () ->
statement.executeQuery("CREATE INDEX ASYNC keyed_j ON keyed ((j -> 'a'))"));
assertEquals("datatype jsonb is not supported in a key", expression.getServerErrorMessage().getMessage());
statement.execute("CREATE DOMAIN jdomain AS jsonb");
PSQLException domain = assertThrows(PSQLException.class, () ->
statement.execute("CREATE TABLE domain_keyed (k jdomain PRIMARY KEY)"));
assertEquals("datatype jdomain is not supported in a key", domain.getServerErrorMessage().getMessage());
statement.execute("CREATE ROLE ddl_role");
connection.setAutoCommit(false);
statement.execute("ALTER ROLE ddl_role WITH LOGIN");
PSQLException withDml = assertThrows(PSQLException.class, () ->
statement.execute("INSERT INTO keyed (id) VALUES (1)"));
assertEquals("ddl and dml are not supported in the same transaction",
withDml.getServerErrorMessage().getMessage());
assertEquals("ddl count: 1, dml count: 1", withDml.getServerErrorMessage().getDetail());
connection.rollback();
statement.execute("GRANT ddl_role TO admin");
PSQLException twoDdl = assertThrows(PSQLException.class, () ->
statement.execute("CREATE TABLE keyed_too (id int PRIMARY KEY)"));
assertEquals("multiple ddl statements not supported in a transaction",
twoDdl.getServerErrorMessage().getMessage());
connection.rollback();
connection.setAutoCommit(true);
statement.execute("DROP ROLE ddl_role");
statement.execute("DROP TABLE keyed");
statement.execute("DROP DOMAIN jdomain");
}
}
/**
* The limits hold whatever a client does to its own table or to its session's settings: DSQL
* has neither the triggers nor the settings Floci keeps them with.
*/
@Test
void theLimitsHoldWhateverTheClientChanges() throws Exception {
try (Connection connection = admin(); Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE guarded (id int PRIMARY KEY)");
statement.execute("ALTER TABLE guarded DISABLE TRIGGER USER");
statement.execute("ALTER TABLE guarded DISABLE TRIGGER ALL");
PSQLException dropped = assertThrows(PSQLException.class, () ->
statement.execute("DROP TRIGGER dsql_rows_inserted ON guarded"));
assertEquals("42704", dropped.getSQLState());
assertEquals("trigger \"dsql_rows_inserted\" for table \"guarded\" does not exist",
dropped.getServerErrorMessage().getMessage());
assertEquals(null, dropped.getServerErrorMessage().getWhere());
statement.execute("SELECT set_config(chr(100) || 'sql.async_index', 'on', false)");
PSQLException plainIndex = assertThrows(PSQLException.class, () ->
statement.execute("CREATE INDEX guarded_plain ON guarded (id)"));
assertEquals("unsupported mode. please use CREATE INDEX ASYNC.",
plainIndex.getServerErrorMessage().getMessage());
connection.setAutoCommit(false);
statement.execute("SELECT set_config(chr(100) || 'sql.row_count', '-100000', true)");
PSQLException rowLimit = assertThrows(PSQLException.class, () ->
statement.execute("INSERT INTO guarded SELECT g FROM generate_series(1, 3001) g"));
assertEquals("54000", rowLimit.getSQLState());
connection.rollback();
statement.execute("SELECT set_config(chr(100) || 'sql.internal', 'on', true)");
PSQLException trigger = assertThrows(PSQLException.class, () -> statement.execute(
"CREATE TRIGGER mine AFTER INSERT ON guarded FOR EACH STATEMENT EXECUTE FUNCTION sys._count_dml()"));
assertEquals("CREATE TRIGGER not supported", trigger.getServerErrorMessage().getMessage());
connection.rollback();
}
}
@Test
void anUnnamedUniqueIndexOverDuplicatesFailsItsJob() throws Exception {
try (Connection connection = admin(); Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE dupes (id int PRIMARY KEY, n int)");
statement.execute("INSERT INTO dupes VALUES (1, 7), (2, 7)");
String jobId;
try (ResultSet job = statement.executeQuery("CREATE UNIQUE INDEX ASYNC ON dupes (n)")) {
assertTrue(job.next());
jobId = job.getString("job_id");
}
try (ResultSet job = statement.executeQuery(
"SELECT status, details, object_name FROM sys.jobs WHERE job_id = '" + jobId + "'")) {
assertTrue(job.next());
assertEquals("failed", job.getString(1));
assertEquals("found duplicate key(s) while validating index uniqueness", job.getString(2));
assertEquals("public.dupes_n_idx", job.getString(3));
}
PSQLException cache = assertThrows(PSQLException.class, () ->
statement.execute("CREATE SEQUENCE huge CACHE 99999999999999999999"));
assertEquals("22003", cache.getSQLState());
assertEquals("value \"99999999999999999999\" is out of range for type bigint",
cache.getServerErrorMessage().getMessage());
}
}
@Test
void aForeignKeyIsEnforcedAndItsCascadeCountsTowardTheRowLimit() throws Exception {
try (Connection connection = admin(); Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE fk_parent (id int PRIMARY KEY)");
statement.execute("CREATE TABLE fk_child (id int PRIMARY KEY,"
+ " parent_id int REFERENCES fk_parent (id) ON DELETE CASCADE)");
PSQLException orphan = assertThrows(PSQLException.class, () ->
statement.execute("INSERT INTO fk_child VALUES (1, 999)"));
assertEquals("23503", orphan.getSQLState());
assertEquals(null, orphan.getServerErrorMessage().getFile());
statement.execute("INSERT INTO fk_parent VALUES (1)");
statement.execute("INSERT INTO fk_child SELECT g, 1 FROM generate_series(1, 1500) g");
statement.execute("INSERT INTO fk_child SELECT g, 1 FROM generate_series(1501, 3000) g");
PSQLException tooMany = assertThrows(PSQLException.class, () ->
statement.execute("DELETE FROM fk_parent WHERE id = 1"));
assertEquals("54000", tooMany.getSQLState());
assertEquals("transaction row limit exceeded", tooMany.getServerErrorMessage().getMessage());
assertEquals(null, tooMany.getServerErrorMessage().getWhere());
assertEquals(null, tooMany.getServerErrorMessage().getFile());
}
}
@Test
void aWriteConflictIsDsqlsOc000() throws Exception {
try (Connection setup = admin(); Statement statement = setup.createStatement()) {
statement.execute("CREATE TABLE conflict (id int PRIMARY KEY, n int)");
statement.execute("INSERT INTO conflict VALUES (1, 0)");
}
try (Connection first = admin(); Connection second = admin()) {
first.setAutoCommit(false);
second.setAutoCommit(false);
try (Statement firstStatement = first.createStatement(); Statement secondStatement = second.createStatement()) {
secondStatement.executeQuery("SELECT n FROM conflict WHERE id = 1").close();
firstStatement.executeUpdate("UPDATE conflict SET n = 1 WHERE id = 1");
CompletableFuture<SQLException> blocked = CompletableFuture.supplyAsync(() -> {
try {
secondStatement.executeUpdate("UPDATE conflict SET n = 2 WHERE id = 1");
return null;
} catch (SQLException e) {
return e;
}
});
first.commit();
SQLException conflict = blocked.get(30, TimeUnit.SECONDS);
assertEquals("40001", conflict.getSQLState());
assertEquals("change conflicts with another transaction (OC000)",
((PSQLException) conflict).getServerErrorMessage().getMessage());
second.rollback();
}
}
}
/**
* A long-term key signs in to its own account's clusters and to no other account's, whichever
* account is Floci's default: the cluster here is not in the default one.
@@ -398,97 +608,18 @@ class DsqlDataPlaneIntegrationTest {
EnforcementFixtures.UserCredentials own = accessKey(ACCOUNT);
EnforcementFixtures.UserCredentials other = accessKey("000000000000");
connect("admin", token("DbConnectAdmin", own.accessKeyId(), own.secretAccessKey(), Instant.now(), 900,
null)).close();
PSQLException foreign = assertThrows(PSQLException.class, () -> connect("admin", token("DbConnectAdmin",
other.accessKeyId(), other.secretAccessKey(), Instant.now(), 900, null)).close());
cluster.connect("admin", cluster.token("DbConnectAdmin", own.accessKeyId(), own.secretAccessKey(),
Instant.now(), 900, null)).close();
PSQLException foreign = assertThrows(PSQLException.class, () -> cluster.connect("admin",
cluster.token("DbConnectAdmin", other.accessKeyId(), other.secretAccessKey(), Instant.now(), 900,
null)).close());
assertEquals("08006", foreign.getSQLState());
assertEquals("unable to accept connection, access denied", foreign.getServerErrorMessage().getMessage());
}
/** A client that writes the wire protocol itself, to send what JDBC sends one message at a time. */
private final class WireClient implements AutoCloseable {
private final Socket socket;
private final InputStream in;
private final OutputStream out;
WireClient(String user, String password) throws Exception {
Socket plain = new Socket("127.0.0.1", endpoint.port());
plain.getOutputStream().write(PostgresWire.int32(8));
plain.getOutputStream().write(PostgresWire.int32(PostgresWire.SSL_REQUEST));
assertEquals('S', plain.getInputStream().read());
socket = new NonValidatingFactory(null).createSocket(plain, host, endpoint.port(), true);
in = new BufferedInputStream(socket.getInputStream());
out = socket.getOutputStream();
Map<String, String> startup = new LinkedHashMap<>();
startup.put("user", user);
startup.put("database", "postgres");
out.write(PostgresWire.startupMessage(startup));
assertEquals('R', PostgresWire.read(in, Integer.MAX_VALUE, "message").type());
send(message('p', PostgresWire.cStringBytes(password)));
untilReady();
}
void send(byte[]... messages) throws IOException {
for (byte[] message : messages) {
out.write(message);
}
out.flush();
}
/** The command tags, and the SQLSTATE of an error, up to the next ReadyForQuery. */
List<String> untilReady() throws IOException {
List<String> answers = new ArrayList<>();
while (true) {
PostgresWire.Message message = PostgresWire.read(in, Integer.MAX_VALUE, "message");
switch (message.type()) {
case 'C' -> answers.add(PostgresWire.cString(message.body(), 0).value());
case 'E' -> answers.add("ERROR " + PostgresWire.parseFields(message.body(), 0).get('C'));
case 'Z' -> {
return answers;
}
default -> {
}
}
}
}
@Override
public void close() throws IOException {
socket.close();
}
}
private static byte[] query(String sql) throws IOException {
return message('Q', PostgresWire.cStringBytes(sql));
}
private static byte[] parse(String statement, String sql) throws IOException {
return message('P', PostgresWire.cStringBytes(statement), PostgresWire.cStringBytes(sql), new byte[2]);
}
/** The unnamed portal for {@code statement}, with no parameters and text results. */
private static byte[] bind(String statement) throws IOException {
return message('B', PostgresWire.cStringBytes(""), PostgresWire.cStringBytes(statement), new byte[6]);
}
private static byte[] execute() throws IOException {
return message('E', PostgresWire.cStringBytes(""), PostgresWire.int32(0));
}
private static byte[] close(String statement) throws IOException {
return message('C', new byte[] {'S'}, PostgresWire.cStringBytes(statement));
}
private static byte[] sync() throws IOException {
return message('S');
}
private static byte[] message(int type, byte[]... parts) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
PostgresWire.write(bytes, type, parts);
return bytes.toByteArray();
/** A connection signed in as {@code admin}. */
private Connection admin() throws Exception {
return cluster.connect("admin", cluster.adminToken());
}
/** A new IAM user's access key in {@code account}, removed with the user after the test. */
@@ -496,35 +627,4 @@ class DsqlDataPlaneIntegrationTest {
return EnforcementFixtures.createUser(cleanup, httpPort, EnforcementFixtures.auth(account, "iam"),
"dsql-" + System.nanoTime());
}
private Connection connect(String user, String password) throws SQLException {
return DriverManager.getConnection(url(), properties(user, password));
}
private String url() {
return "jdbc:postgresql://127.0.0.1:" + endpoint.port() + "/postgres";
}
private static Properties properties(String user, String password) {
Properties properties = new Properties();
properties.setProperty("user", user);
properties.setProperty("password", password);
properties.setProperty("sslmode", "require");
properties.setProperty("sslfactory", "org.postgresql.ssl.NonValidatingFactory");
return properties;
}
private String adminToken() throws Exception {
return token("DbConnectAdmin", "test", "test", Instant.now(), 900, null);
}
private String token(String action, String accessKeyId, String secret, Instant at, int expires,
String sessionToken) throws Exception {
return SigV4TokenTestHelper.createDsqlToken(host, REGION, action, accessKeyId, secret, at, expires,
sessionToken);
}
private RequestSpecification dsql() {
return given().port(httpPort).header("Authorization", AUTH).contentType("application/json");
}
}
@@ -0,0 +1,106 @@
package io.github.hectorvent.floci.services.dsql;
import io.github.hectorvent.floci.core.common.PostgresWire;
import org.postgresql.ssl.NonValidatingFactory;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* A client of a DSQL endpoint that writes the wire protocol itself, to send what JDBC sends one
* message at a time: several queries, or several Syncs, before reading any answer.
*/
public final class DsqlWireClient implements AutoCloseable {
private final Socket socket;
private final InputStream in;
private final OutputStream out;
/** Signs in to the endpoint on {@code port} as {@code user}, naming {@code host} as the server. */
public DsqlWireClient(int port, String host, String user, String password) throws Exception {
Socket plain = new Socket("127.0.0.1", port);
plain.getOutputStream().write(PostgresWire.int32(8));
plain.getOutputStream().write(PostgresWire.int32(PostgresWire.SSL_REQUEST));
assertEquals('S', plain.getInputStream().read());
socket = new NonValidatingFactory(null).createSocket(plain, host, port, true);
in = new BufferedInputStream(socket.getInputStream());
out = socket.getOutputStream();
Map<String, String> startup = new LinkedHashMap<>();
startup.put("user", user);
startup.put("database", "postgres");
out.write(PostgresWire.startupMessage(startup));
assertEquals('R', PostgresWire.read(in, Integer.MAX_VALUE, "message").type());
send(message('p', PostgresWire.cStringBytes(password)));
untilReady();
}
public void send(byte[]... messages) throws IOException {
for (byte[] message : messages) {
out.write(message);
}
out.flush();
}
/** The command tags, and the SQLSTATE of an error, up to the next ReadyForQuery. */
public List<String> untilReady() throws IOException {
List<String> answers = new ArrayList<>();
while (true) {
PostgresWire.Message message = PostgresWire.read(in, Integer.MAX_VALUE, "message");
switch (message.type()) {
case 'C' -> answers.add(PostgresWire.cString(message.body(), 0).value());
case 'E' -> answers.add("ERROR " + PostgresWire.parseFields(message.body(), 0).get('C'));
case 'Z' -> {
return answers;
}
default -> {
}
}
}
}
@Override
public void close() throws IOException {
socket.close();
}
public static byte[] query(String sql) throws IOException {
return message('Q', PostgresWire.cStringBytes(sql));
}
public static byte[] parse(String statement, String sql) throws IOException {
return message('P', PostgresWire.cStringBytes(statement), PostgresWire.cStringBytes(sql), new byte[2]);
}
/** The unnamed portal for {@code statement}, with no parameters and text results. */
public static byte[] bind(String statement) throws IOException {
return message('B', PostgresWire.cStringBytes(""), PostgresWire.cStringBytes(statement), new byte[6]);
}
public static byte[] execute() throws IOException {
return message('E', PostgresWire.cStringBytes(""), PostgresWire.int32(0));
}
public static byte[] close(String statement) throws IOException {
return message('C', new byte[] {'S'}, PostgresWire.cStringBytes(statement));
}
public static byte[] sync() throws IOException {
return message('S');
}
private static byte[] message(int type, byte[]... parts) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
PostgresWire.write(bytes, type, parts);
return bytes.toByteArray();
}
}
@@ -114,6 +114,30 @@ class DsqlSessionTest {
assertFalse(fields.containsKey('R'));
}
@Test
void aSerializationFailureIsDsqlsOc000() {
byte[] postgres = error(Map.of('C', "40001", 'M', "could not serialize access due to concurrent update",
'F', "heapam.c", 'L', "1", 'R', "heap_update"));
Map<Character, String> fields = PostgresWire.parseFields(DsqlSession.inDsqlWords((byte) 'E', postgres), 0);
assertEquals("40001", fields.get('C'));
assertEquals("change conflicts with another transaction (OC000)", fields.get('M'));
assertFalse(fields.containsKey('F'));
}
@Test
void aCascadePastTheRowLimitKeepsTheStatementItRanAndDropsSys() {
byte[] postgres = error(Map.of('C', "54000", 'M', "transaction row limit exceeded",
'W', "PL/pgSQL function sys._count_dml() line 14 at RAISE\n"
+ "SQL statement \"DELETE FROM ONLY \"fk3\".\"c_cascade\" WHERE $1 OPERATOR(pg_catalog.=) \"pid\"\""));
Map<Character, String> fields = PostgresWire.parseFields(DsqlSession.inDsqlWords((byte) 'E', postgres), 0);
assertEquals("SQL statement \"DELETE FROM ONLY \"fk3\".\"c_cascade\" WHERE $1 OPERATOR(pg_catalog.=) \"pid\"\"",
fields.get('W'));
}
private static byte[] error(Map<Character, String> fields) {
Map<Character, String> ordered = new LinkedHashMap<>();
ordered.put('S', fields.getOrDefault('S', "ERROR"));
@@ -12,6 +12,17 @@ import static org.junit.jupiter.api.Assertions.assertNull;
class DsqlStatementsTest {
@Test
void createIndexAsyncBecomesTheJobItAnswers() {
List<DsqlStatements.Statement> statements =
DsqlStatements.rewrite("CREATE UNIQUE INDEX ASYNC IF NOT EXISTS t_u ON probe.t (n) WHERE n > 0");
assertEquals(1, statements.size());
assertEquals("SELECT job_id FROM sys.create_index_async($dsql$CREATE UNIQUE INDEX IF NOT EXISTS t_u"
+ " ON probe.t (n) WHERE n > 0$dsql$, 't_u', 'probe.t')", statements.get(0).sql());
assertNull(statements.get(0).commandTag());
}
@Test
void awsIamGrantAndRevokeBecomeCallsWithDsqlsCommandTags() {
List<DsqlStatements.Statement> statements = DsqlStatements.rewrite(
@@ -26,6 +37,48 @@ class DsqlStatementsTest {
assertEquals("AWS IAM REVOKE", statements.get(1).commandTag());
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"TRUNCATE t|0A000|unsupported statement: Truncate",
"LISTEN chan|0A000|unsupported statement: Listen",
"NOTIFY chan|0A000|unsupported statement: Notify",
"VACUUM t|0A000|unsupported VACUUM statement",
"DO $$ BEGIN END $$|0A000|DO with language plpgsql not supported",
"CREATE DATABASE x|0A000|CREATE DATABASE not supported",
"CREATE TABLESPACE ts LOCATION '/tmp'|0A000|unsupported statement: CreateTableSpace",
"CREATE EXTENSION pgcrypto|0A000|unsupported statement: CreateExtension",
"GRANT CONNECT ON DATABASE postgres TO r|0A000|unsupported object type in GRANT",
"CREATE SEQUENCE s|0A000|CREATE SEQUENCE is not supported without an explicit cache size. please define CACHE"
+ " greater than or equal to 65536 or equal to 1",
"CREATE SEQUENCE s2 CACHE 100|22023|CACHE (100) must be greater than or equal to 65536 or equal to 1",
"ALTER TABLE t ADD COLUMN c int DEFAULT 1|0A000|ALTER TABLE ADD COLUMN with constraint not supported",
"ALTER TABLE t ADD CONSTRAINT ck CHECK (n > 0)|0A000|unsupported ALTER TABLE ADD CONSTRAINT statement",
"SELECT * FROM t FOR SHARE|0A000|locking clauses other than FOR UPDATE/FOR KEY SHARE are not supported",
"SELECT * FROM t FOR NO KEY UPDATE|0A000|locking clauses other than FOR UPDATE/FOR KEY SHARE are not supported",
"SELECT pg_advisory_lock(1)|0A000|function pg_advisory_lock not supported",
"SELECT pg_try_advisory_xact_lock(1)|0A000|function pg_try_advisory_xact_lock not supported",
"SELECT \"pg_advisory_lock\"(1)|0A000|function pg_advisory_lock not supported",
"CREATE SEQUENCE s9 /* CACHE 65536 */ CACHE 2|22023|CACHE (2) must be greater than or equal to 65536 or equal to 1",
"SET \"default_transaction_isolation\" TO 'read committed'|0A000|setting configuration parameter"
+ " \"default_transaction_isolation\" not supported",
"SELECT set_config('default_transaction_isolation', 'read committed', false)|0A000|setting configuration"
+ " parameter \"default_transaction_isolation\" not supported",
"SELECT set_config('transaction_isolation', 'read committed', false)|0A000|setting configuration parameter"
+ " \"transaction_isolation\" not supported",
"ALTER ROLE admin SET default_transaction_isolation = 'read committed'|0A000|setting configuration parameter"
+ " \"default_transaction_isolation\" not supported",
"ALTER DATABASE postgres SET search_path = public|0A000|unsupported statement: AlterDatabaseSet",
"ALTER DATABASE postgres RESET ALL|0A000|unsupported statement: AlterDatabaseSet",
"SET TRANSACTION ISOLATION LEVEL SERIALIZABLE|0A000|Unsupported isolation level: SERIALIZABLE",
"BEGIN ISOLATION LEVEL READ COMMITTED|0A000|Unsupported isolation level: READ COMMITTED",
"SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL SERIALIZABLE|0A000|Unsupported isolation level: SERIALIZABLE",
"SET default_transaction_isolation = 'read committed'|0A000|setting configuration parameter"
+ " \"default_transaction_isolation\" not supported",
})
void whatDsqlRefusesRaisesItsOwnError(String sql, String state, String message) {
assertEquals(DsqlStatements.reject(state, message, null), DsqlStatements.rewrite(sql).get(0).sql());
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"SET dsql.x = 1|dsql.x",
@@ -69,21 +122,69 @@ class DsqlStatementsTest {
assertEquals("DROP ROLE", DsqlStatements.rewrite("DROP GROUP g").get(0).commandTag());
}
@Test
void aCacheTooLargeForABigintIsLeftToThePostgresqlError() {
String sql = "CREATE SEQUENCE huge CACHE 99999999999999999999";
assertEquals(sql, DsqlStatements.rewrite(sql).get(0).sql());
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"SELECT * FROM t FOR UPDATE SKIP LOCKED",
"SELECT * FROM t FOR KEY SHARE",
"CREATE SEQUENCE s1 CACHE 1",
"CREATE SEQUENCE s3 CACHE 65536",
"ALTER TABLE t ADD COLUMN d int",
"ALTER TABLE t DROP COLUMN d",
"SET TRANSACTION ISOLATION LEVEL REPEATABLE READ",
"SET search_path TO probe",
"DROP ROLE CURRENT_USER",
"DROP ROLE IF EXISTS",
"DROP ROLE a b",
"DROP ROLE a,",
"SELECT 'AWS IAM GRANT a TO b' AS text",
"SELECT 'TRUNCATE t; FOR SHARE' AS text",
"INSERT INTO t (note) VALUES ($x$ pg_advisory_lock( $x$)",
"CREATE INDEX ON t (n)",
"TRUNCATE t",
"CREATE SEQUENCE \"cache 2\" CACHE 65536",
})
void whatIsNotDsqlsOwnSyntaxPassesUnchanged(String sql) {
void whatDsqlAcceptsPassesUnchanged(String sql) {
assertEquals(sql, DsqlStatements.rewrite(sql).get(0).sql());
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"CREATE ROLE r1|CREATE ROLE",
"create user u1 WITH LOGIN|CREATE ROLE",
"ALTER ROLE r1 SET search_path = public|ALTER ROLE",
"ALTER GROUP g ADD USER u1|ALTER ROLE",
"GRANT r1 TO u1|GRANT ROLE",
"REVOKE r1 FROM u1|REVOKE ROLE",
})
void aStatementOnRolesIsCountedAsDdlUnderPostgresqlsTag(String sql, String tag) {
DsqlStatements.Statement statement = DsqlStatements.rewrite(sql).get(0);
assertEquals("CALL sys.run_role_ddl($dsql$" + sql + "$dsql$)", statement.sql());
assertEquals(tag, statement.commandTag());
}
@Test
void aGrantOnAnObjectOrAUserMappingIsNoRoleStatement() {
for (String sql : List.of("GRANT SELECT ON t TO r1", "REVOKE ALL ON t FROM r1",
"CREATE USER MAPPING FOR r1 SERVER s")) {
assertEquals(sql, DsqlStatements.rewrite(sql).get(0).sql(), sql);
}
}
@Test
void aLineCommentEndsAtACarriageReturnAsInPostgresql() {
List<DsqlStatements.Statement> statements = DsqlStatements.rewrite("SELECT 1 --\r; TRUNCATE t");
assertEquals(2, statements.size());
assertEquals(DsqlStatements.reject("0A000", "unsupported statement: Truncate", null), statements.get(1).sql());
}
@Test
void aQueryWithNothingToRewriteGoesToTheDatabaseExactlyAsSent() {
String query = "-- comment\nSELECT 1;\n/* two */ SELECT 'a;b';";
@@ -0,0 +1,352 @@
package io.github.hectorvent.floci.services.dsql.dataplane;
import com.github.dockerjava.api.DockerClient;
import io.github.hectorvent.floci.services.dsql.DsqlClusterFixture;
import io.github.hectorvent.floci.services.dsql.DsqlDatabasesProfile;
import io.github.hectorvent.floci.services.dsql.DsqlWireClient;
import io.github.hectorvent.floci.testing.MutableClock;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.postgresql.util.PSQLException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import static io.github.hectorvent.floci.services.dsql.DsqlWireClient.query;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A transaction lives 300 seconds on DSQL, ended as DSQL ends it (measured, eu-west-1, 2026-10-21):
* the client's next message after the limit, a ROLLBACK included, gets the age error and the
* connection closes; a transaction idle past the limit and 15 seconds more is ended the same way
* unasked; a statement that runs across the limit ends in the age error and keeps nothing, inside a
* transaction block or not; and a failed transaction idle as long is closed. The test moves the
* endpoint's clock instead of waiting, and makes a statement run long by having it wait for a row
* another connection holds.
*/
@QuarkusTest
@TestProfile(DsqlDatabasesProfile.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@Tag("docker")
class DsqlTransactionAgeIntegrationTest {
private static final Duration PAST_THE_LIMIT = Duration.ofSeconds(301);
private static final Duration PAST_THE_GRACE = Duration.ofSeconds(316);
@Inject
DockerClient dockerClient;
@Inject
DsqlEndpoint endpoint;
@Inject
MutableClock clock;
@ConfigProperty(name = "quarkus.http.test-port", defaultValue = "0")
int httpPort;
private DsqlClusterFixture cluster;
@BeforeAll
void createCluster() throws Exception {
cluster = new DsqlClusterFixture(httpPort, endpoint);
cluster.create(dockerClient);
try (Connection connection = connect("extended"); Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE aged (id int PRIMARY KEY, n int)");
statement.execute("INSERT INTO aged VALUES (1, 0)");
}
}
@AfterAll
void deleteCluster() {
cluster.delete();
}
@ParameterizedTest
@ValueSource(strings = {"extended", "simple"})
void aMessagePastTheLimitEndsTheTransactionAndTheConnection(String queryMode) throws Exception {
try (Connection connection = connect(queryMode); Statement statement = connection.createStatement()) {
connection.setAutoCommit(false);
statement.executeQuery("SELECT 1").close();
clock.advance(PAST_THE_LIMIT);
SQLException expired = assertThrows(SQLException.class, () -> statement.execute("ROLLBACK"));
assertMentions(expired, "transaction age limit of 300s exceeded");
assertFalse(connection.isValid(2));
}
}
@Test
void anIdleTransactionPastTheLimitAndItsGraceIsEndedUnasked() throws Exception {
try (Connection connection = connect("extended"); Statement statement = connection.createStatement()) {
connection.setAutoCommit(false);
statement.executeQuery("SELECT 1").close();
clock.advance(PAST_THE_GRACE);
endpoint.runDueChecks();
SQLException ended = assertThrows(SQLException.class, () -> statement.executeQuery("SELECT 2").close());
assertMentions(ended, "Current transaction age 316s exceeds 300s");
assertFalse(connection.isValid(2));
}
}
@Test
void aStatementRunningPastTheLimitEndsInTheAgeErrorAndFailsTheTransaction() throws Exception {
try (Connection connection = connect("extended"); Statement statement = connection.createStatement()) {
connection.setAutoCommit(false);
statement.executeQuery("SELECT 1").close();
Object outcome = pastTheLimit(() -> statement.executeQuery("SELECT n FROM aged WHERE id = 1 FOR UPDATE"));
assertMentions(assertInstanceOf(SQLException.class, outcome), "transaction age limit of 300s exceeded");
connection.rollback();
connection.setAutoCommit(true);
try (ResultSet row = statement.executeQuery("SELECT 3")) {
assertTrue(row.next());
assertEquals(3, row.getInt(1));
}
}
}
/** A statement past the limit fails outside a transaction block too, and what it wrote is not kept (measured). */
@Test
void aStatementPastTheLimitFailsOutsideATransactionToo() throws Exception {
try (Connection connection = connect("extended"); Statement statement = connection.createStatement()) {
Object write = pastTheLimit(() -> statement.executeUpdate("UPDATE aged SET n = 7 WHERE id = 1"));
assertMentions(assertInstanceOf(SQLException.class, write), "transaction age limit of 300s exceeded");
Object read = pastTheLimit(() -> statement.executeQuery("SELECT n FROM aged WHERE id = 1 FOR UPDATE"));
assertMentions(assertInstanceOf(SQLException.class, read), "transaction age limit of 300s exceeded");
}
assertEquals(0, aged());
}
/** A statement past the limit fails the rest of its query, a COMMIT in it included, and keeps nothing (measured). */
@Test
void aCommitAfterAStatementPastTheLimitKeepsNothing() throws Exception {
try (DsqlWireClient client = cluster.wireClient("admin", cluster.adminToken())) {
Object afterRead = pastTheLimit(() -> {
client.send(query("BEGIN; INSERT INTO aged VALUES (2, 8);"
+ " SELECT n FROM aged WHERE id = 1 FOR UPDATE; COMMIT"));
return client.untilReady();
});
assertTrue(((List<?>) afterRead).contains("ERROR 54000"), String.valueOf(afterRead));
// As on DSQL, the connection is left in the failed transaction.
client.send(query("ROLLBACK"));
client.untilReady();
Object afterWrite = pastTheLimit(() -> {
client.send(query("BEGIN; UPDATE aged SET n = 9 WHERE id = 1; COMMIT"));
return client.untilReady();
});
assertTrue(((List<?>) afterWrite).contains("ERROR 54000"), String.valueOf(afterWrite));
client.send(query("ROLLBACK"));
client.untilReady();
}
assertEquals(0, aged());
}
@Test
void aFailedTransactionIdlePastTheLimitAndItsGraceIsClosed() throws Exception {
try (Connection connection = connect("extended"); Statement statement = connection.createStatement()) {
connection.setAutoCommit(false);
statement.executeQuery("SELECT 1").close();
assertThrows(SQLException.class, () -> statement.executeQuery("SELECT 1 / 0").close());
clock.advance(PAST_THE_GRACE);
endpoint.runDueChecks();
SQLException closed = assertThrows(SQLException.class, () -> statement.execute("ROLLBACK"));
assertMentions(closed, "terminating connection due to idle-in-transaction timeout");
assertFalse(connection.isValid(2));
}
}
/**
* A client message after a failed transaction's first idle wait still lets it be closed once it
* idles as long again.
*/
@Test
void aFailedTransactionIsClosedOnceIdleAfterEachMessage() throws Exception {
try (Connection connection = connect("extended"); Statement statement = connection.createStatement()) {
connection.setAutoCommit(false);
statement.executeQuery("SELECT 1").close();
assertThrows(SQLException.class, () -> statement.executeQuery("SELECT 1 / 0").close());
clock.advance(Duration.ofSeconds(200));
assertThrows(SQLException.class, () -> statement.executeQuery("SELECT 2").close());
clock.advance(Duration.ofSeconds(200));
endpoint.runDueChecks();
clock.advance(Duration.ofSeconds(116));
endpoint.runDueChecks();
SQLException closed = assertThrows(SQLException.class, () -> statement.execute("ROLLBACK"));
assertMentions(closed, "terminating connection due to idle-in-transaction timeout");
}
}
/** A BEGIN queued behind a long statement starts when it can run, not when it was sent. */
@Test
void aBeginQueuedBehindALongStatementStartsWhenItRuns() throws Exception {
try (DsqlWireClient client = cluster.wireClient("admin", cluster.adminToken());
Connection holder = holdRow()) {
client.send(query("SELECT n FROM aged WHERE id = 1 FOR UPDATE"), query("BEGIN"), query("SELECT 1"));
awaitWaitingForTheRow();
clock.advance(Duration.ofSeconds(200));
holder.rollback();
assertEquals(List.of("SELECT 1"), client.untilReady());
assertEquals(List.of("BEGIN"), client.untilReady());
assertEquals(List.of("SELECT 1"), client.untilReady());
// Past the limit since the BEGIN was sent, within it since it ran.
clock.advance(Duration.ofSeconds(150));
client.send(query("SELECT 2"));
assertEquals(List.of("SELECT 1"), client.untilReady());
client.send(query("ROLLBACK"));
assertEquals(List.of("ROLLBACK"), client.untilReady());
}
}
/** A transaction a prepared BEGIN opens starts when the BEGIN runs, not when it was prepared. */
@Test
void aPreparedBeginStartsItsTransactionWhenItRuns() throws Exception {
try (Connection connection = connect("extended");
PreparedStatement begin = connection.prepareStatement("BEGIN");
Statement statement = connection.createStatement()) {
begin.execute();
statement.execute("ROLLBACK");
clock.advance(Duration.ofSeconds(250));
begin.execute();
clock.advance(Duration.ofSeconds(100));
try (ResultSet row = statement.executeQuery("SELECT 1")) {
assertTrue(row.next());
}
statement.execute("ROLLBACK");
}
}
/** A statement a test lets run past the age limit; what it returns, or throws, is its outcome. */
private interface Running {
Object run() throws Exception;
}
/**
* Runs {@code statement}, which waits for the row another connection holds, moves the clock
* past the age limit while it waits, lets the checks due then run, and lets the statement end:
* its result, or what it threw.
*/
private Object pastTheLimit(Running statement) throws Exception {
try (Connection holder = holdRow()) {
CompletableFuture<Object> outcome = CompletableFuture.supplyAsync(() -> {
try {
return statement.run();
} catch (Exception e) {
return e;
}
});
awaitWaitingForTheRow();
clock.advance(PAST_THE_LIMIT);
endpoint.runDueChecks();
// The statement is stopped at the limit; only then does the row go.
outcome.get(30, TimeUnit.SECONDS);
try {
holder.rollback();
} catch (SQLException ended) {
// The holder's own transaction is past the limit too, so its ROLLBACK ends its
// connection, which lets the row go all the same.
}
return outcome.get(30, TimeUnit.SECONDS);
}
}
/** A connection holding row 1 of {@code aged} until it rolls back. */
private Connection holdRow() throws Exception {
Connection holder = connect("extended");
holder.setAutoCommit(false);
try (Statement statement = holder.createStatement()) {
statement.executeQuery("SELECT n FROM aged WHERE id = 1 FOR UPDATE").close();
}
return holder;
}
/** Waits until a statement waits for a lock, read outside any transaction so each look is fresh. */
private void awaitWaitingForTheRow() {
await().atMost(Duration.ofSeconds(10)).until(() -> {
try (Connection connection = connect("extended"); Statement statement = connection.createStatement();
ResultSet row = statement.executeQuery(
"SELECT count(*) FROM pg_stat_activity WHERE wait_event_type = 'Lock'")) {
return row.next() && row.getInt(1) > 0;
}
});
}
/** The sum of {@code aged}'s counters, 0 while nothing a test wrote was kept. */
private int aged() throws Exception {
try (Connection connection = connect("extended"); Statement statement = connection.createStatement();
ResultSet row = statement.executeQuery("SELECT coalesce(sum(n), 0) FROM aged")) {
assertTrue(row.next());
return row.getInt(1);
}
}
/** Whether {@code error} or an exception chained to it says {@code text}. */
private static void assertMentions(SQLException error, String text) {
List<String> messages = messages(error);
assertTrue(messages.stream().anyMatch(message -> message.contains(text)), String.join(" | ", messages));
}
/**
* The messages and details of an exception and of every exception chained to it, each once:
* the driver can chain an exception back to one before it.
*/
private static List<String> messages(SQLException error) {
List<String> messages = new ArrayList<>();
Set<Throwable> seen = Collections.newSetFromMap(new IdentityHashMap<>());
for (Throwable each = error; each != null && seen.add(each); each = each.getCause() != null ? each.getCause()
: each instanceof SQLException sql ? sql.getNextException() : null) {
messages.add(String.valueOf(each.getMessage()));
if (each instanceof PSQLException psql && psql.getServerErrorMessage() != null) {
messages.add(psql.getSQLState() + " " + psql.getServerErrorMessage().getMessage() + " "
+ psql.getServerErrorMessage().getDetail());
}
}
return messages;
}
private Connection connect(String queryMode) throws Exception {
Properties properties = cluster.properties("admin", cluster.adminToken());
properties.setProperty("preferQueryMode", queryMode);
properties.setProperty("prepareThreshold", "1");
return DriverManager.getConnection(cluster.url(), properties);
}
}