Light, fluffy, and always free - The AWS Local Emulator alternative
feat(dsql): speak DSQL's dialect and keep its transaction limits (#6185)
Alessandro Lattao42fd85831110
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/DsqlCompatTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/DsqlCompatTest.javaindex a033758782..63160f5afe 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/DsqlCompatTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/DsqlCompatTest.java@@ -143,7 +143,7 @@ class DsqlCompatTest {@Test@Order(4)- void adminSignsInWithTheSdksToken() throws Exception {+ void adminSignsInWithTheSdksTokenAndTheDatabaseSpeaksDsql() throws Exception {String token = dsql.utilities().generateDbConnectAdminAuthToken(b -> b.hostname(endpoint).region(REGION));try (Connection connection = connect("admin", token); Statement statement = connection.createStatement()) {@@ -152,12 +152,19 @@ class DsqlCompatTest {assertThat(row.getString(1)).isEqualTo("admin");assertThat(row.getString(2)).isEqualTo("repeatable read");}- statement.execute("CREATE TABLE compat_orders (id int PRIMARY KEY, n int)");- statement.execute("INSERT INTO compat_orders VALUES (1, 7)");- try (ResultSet row = statement.executeQuery("SELECT n FROM compat_orders WHERE id = 1")) {- assertThat(row.next()).isTrue();- assertThat(row.getInt(1)).isEqualTo(7);+ statement.execute("CREATE TABLE compat_orders (id uuid PRIMARY KEY, n int)");+ String jobId;+ try (ResultSet job = statement.executeQuery("CREATE INDEX ASYNC compat_orders_n ON compat_orders (n)")) {+ assertThat(job.next()).isTrue();+ jobId = job.getString("job_id");+ }+ try (ResultSet waited = statement.executeQuery("CALL sys.wait_for_job('" + jobId + "')")) {+ assertThat(waited.next()).isTrue();+ assertThat(waited.getBoolean(1)).isTrue();}+ assertThatThrownBy(() -> statement.execute("TRUNCATE compat_orders"))+ .isInstanceOf(SQLException.class)+ .hasMessageContaining("unsupported statement: Truncate");}}diff --git a/docs/services/dsql.md b/docs/services/dsql.mdindex e4e6fa2203..c3ac80b7f7 100644--- a/docs/services/dsql.md+++ b/docs/services/dsql.md@@ -5,8 +5,8 @@**Endpoint:** `http://localhost:4566` (control plane), `<cluster-id>.dsql.<region>.localhost.floci.io:5432` (clusters)Floci runs each Aurora DSQL cluster as a real PostgreSQL 16 database in a Docker container, behind one-endpoint that admits clients the way DSQL does: TLS and an IAM token as the password. The answers,-messages and SQLSTATEs below were measured on AWS.+endpoint that admits clients the way DSQL does: TLS, an IAM token as the password, and DSQL's+dialect and limits. The answers, messages and SQLSTATEs below were measured on AWS.## Supported Actions@@ -83,37 +83,68 @@ When Floci runs in Docker, publish `5432` alongside `4566`.## SQLThe database is PostgreSQL 16 at `REPEATABLE READ`, as DSQL's is, with the role `admin`, which owns-the `public` schema and can create roles and databases. A connection closes after an hour, as DSQL-closes it.+the `public` schema and can create roles and databases, and DSQL's dialect installed in it:+- `CREATE [UNIQUE] INDEX ASYNC` answers a `job_id`; `sys.jobs` and `sys.wait_for_job` report the+ job. A unique index over duplicate keys fails its job with `found duplicate key(s) while validating+ index uniqueness` and stays, invalid, as on DSQL. A plain `CREATE INDEX` is refused.- `AWS IAM GRANT <role> TO '<arn>'` and `AWS IAM REVOKE <role> FROM '<arn>'`, for an IAM role oruser, with `sys.iam_pg_role_mappings`. A superuser role cannot be mapped, only a role holding the`ADMIN` option on a role can map it (`admin` maps the roles it created), and a mapped role cannotbe dropped until its mappings are revoked.+- One DDL statement per transaction, statements on roles (`CREATE`, `ALTER` and `DROP ROLE`, and+ `GRANT` or `REVOKE` of a role) included, no DDL with DML, and at most 3,000 modified rows per+ transaction.+- A transaction lives 300 seconds, as on DSQL. A client message after that, a `ROLLBACK` included,+ ends it with `54000` `transaction age limit of 300s exceeded` and closes the connection with+ `08P01`. An idle transaction is ended the same way, unasked, 15 seconds after its limit. A+ statement still running at the limit fails with the same `54000`: nothing its transaction wrote+ is kept, the rest of its query, a `COMMIT` included, does not run, and the connection stays, in+ the failed transaction. The limit holds for a statement outside a transaction block too. A failed+ transaction left idle as long is closed with `25P03`. A connection closes after an hour.+- Refused with DSQL's SQLSTATE and message: temporary and partitioned tables, `CREATE TABLE AS`,+ `SELECT INTO` and materialized views, triggers, `CREATE TYPE`, PL/pgSQL functions and `DO`,+ extensions, array columns, `jsonb` and `bytea` keys (an expression's, or a domain's over either,+ included), `TRUNCATE`, `LISTEN`/`NOTIFY`, `VACUUM`, sequences without a `CACHE` of 1 or at least+ 65536, `ALTER TABLE ... ADD COLUMN` with a constraint or default, `ADD CONSTRAINT`, `ALTER DATABASE+ ... SET`, `FOR SHARE` and `FOR NO KEY UPDATE`, advisory locks, and isolation levels other than+ repeatable read, whether chosen for a transaction, set for the session, set with `set_config` or+ set for a role.+- Foreign keys work as on DSQL: declared in `CREATE TABLE`, enforced, with their `ON DELETE` and+ `ON UPDATE` actions and `DEFERRABLE`; rows a cascade changes count toward the 3,000-row limit.+ Adding one with `ALTER TABLE` is refused, as DSQL refuses it.- `sys.iam_session_user()` answers the connection's IAM principal and `sys.current_session_id()`- its session id, as on DSQL.+ its session id; `sys.dsql_major_version()`, `sys.cluster_size()` and `sys.cluster_size_limit()`+ answer as on DSQL.- `dsql` is a reserved prefix, as on DSQL: `SET`, `RESET`, `set_config`, `ALTER ROLE ... SET` and afunction's `SET` clause of a `dsql.` parameter fail with `42602` and `"dsql" is a reservedprefix.`, and `SHOW` of one with `42704`. `set_config` of another dotted parameter is `0A000`, though`SET` of one works.-- Errors carry no source location, as DSQL's carry none, and no line of Floci's `sys` functions in- their context; notices keep their location.+- Errors carry no source location, as DSQL's carry none, and nothing Floci's `sys` functions ran+ in their context; notices keep their location. A write conflict is DSQL's `40001` `change+ conflicts with another transaction (OC000)`.### Differences from AWS-- The rest of DSQL's SQL dialect is not applied yet: `CREATE INDEX ASYNC` and its jobs are refused- as PostgreSQL refuses them, what DSQL refuses works, and DSQL's transaction limits (one DDL- statement, 3,000 rows, 300 seconds) do not apply.-- `sys` also holds the tables behind Floci's IAM mappings.-- Floci checks the statements a client sends, not what a `DO` block or a function body runs. In- one, `SET`, `RESET` and `set_config` of a `dsql.` parameter set it where DSQL refuses it, since- only a PostgreSQL extension written in C can reserve a prefix, and so does `set_config` of a name- built at run time, as in `set_config(chr(100) || 'sql.x', ...)`. Nothing Floci reads lives in such- a parameter. Likewise a `DROP ROLE` in one drops a mapped role: `sys.iam_pg_role_mappings` no+- DSQL is optimistic: conflicting transactions both run and the second to commit fails. Floci's+ database is PostgreSQL, so a write that conflicts waits for the other transaction and fails when+ it commits, with DSQL's error.+- `sys` also holds the tables behind Floci's jobs, IAM mappings, session identities and+ transaction counts, and each table has the three `dsql_rows_*` triggers that count its writes.+ Disabling them changes nothing, and dropping one is refused as for a trigger that does not exist.+- Floci checks the statements a client sends, not what a SQL function's body runs. In one, `SET`,+ `RESET` and `set_config` of a `dsql.` parameter set it where DSQL refuses it, since only a+ PostgreSQL extension written in C can reserve a prefix, and so does `set_config` of a name built+ at run time, as in `set_config(chr(100) || 'sql.x', ...)`. Nothing Floci reads lives in such a+ parameter. Likewise a `DROP ROLE` in one drops a mapped role: `sys.iam_pg_role_mappings` nolonger lists its mappings, and the next `AWS IAM GRANT` or `REVOKE` removes them.-- DSQL is optimistic: conflicting transactions both run and the second to commit fails with- `40001`. Floci's database is PostgreSQL, so a write that conflicts waits for the other- transaction, then fails with PostgreSQL's `40001`.+- DSQL's primary key covers every column of its table, and its definition reads `PRIMARY KEY (id)+ INCLUDE (...)`; Floci's reads `PRIMARY KEY (id)`.+- A statement Floci refuses carries no position (`LINE 1: ...` in psql), where DSQL gives one.+- DSQL lets a statement running at the age limit finish, and fails it then; Floci stops it at the+ limit. The error, and what is kept, are the same.+- Floci's `sys.create_index_async`, behind `CREATE INDEX ASYNC`, creates the one index it is+ handed when a client calls it itself; DSQL has no such function.- DSQL accepts connections while a cluster is still `CREATING`; Floci's cluster is `CREATING` onlywhile its database starts, and serves once its database answers.diff --git a/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlEndpoint.java b/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlEndpoint.javaindex 7f19fba629..01edbd27f5 100644--- a/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlEndpoint.java+++ b/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlEndpoint.java@@ -29,6 +29,7 @@ import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;+import java.time.Clock;import java.time.Duration;import java.time.Instant;import java.time.ZoneOffset;@@ -38,6 +39,11 @@ import java.util.Locale;import java.util.Map;import java.util.Set;import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.Executors;+import java.util.concurrent.ScheduledExecutorService;+import java.util.concurrent.ScheduledFuture;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicBoolean;/*** The address every DSQL cluster is reached at: one port, as on AWS, where the server name a client@@ -70,6 +76,14 @@ public class DsqlEndpoint {private final Map<Long, DsqlDatabases.Backend> cancelKeys = new ConcurrentHashMap<>();private final Map<String, Set<Socket>> connections = new ConcurrentHashMap<>();private volatile ServerSocket server;+ private final Clock clock;+ // The sessions' age checks, each due by the clock, on one thread for the whole endpoint.+ private final ScheduledExecutorService ageChecks = Executors.newSingleThreadScheduledExecutor(+ Thread.ofVirtual().name("dsql-age-checks").factory());+ private final Set<ScheduledCheck> pendingChecks = ConcurrentHashMap.newKeySet();+ // DSQL's (measured): a transaction lives 300 seconds, and one idle past that is ended 15 later.+ private static final Duration TRANSACTION_AGE_LIMIT = Duration.ofSeconds(300);+ private static final Duration TRANSACTION_IDLE_GRACE = Duration.ofSeconds(15);/** A cluster being served, and where its database answers. */record Route(String host, String arn, String region, String accountId, DsqlDatabases.Backend backend) {@@ -92,7 +106,8 @@ public class DsqlEndpoint {@Injectpublic DsqlEndpoint(DsqlTlsCertificates certificates, IamService iamService, IamPolicyEvaluator policyEvaluator,- Instance<ScpProvider> scpProvider, EmulatorConfig config) {+ Instance<ScpProvider> scpProvider, EmulatorConfig config, Clock clock) {+ this.clock = clock;this.certificates = certificates;this.iamService = iamService;this.policyEvaluator = policyEvaluator;@@ -127,6 +142,8 @@ public class DsqlEndpoint {@PreDestroypublic synchronized void stop() {+ ageChecks.shutdownNow();+ pendingChecks.clear();ServerSocket listening = server;server = null;if (listening != null) {@@ -178,6 +195,78 @@ public class DsqlEndpoint {return HANDSHAKE_TIMEOUT_MILLIS;}+ /** The time every transaction's age is read by. */+ Clock clock() {+ return clock;+ }++ /** A check that runs once, when the clock reaches its time, unless it is cancelled first. */+ final class ScheduledCheck {++ private final Instant due;+ private final Runnable check;+ private final AtomicBoolean done = new AtomicBoolean();+ private volatile ScheduledFuture<?> future;++ private ScheduledCheck(Instant due, Runnable check) {+ this.due = due;+ this.check = check;+ }++ void cancel() {+ if (done.compareAndSet(false, true)) {+ pendingChecks.remove(this);+ future.cancel(false);+ }+ }++ private void run() {+ if (done.compareAndSet(false, true)) {+ pendingChecks.remove(this);+ check.run();+ }+ }+ }++ /** Runs {@code check} when the clock reaches {@code due}. */+ ScheduledCheck schedule(Instant due, Runnable check) {+ ScheduledCheck scheduled = new ScheduledCheck(due, check);+ pendingChecks.add(scheduled);+ // toMillis drops what is below a millisecond, which would run the check just before it is due.+ long delay = Math.max(0, Duration.between(clock.instant(), due).toMillis() + 1);+ scheduled.future = ageChecks.schedule(scheduled::run, delay, TimeUnit.MILLISECONDS);+ return scheduled;+ }++ /**+ * Runs every check the clock has reached, and those they schedule that it has reached too: the+ * checks a clock moved forward has made due before their delay ran out.+ */+ void runDueChecks() {+ boolean ran = true;+ while (ran) {+ ran = false;+ Instant now = clock.instant();+ for (ScheduledCheck scheduled : List.copyOf(pendingChecks)) {+ if (!scheduled.due.isAfter(now)) {+ scheduled.future.cancel(false);+ scheduled.run();+ ran = true;+ }+ }+ }+ }++ /** How long a transaction may live. */+ Duration transactionAgeLimit() {+ return TRANSACTION_AGE_LIMIT;+ }++ /** How long past its age limit an idle transaction is let be. */+ Duration transactionIdleGrace() {+ return TRANSACTION_IDLE_GRACE;+ }+/*** Whether {@code token} lets {@code user} in, checked in the order DSQL reports: the cluster* the client asked for by name (or, without a name, the one the token is for), the actiondiff --git a/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlSession.java b/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlSession.javaindex 28fb381ee3..a503ff1ab2 100644--- a/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlSession.java+++ b/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlSession.java@@ -17,6 +17,7 @@ import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.Socket;import java.time.Duration;+import java.time.Instant;import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Arrays;@@ -28,15 +29,16 @@ import java.util.List;import java.util.Locale;import java.util.Map;import java.util.Set;+import java.util.concurrent.atomic.AtomicInteger;import java.util.function.Function;import java.util.stream.Stream;/*** One client connection to a DSQL endpoint, as Aurora DSQL serves it (measured on AWS, eu-west-1,- * 2026-10-16): TLS is mandatory, the password is an IAM token for the endpoint, the startup is read- * as DSQL reads it, DSQL's own statements become the {@code sys} calls that implement them, their- * errors come back without the source locations and {@code sys} lines DSQL never shows, and a- * connection lives an hour.+ * 2026-10-16 to 2026-10-21): TLS is mandatory, the password is an IAM token for the endpoint, the+ * startup is read as DSQL reads it, DSQL's own statements become the {@code sys} calls that+ * implement them, their errors come back in DSQL's words, a transaction lives 300 seconds and a+ * connection an hour.*/final class DsqlSession {@@ -44,6 +46,8 @@ final class DsqlSession {// A startup packet is refused above PostgreSQL's own limit, 10,000 bytes, and a message above 64 MB.private static final int MAX_STARTUP = 10_000;private static final int MAX_MESSAGE = 64 * 1024 * 1024;+ private static final String SERIALIZATION_FAILURE = "40001";+ private static final String QUERY_CANCELED = "57014";private static final String ACCESS_DENIED = "unable to accept connection, access denied";private final Socket socket;@@ -61,10 +65,37 @@ final class DsqlSession {private volatile String principalArn;private volatile int backendPid;private volatile long cancelKey;+ // What the age limit needs: where each side is written, whether a statement is still running+ // (a Query or Sync whose ReadyForQuery has not come back), and the open transaction's start.+ private final Object clientWrites = new Object();+ private final Object databaseWrites = new Object();+ private final AtomicInteger awaitingReady = new AtomicInteger();+ private volatile OutputStream clientOut;+ private volatile OutputStream databaseOut;+ private volatile Socket clientSocket;+ private volatile Socket databaseSocket;+ private volatile Instant lastClientMessage;+ private volatile Instant transactionStart;+ // The session's one age check pending, by the endpoint's clock: replaced by the next, and+ // cancelled when the transaction or the connection ends.+ private DsqlEndpoint.ScheduledCheck ageCheck;+ // When the database last answered a batch: a statement it runs next starts no earlier.+ private volatile Instant lastReady;+ // The startup's BackendKeyData, to cancel the session's statement with; and whether the+ // statement being cancelled was cancelled for its transaction's age.+ private volatile byte[] cancelKeyData;+ private volatile boolean cancelledForAge;+ private volatile char transactionStatus = 'I';DsqlSession(Socket socket, DsqlEndpoint endpoint) {this.socket = socket;this.endpoint = endpoint;+ this.lastClientMessage = now();+ this.lastReady = now();+ }++ private Instant now() {+ return endpoint.clock().instant();}void serve() throws IOException {@@ -163,6 +194,10 @@ final class DsqlSession {principalArn = admission.principalArn();backendOut.write(PostgresWire.startupMessage(backendStartup));backendOut.flush();+ clientOut = out;+ databaseOut = backendOut;+ clientSocket = tls;+ databaseSocket = backend;Thread toClient = Thread.ofVirtual().name("dsql-backend-" + sessionId).start(() -> relayToClient(backendIn, out, admission.route(), tls));@@ -178,6 +213,7 @@ final class DsqlSession {try {relayToBackend(in, backendOut);} finally {+ cancelAgeCheck();lifetime.interrupt();closeQuietly(backend);toClient.interrupt();@@ -193,67 +229,248 @@ final class DsqlSession {private void relayToBackend(InputStream in, OutputStream backendOut) throws IOException {while (true) {PostgresWire.Message message = PostgresWire.read(in, MAX_MESSAGE, "message");- switch (message.type()) {- case 'Q' -> {- String query = PostgresWire.cString(message.body(), 0).value();- PostgresWire.write(backendOut, 'Q', PostgresWire.cStringBytes(rewriteSimpleQuery(query)));+ if (message.type() != 'X') {+ lastClientMessage = now();+ if (transactionStatus == 'T' && pastAgeLimit()) {+ // DSQL ends a transaction past its age at the client's next message, a ROLLBACK+ // included, and the connection with it (measured).+ terminate();+ return;}- case 'P' -> {- PostgresWire.CString name = PostgresWire.cString(message.body(), 0);- PostgresWire.CString query = PostgresWire.cString(message.body(), name.next());- DsqlStatements.Query rewritten = DsqlStatements.rewriteQuery(query.value());- String tag = rewritten.overridesTags() && rewritten.commandTags().size() == 1- ? rewritten.commandTags().get(0) : null;- synchronized (batches) {- extendedBatch().parses.addLast(new Named(name.value(), tag));- }- PostgresWire.write(backendOut, 'P', PostgresWire.cStringBytes(name.value()),- PostgresWire.cStringBytes(rewritten.sql()),- Arrays.copyOfRange(message.body(), query.next(), message.body().length));+ if (message.type() == 'Q' || message.type() == 'S' || message.type() == 'F') {+ awaitingReady.incrementAndGet();}- case 'B' -> {- PostgresWire.CString portal = PostgresWire.cString(message.body(), 0);- PostgresWire.CString statement = PostgresWire.cString(message.body(), portal.next());- synchronized (batches) {- extendedBatch().binds.addLast(new Named(portal.value(), statement.value()));- }- PostgresWire.write(backendOut, message);+ }+ synchronized (databaseWrites) {+ if (relayOne(message, backendOut)) {+ return;}- case 'E' -> {- String portal = PostgresWire.cString(message.body(), 0).value();- synchronized (batches) {- extendedBatch().results.addLast(new Named(portal, null));- }- PostgresWire.write(backendOut, message);+ if (in.available() == 0) {+ backendOut.flush();}- case 'C' -> {- String kind = message.body()[0] == 'S' ? "S" : "P";- synchronized (batches) {- extendedBatch().closes.addLast(new Named(PostgresWire.cString(message.body(), 1).value(), kind));- }- PostgresWire.write(backendOut, message);+ }+ }+ }++ /** Hands one client message to the database, DSQL's syntax rewritten; true once the client said goodbye. */+ private boolean relayOne(PostgresWire.Message message, OutputStream backendOut) throws IOException {+ switch (message.type()) {+ case 'Q' -> {+ String query = PostgresWire.cString(message.body(), 0).value();+ PostgresWire.write(backendOut, 'Q', PostgresWire.cStringBytes(rewriteSimpleQuery(query)));+ }+ case 'P' -> {+ PostgresWire.CString name = PostgresWire.cString(message.body(), 0);+ PostgresWire.CString query = PostgresWire.cString(message.body(), name.next());+ DsqlStatements.Query rewritten = DsqlStatements.rewriteQuery(query.value());+ String tag = rewritten.overridesTags() && rewritten.commandTags().size() == 1+ ? rewritten.commandTags().get(0) : null;+ synchronized (batches) {+ extendedBatch().parses.addLast(new Named(name.value(), tag));}- case 'S', 'F' -> {- // A Sync, or a FunctionCall, is answered by a ReadyForQuery of its own.- synchronized (batches) {- extendedBatch();- openBatch = null;- }- PostgresWire.write(backendOut, message);+ PostgresWire.write(backendOut, 'P', PostgresWire.cStringBytes(name.value()),+ PostgresWire.cStringBytes(rewritten.sql()),+ Arrays.copyOfRange(message.body(), query.next(), message.body().length));+ }+ case 'B' -> {+ PostgresWire.CString portal = PostgresWire.cString(message.body(), 0);+ PostgresWire.CString statement = PostgresWire.cString(message.body(), portal.next());+ synchronized (batches) {+ extendedBatch().binds.addLast(new Named(portal.value(), statement.value()));}- case 'X' -> {- PostgresWire.write(backendOut, message);- backendOut.flush();- return;+ PostgresWire.write(backendOut, message);+ }+ case 'E' -> {+ String portal = PostgresWire.cString(message.body(), 0).value();+ synchronized (batches) {+ extendedBatch().results.addLast(new Named(portal, null));+ }+ PostgresWire.write(backendOut, message);+ }+ case 'C' -> {+ String kind = message.body()[0] == 'S' ? "S" : "P";+ synchronized (batches) {+ extendedBatch().closes.addLast(new Named(PostgresWire.cString(message.body(), 1).value(), kind));}- default -> PostgresWire.write(backendOut, message);+ PostgresWire.write(backendOut, message);}- if (in.available() == 0) {+ case 'S', 'F' -> {+ // A Sync, or a FunctionCall, is answered by a ReadyForQuery of its own.+ synchronized (batches) {+ endBatch();+ }+ PostgresWire.write(backendOut, message);+ }+ case 'X' -> {+ PostgresWire.write(backendOut, message);backendOut.flush();+ return true;}+ default -> PostgresWire.write(backendOut, message);+ }+ return false;+ }++ /** When {@code batch} could first run: once sent, and once the database had answered the batch before it. */+ private Instant couldRun(Batch batch) {+ Instant answeredBefore = lastReady;+ return batch.sent.isAfter(answeredBefore) ? batch.sent : answeredBefore;+ }++ /** When the transaction the database is running started: the open one, or the batch's own. */+ private Instant runningTransactionStart() {+ Instant start = transactionStatus == 'T' ? transactionStart : null;+ if (start == null) {+ synchronized (batches) {+ Batch answering = batches.peekFirst();+ start = answering == null ? null : couldRun(answering);+ }+ }+ return start;+ }++ private Duration ageOfRunning() {+ Instant start = runningTransactionStart();+ return start == null ? Duration.ZERO : Duration.between(start, now());+ }++ /** DSQL's age error for a transaction {@code age} old. */+ private byte[] ageError(Duration age) {+ long limit = endpoint.transactionAgeLimit().toSeconds();+ return error("ERROR", "54000", "transaction age limit of " + limit + "s exceeded",+ "Current transaction age " + age.toSeconds() + "s exceeds " + limit + "s", null);+ }++ private boolean pastAgeLimit() {+ Instant start = transactionStart;+ return start != null && Duration.between(start, now()).compareTo(endpoint.transactionAgeLimit()) > 0;+ }++ private Duration transactionAge() {+ Instant start = transactionStart;+ return start == null ? Duration.ZERO : Duration.between(start, now());+ }++ /**+ * Follows the transaction the database reports. One that opens started when its batch could+ * first run: once sent, and once the database had answered the batch before it, so a BEGIN+ * queued behind a long statement does not count that wait. At its age limit a statement still+ * running is stopped with the age error, which fails the transaction; idle past the limit and+ * its grace the transaction is ended as DSQL ends it (measured: 315 s after BEGIN, whatever it+ * last ran). One that fails stays until it idles as long, as DSQL's idle-in-transaction+ * timeout lets it.+ */+ private void transactionStatus(char status, Instant batchCouldRun) {+ transactionStatus = status;+ if (status == 'I') {+ transactionStart = null;+ cancelAgeCheck();+ } else if (status == 'T' && transactionStart == null) {+ Instant start = batchCouldRun;+ transactionStart = start;+ schedule(start.plus(endpoint.transactionAgeLimit()), () -> {+ if (start.equals(transactionStart) && transactionStatus == 'T') {+ cancelForAge();+ schedule(start.plus(endpoint.transactionAgeLimit()).plus(endpoint.transactionIdleGrace()), () -> {+ if (start.equals(transactionStart) && transactionStatus == 'T' && awaitingReady.get() == 0) {+ terminate();+ }+ });+ }+ });+ } else if (status == 'E') {+ closeWhenIdle(now());}}+ /**+ * Outside a transaction block, the batch the database runs next is a transaction of its own,+ * under the same limit (measured): one still running at the limit is stopped with the age error.+ */+ private void watchImplicitTransaction(Batch running, Instant couldRun) {+ schedule(couldRun.plus(endpoint.transactionAgeLimit()), () -> {+ boolean stillRunning;+ synchronized (batches) {+ stillRunning = batches.peekFirst() == running;+ }+ if (stillRunning && transactionStatus == 'I') {+ cancelForAge();+ }+ });+ }++ /**+ * Stops the statement running at the transaction's age limit, with the cancel request a client+ * would send; its {@code 57014} reaches the client as DSQL's age error. DSQL lets the statement+ * finish and fails it then (measured); stopping it at the limit ends the same way, the error+ * and nothing kept, the rest of its query, a COMMIT included, never run.+ */+ private void cancelForAge() {+ byte[] keyData = cancelKeyData;+ if (awaitingReady.get() > 0 && keyData != null) {+ cancelledForAge = true;+ endpoint.forwardCancel(keyData);+ }+ }++ /**+ * Closes a failed transaction's connection once the client has sent nothing for its idle time+ * since {@code since}; a message in between moves the wait to start from it.+ */+ private void closeWhenIdle(Instant since) {+ schedule(since.plus(endpoint.transactionAgeLimit()).plus(endpoint.transactionIdleGrace()), () -> {+ Instant last = lastClientMessage;+ if (transactionStatus != 'E' || awaitingReady.get() > 0) {+ return;+ }+ if (last.isAfter(since)) {+ closeWhenIdle(last);+ return;+ }+ close("FATAL", "25P03", "terminating connection due to idle-in-transaction timeout", null);+ });+ }++ /** Puts {@code check}, due at {@code when}, in place of the age check pending. */+ private synchronized void schedule(Instant when, Runnable check) {+ if (ageCheck != null) {+ ageCheck.cancel();+ }+ ageCheck = endpoint.schedule(when, check);+ }++ private synchronized void cancelAgeCheck() {+ if (ageCheck != null) {+ ageCheck.cancel();+ ageCheck = null;+ }+ }++ /** DSQL's end of a transaction past its age: the age error, then the connection's (measured). */+ private void terminate() {+ try {+ synchronized (clientWrites) {+ PostgresWire.write(clientOut, 'E', ageError(transactionAge()));+ }+ } catch (IOException ignored) {+ // The client left first; the connection is closed below either way.+ }+ close("FATAL", "08P01", "terminating connection because protocol synchronization was lost", null);+ }++ private void close(String severity, String state, String message, String detail) {+ try {+ synchronized (clientWrites) {+ PostgresWire.write(clientOut, 'E', error(severity, state, message, detail, null));+ clientOut.flush();+ }+ } catch (IOException ignored) {+ // The client left first; both sides are closed below either way.+ }+ closeQuietly(clientSocket);+ closeQuietly(databaseSocket);+ }+/*** A simple query as the database runs it. Its statements' command tags join the batch its* ReadyForQuery ends: the extended-protocol messages sent since the last Sync, if any.@@ -261,18 +478,30 @@ final class DsqlSession {private String rewriteSimpleQuery(String query) {DsqlStatements.Query rewritten = DsqlStatements.rewriteQuery(query);synchronized (batches) {- Batch batch = extendedBatch();+ Batch batch = endBatch();rewritten.commandTags().forEach(tag -> batch.results.addLast(new Named(null, tag)));- openBatch = null;}return rewritten.sql();}+ /**+ * The batch a Query, Sync or FunctionCall ends, the extended-protocol messages since the last+ * Sync included, which its ReadyForQuery answers. Called holding {@code batches}.+ */+ private Batch endBatch() {+ Batch batch = extendedBatch();+ openBatch = null;+ return batch;+ }+/** The batch the extended-protocol messages since the last Sync belong to. Called holding {@code batches}. */private Batch extendedBatch() {if (openBatch == null) {- openBatch = new Batch();+ openBatch = new Batch(now());batches.addLast(openBatch);+ if (batches.size() == 1 && transactionStatus == 'I') {+ watchImplicitTransaction(openBatch, couldRun(openBatch));+ }}return openBatch;}@@ -284,10 +513,15 @@ final class DsqlSession {* query statement's tag.*/private static final class Batch {+ final Instant sent;final Deque<Named> parses = new ArrayDeque<>();final Deque<Named> binds = new ArrayDeque<>();final Deque<Named> closes = new ArrayDeque<>();final Deque<Named> results = new ArrayDeque<>();++ Batch(Instant sent) {+ this.sent = sent;+ }}/** A statement or portal name, and what goes with it; a simple query's result has no name. */@@ -369,6 +603,7 @@ final class DsqlSession {case 'K' -> {cancelKey = endpoint.registerCancelKey(message.body(), route.backend());backendPid = PostgresWire.int32(message.body(), 0);+ cancelKeyData = message.body();startup.add(message);continue;}@@ -408,23 +643,51 @@ final class DsqlSession {(closed.value().equals("S") ? statementTags : portalStatements).remove(closed.name());}}- case 'E', 'N' -> message = new PostgresWire.Message(message.type(),- inDsqlWords(message.type(), message.body()));+ case 'E', 'N' -> {+ if (message.type() == 'E') {+ String state = PostgresWire.parseFields(message.body(), 0).get('C');+ if (cancelledForAge && QUERY_CANCELED.equals(state)) {+ cancelledForAge = false;+ message = new PostgresWire.Message(message.type(), ageError(ageOfRunning()));+ break;+ }+ }+ message = new PostgresWire.Message(message.type(), inDsqlWords(message.type(), message.body()));+ }case 'Z' -> {+ awaitingReady.updateAndGet(n -> Math.max(0, n - 1));+ // A cancel that reached no statement leaves nothing for a later one to inherit.+ cancelledForAge = false;+ Batch answered;synchronized (batches) {- batches.pollFirst();+ answered = batches.pollFirst();}+ Instant couldRun = answered != null ? couldRun(answered) : lastReady;+ lastReady = now();if (message.body()[0] == 'I') {// Outside a transaction no portal outlives its Sync.portalStatements.clear();}+ char status = (char) message.body()[0];+ if (started) {+ transactionStatus(status, couldRun);+ Batch next;+ synchronized (batches) {+ next = batches.peekFirst();+ }+ if (status == 'I' && next != null) {+ watchImplicitTransaction(next, couldRun(next));+ }+ }}default -> {}}- PostgresWire.write(out, message);- if (backendIn.available() == 0) {- out.flush();+ synchronized (clientWrites) {+ PostgresWire.write(out, message);+ if (backendIn.available() == 0) {+ out.flush();+ }}}} catch (IOException ignored) {@@ -434,14 +697,23 @@ final class DsqlSession {}/**- * An error or notice as DSQL words it (measured on AWS). An error carries no source location,- * PostgreSQL's own included, while a notice keeps its location. The context keeps what the- * client's SQL ran and drops what Floci's {@code sys} functions ran, as DSQL's context never- * shows its own: the context lists the innermost call first, so everything up to the last+ * An error or notice as DSQL words it (measured on AWS). An optimistic concurrency conflict is+ * DSQL's OC000. An error carries no source location, PostgreSQL's own included, while a notice+ * keeps its location. The context keeps what the client's SQL ran, such as the statement a+ * foreign key's cascade ran, and drops what Floci's {@code sys} functions ran, as DSQL's context+ * never shows its own: the context lists the innermost call first, so everything up to the last* line of a {@code sys} function, the statements it ran included, is theirs.*/static byte[] inDsqlWords(byte type, byte[] body) {Map<Character, String> fields = PostgresWire.parseFields(body, 0);+ if (type == 'E' && SERIALIZATION_FAILURE.equals(fields.get('C'))) {+ Map<Character, String> conflict = new LinkedHashMap<>();+ conflict.put('S', fields.getOrDefault('S', "ERROR"));+ conflict.put('V', fields.getOrDefault('V', "ERROR"));+ conflict.put('C', SERIALIZATION_FAILURE);+ conflict.put('M', "change conflicts with another transaction (OC000)");+ return PostgresWire.fields(conflict);+ }boolean changed = false;String where = fields.get('W');if (where != null) {diff --git a/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlStatements.java b/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlStatements.javaindex 9616ed1a66..2a8aebdccb 100644--- a/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlStatements.java+++ b/src/main/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlStatements.java@@ -6,15 +6,29 @@ import java.util.Locale;import java.util.Set;/**- * The statements of a query as Aurora DSQL reads them. DSQL's own syntax ({@code AWS IAM GRANT}- * and {@code REVOKE}) becomes the calls into the cluster's {@code sys} schema that implement it,- * and a statement DSQL refuses becomes a call to {@code sys._reject} with the SQLSTATE and message- * DSQL answers (measured on AWS, eu-west-1, 2026-10-16 and 2026-10-20), so the database raises the- * error and the transaction fails as DSQL's does.+ * The statements of a query as Aurora DSQL reads them. DSQL's own syntax ({@code CREATE INDEX+ * ASYNC}, {@code AWS IAM GRANT} and {@code REVOKE}) becomes the calls into the cluster's+ * {@code sys} schema that implement it, and a statement DSQL refuses becomes a call to+ * {@code sys._reject} with the SQLSTATE and message DSQL answers (measured on AWS, eu-west-1,+ * 2026-10-16), so the database raises the error and the transaction fails as DSQL's does. What+ * DSQL refuses that the catalog can tell (types, temporary and partitioned tables, PL/pgSQL+ * functions, triggers) is refused inside the database instead.*/public final class DsqlStatements {+ private static final Set<String> ADVISORY_LOCKS = Set.of(+ "pg_advisory_lock", "pg_advisory_lock_shared", "pg_try_advisory_lock", "pg_try_advisory_lock_shared",+ "pg_advisory_xact_lock", "pg_advisory_xact_lock_shared", "pg_try_advisory_xact_lock",+ "pg_try_advisory_xact_lock_shared", "pg_advisory_unlock", "pg_advisory_unlock_shared",+ "pg_advisory_unlock_all");+ private static final Set<String> COLUMN_CONSTRAINTS = Set.of(+ "DEFAULT", "NOT", "NULL", "CHECK", "UNIQUE", "PRIMARY", "REFERENCES", "GENERATED", "CONSTRAINT",+ "COLLATE");+ private static final Set<String> TABLE_CONSTRAINTS = Set.of(+ "CONSTRAINT", "PRIMARY", "UNIQUE", "CHECK", "FOREIGN", "EXCLUDE");private static final String RESERVED_PREFIX = "dsql.";+ private static final Set<String> ISOLATION_PARAMETERS = Set.of("default_transaction_isolation", "transaction_isolation");+ private static final Set<String> ROLE_KINDS = Set.of("ROLE", "USER", "GROUP");private static final Set<String> ROLE_SPECIFIERS = Set.of("CURRENT_ROLE", "CURRENT_USER", "SESSION_USER", "PUBLIC","NONE");@@ -94,10 +108,88 @@ public final class DsqlStatements {return drop;}}+ if ("CREATE".equals(first)) {+ int at = 1;+ if ("UNIQUE".equals(word(tokens, at))) {+ at++;+ }+ if ("INDEX".equals(word(tokens, at)) && "ASYNC".equals(word(tokens, at + 1))) {+ return createIndexAsync(text, tokens, at + 1);+ }+ if ("DATABASE".equals(second)) {+ return rejected("0A000", "CREATE DATABASE not supported");+ }+ if ("TABLESPACE".equals(second)) {+ return rejected("0A000", "unsupported statement: CreateTableSpace");+ }+ if ("EXTENSION".equals(second)) {+ return rejected("0A000", "unsupported statement: CreateExtension");+ }+ int sequence = indexOfWord(tokens, "SEQUENCE");+ if (sequence > 0 && sequence <= 3 && onlyWords(tokens, 1, sequence, Set.of("TEMP", "TEMPORARY", "UNLOGGED"))) {+ Statement refused = sequenceCache(tokens);+ if (refused != null) {+ return refused;+ }+ }+ }+ if ("TRUNCATE".equals(first)) {+ return rejected("0A000", "unsupported statement: Truncate");+ }+ if ("LISTEN".equals(first)) {+ return rejected("0A000", "unsupported statement: Listen");+ }+ if ("NOTIFY".equals(first)) {+ return rejected("0A000", "unsupported statement: Notify");+ }+ if ("UNLISTEN".equals(first)) {+ return rejected("0A000", "unsupported statement: Unlisten");+ }+ if ("VACUUM".equals(first)) {+ return rejected("0A000", "unsupported VACUUM statement");+ }+ if ("DO".equals(first)) {+ return rejected("0A000", "DO with language plpgsql not supported");+ }+ if ("GRANT".equals(first) || "REVOKE".equals(first)) {+ int on = indexOfWord(tokens, "ON");+ if (on > 0 && "DATABASE".equals(word(tokens, on + 1))) {+ return rejected("0A000", "unsupported object type in " + first);+ }+ }+ if ("ALTER".equals(first) && "DATABASE".equals(second)+ && (indexOfWord(tokens, "SET") > 0 || indexOfWord(tokens, "RESET") > 0)) {+ return rejected("0A000", "unsupported statement: AlterDatabaseSet");+ }+ if ("ALTER".equals(first) && "TABLE".equals(second)) {+ Statement refused = alterTableAdd(tokens);+ if (refused != null) {+ return refused;+ }+ }Statement setting = setting(tokens, first);if (setting != null) {return setting;}+ Statement isolation = isolation(tokens, first, second);+ if (isolation != null) {+ return isolation;+ }+ Statement role = roleDdl(text, tokens, first, second);+ if (role != null) {+ return role;+ }+ Statement locking = lockingClause(tokens);+ if (locking != null) {+ return locking;+ }+ for (int i = 0; i + 1 < tokens.size(); i++) {+ Token token = tokens.get(i);+ boolean name = token.type() == Type.WORD || token.type() == Type.QUOTED_IDENTIFIER;+ if (name && ADVISORY_LOCKS.contains(identifier(token)) && "(".equals(tokens.get(i + 1).text())) {+ return rejected("0A000", "function " + identifier(token) + " not supported");+ }+ }return new Statement(text, null);}@@ -123,6 +215,107 @@ public final class DsqlStatements {return new Statement(call, grant ? "AWS IAM GRANT" : "AWS IAM REVOKE");}+ /**+ * {@code CREATE [UNIQUE] INDEX ASYNC [IF NOT EXISTS] [name] ON [ONLY] table ...}: the+ * statement without {@code ASYNC}, the index's name and its table, for+ * {@code sys.create_index_async}, which answers the job id DSQL answers.+ */+ private static Statement createIndexAsync(String text, List<Token> tokens, int asyncAt) {+ Token async = tokens.get(asyncAt);+ int base = tokens.get(0).start();+ String statement = text.substring(0, async.start() - base) + text.substring(async.end() - base);+ int at = asyncAt + 1;+ if ("IF".equals(word(tokens, at)) && "NOT".equals(word(tokens, at + 1)) && "EXISTS".equals(word(tokens, at + 2))) {+ at += 3;+ }+ String indexName = null;+ if (!"ON".equals(word(tokens, at)) && at < tokens.size()) {+ indexName = identifier(tokens.get(at));+ at++;+ }+ if (!"ON".equals(word(tokens, at))) {+ return new Statement(statement, null);+ }+ at++;+ if ("ONLY".equals(word(tokens, at))) {+ at++;+ }+ int tableStart = at;+ while (at < tokens.size() && !"(".equals(tokens.get(at).text()) && !"USING".equals(word(tokens, at))) {+ at++;+ }+ if (tableStart >= at) {+ return new Statement(statement, null);+ }+ String table = text.substring(tokens.get(tableStart).start() - base, tokens.get(at - 1).end() - base);+ String call = "SELECT job_id FROM sys.create_index_async(" + dollarQuoted(statement) + ", "+ + (indexName == null ? "NULL" : literal(indexName)) + ", " + literal(table) + ")";+ return new Statement(call, null);+ }++ /** The sequence's {@code CACHE}, read from the statement's tokens so comments and names do not count. */+ private static Statement sequenceCache(List<Token> tokens) {+ String cache = null;+ for (int i = 0; i + 1 < tokens.size() && cache == null; i++) {+ if ("CACHE".equals(word(tokens, i))) {+ boolean negative = "-".equals(tokens.get(i + 1).text());+ int at = negative ? i + 2 : i + 1;+ if (at < tokens.size() && tokens.get(at).type() == Type.NUMBER) {+ cache = (negative ? "-" : "") + tokens.get(at).text();+ }+ }+ }+ if (cache == null) {+ return rejected("0A000", "CREATE SEQUENCE is not supported without an explicit cache size. please"+ + " define CACHE greater than or equal to 65536 or equal to 1");+ }+ long size;+ try {+ size = Long.parseLong(cache);+ } catch (NumberFormatException e) {+ // Past a bigint, or not an integer: the database's own error is what DSQL answers too (measured).+ return null;+ }+ if (size != 1 && size < 65536) {+ return rejected("22023", "CACHE (" + size + ") must be greater than or equal to 65536 or equal to 1");+ }+ return null;+ }++ /** {@code ALTER TABLE ... ADD [COLUMN] name type <constraint>} and {@code ADD CONSTRAINT}. */+ private static Statement alterTableAdd(List<Token> tokens) {+ for (int i = 2; i < tokens.size(); i++) {+ if (!"ADD".equals(word(tokens, i))) {+ continue;+ }+ int at = i + 1;+ if (TABLE_CONSTRAINTS.contains(word(tokens, at))) {+ return rejected("0A000", "unsupported ALTER TABLE ADD CONSTRAINT statement");+ }+ if ("COLUMN".equals(word(tokens, at))) {+ at++;+ }+ if ("IF".equals(word(tokens, at)) && "NOT".equals(word(tokens, at + 1))) {+ at += 3;+ }+ int depth = 0;+ for (int j = at + 1; j < tokens.size(); j++) {+ String text = tokens.get(j).text();+ if ("(".equals(text)) {+ depth++;+ } else if (")".equals(text)) {+ depth--;+ } else if (depth == 0 && ",".equals(text)) {+ break;+ } else if (depth == 0 && tokens.get(j).type() == Type.WORD+ && COLUMN_CONSTRAINTS.contains(tokens.get(j).upper())) {+ return rejected("0A000", "ALTER TABLE ADD COLUMN with constraint not supported");+ }+ }+ }+ return null;+ }+/*** DSQL reserves the {@code dsql} prefix as PostgreSQL reserves an extension's (measured,* eu-west-1, 2026-10-20): setting or resetting a {@code dsql.} parameter, with {@code SET} or@@ -145,6 +338,9 @@ public final class DsqlStatements {if (name.startsWith(RESERVED_PREFIX)) {return reservedPrefix(name);}+ if ("SET".equals(word) && ISOLATION_PARAMETERS.contains(name)) {+ return notSupported(name);+ }}boolean setConfig = "SET_CONFIG".equals(word) || tokens.get(i).type() == Type.QUOTED_IDENTIFIER&& "set_config".equals(tokens.get(i).value());@@ -154,8 +350,8 @@ public final class DsqlStatements {if (name.startsWith(RESERVED_PREFIX)) {return reservedPrefix(name);}- if (name.contains(".")) {- return rejected("0A000", "setting configuration parameter \"" + name + "\" not supported");+ if (name.contains(".") || ISOLATION_PARAMETERS.contains(name)) {+ return notSupported(name);}}}@@ -193,6 +389,26 @@ public final class DsqlStatements {"DROP ROLE");}+ private static Statement notSupported(String parameter) {+ return rejected("0A000", "setting configuration parameter \"" + parameter + "\" not supported");+ }++ /**+ * A statement on roles, which DSQL counts as DDL (measured) though PostgreSQL fires no event+ * trigger for one: {@code CREATE} or {@code ALTER ROLE|USER|GROUP}, and {@code GRANT} or+ * {@code REVOKE} of a role, which names no object with {@code ON}. {@code sys.run_role_ddl}+ * counts it, then runs it as the caller, under PostgreSQL's command tag.+ */+ private static Statement roleDdl(String text, List<Token> tokens, String first, String second) {+ boolean createOrAlter = ("CREATE".equals(first) || "ALTER".equals(first)) && ROLE_KINDS.contains(second)+ && !"MAPPING".equals(word(tokens, 2));+ boolean grantOrRevoke = ("GRANT".equals(first) || "REVOKE".equals(first)) && indexOfWord(tokens, "ON") < 0;+ if (!createOrAlter && !grantOrRevoke) {+ return null;+ }+ return new Statement("CALL sys.run_role_ddl(" + dollarQuoted(text) + ")", first + " ROLE");+ }+private static Statement reservedPrefix(String name) {return new Statement(reject("42602", "invalid configuration parameter name \"" + name + "\"","\"dsql\" is a reserved prefix."), null);@@ -218,6 +434,41 @@ public final class DsqlStatements {return name.toString();}+ private static Statement isolation(List<Token> tokens, String first, String second) {+ boolean setsCharacteristics = "SET".equals(first) && ("TRANSACTION".equals(second)+ || ("SESSION".equals(second) && "CHARACTERISTICS".equals(word(tokens, 2))));+ boolean begins = "BEGIN".equals(first) || ("START".equals(first) && "TRANSACTION".equals(second));+ if (setsCharacteristics || begins) {+ int level = indexOfWord(tokens, "LEVEL");+ if (level > 0 && "ISOLATION".equals(word(tokens, level - 1))) {+ String chosen = word(tokens, level + 1) + " " + word(tokens, level + 2);+ String name = switch (chosen) {+ case "REPEATABLE READ" -> null;+ case "READ COMMITTED", "READ UNCOMMITTED" -> chosen;+ default -> word(tokens, level + 1);+ };+ if (name != null) {+ return rejected("0A000", "Unsupported isolation level: " + name);+ }+ }+ }+ return null;+ }++ private static Statement lockingClause(List<Token> tokens) {+ for (int i = 0; i + 1 < tokens.size(); i++) {+ if (!"FOR".equals(word(tokens, i))) {+ continue;+ }+ String next = word(tokens, i + 1);+ if ("SHARE".equals(next) || ("NO".equals(next) && "KEY".equals(word(tokens, i + 2))+ && "UPDATE".equals(word(tokens, i + 3)))) {+ return rejected("0A000", "locking clauses other than FOR UPDATE/FOR KEY SHARE are not supported");+ }+ }+ return null;+ }+private static Statement rejected(String state, String message) {return new Statement(reject(state, message, null), null);}@@ -245,7 +496,8 @@ public final class DsqlStatements {if (Character.isWhitespace(c)) {i++;} else if (c == '-' && i + 1 < n && sql.charAt(i + 1) == '-') {- while (i < n && sql.charAt(i) != '\n') {+ // PostgreSQL ends the comment at either line break.+ while (i < n && sql.charAt(i) != '\n' && sql.charAt(i) != '\r') {i++;}} else if (c == '/' && i + 1 < n && sql.charAt(i + 1) == '*') {@@ -368,6 +620,24 @@ public final class DsqlStatements {return tokens.get(index).upper();}+ private static int indexOfWord(List<Token> tokens, String word) {+ for (int i = 0; i < tokens.size(); i++) {+ if (word.equals(word(tokens, i))) {+ return i;+ }+ }+ return -1;+ }++ private static boolean onlyWords(List<Token> tokens, int from, int to, Set<String> allowed) {+ for (int i = from; i < to; i++) {+ if (!allowed.contains(word(tokens, i))) {+ return false;+ }+ }+ return true;+ }+private static String identifier(Token token) {return switch (token.type()) {case QUOTED_IDENTIFIER -> token.value();@@ -379,4 +649,13 @@ public final class DsqlStatements {static String literal(String value) {return "'" + value.replace("'", "''") + "'";}++ private static String dollarQuoted(String value) {+ String tag = "$dsql$";+ int n = 0;+ while (value.contains(tag)) {+ tag = "$dsql" + (++n) + "$";+ }+ return tag + value + tag;+ }}diff --git a/src/main/resources/dsql/bootstrap.sql b/src/main/resources/dsql/bootstrap.sqlindex d39dd25bd7..91a7e62439 100644--- a/src/main/resources/dsql/bootstrap.sql+++ b/src/main/resources/dsql/bootstrap.sql@@ -1,7 +1,8 @@--- What a cluster's PostgreSQL is before any client connects, as Aurora DSQL's database is (measured--- on AWS, eu-west-1, 2026-10-16): the role admin, which owns the public schema, repeatable read, and--- the sys schema with the session's identity and AWS IAM GRANT. Installed by Floci as the superuser--- dbowner every time the database starts; every statement is idempotent.+-- Aurora DSQL's dialect inside a cluster's PostgreSQL, installed by Floci as the superuser dbowner+-- every time the database starts. Every statement is idempotent. What DSQL answers was measured on+-- AWS (eu-west-1, 2026-10-16); the messages and SQLSTATEs below are its own. Event triggers do not+-- fire for a session in the replica role, so the dialect's own DDL is not checked against it.+SET session_replication_role = replica;DO $$BEGIN@@ -17,7 +18,63 @@ ALTER DATABASE postgres SET default_transaction_isolation TO 'repeatable read';CREATE SCHEMA IF NOT EXISTS sys AUTHORIZATION dbowner;GRANT USAGE ON SCHEMA sys TO PUBLIC;--- ── The session ───────────────────────────────────────────────────────────────+-- ── Identifiers: a UUID as 26 characters of lowercase base32 ──────────────────++CREATE OR REPLACE FUNCTION sys.uuid_to_base32_str(u uuid) RETURNS text+LANGUAGE plpgsql IMMUTABLE STRICT AS $$+DECLARE+ alphabet constant text := 'abcdefghijklmnopqrstuvwxyz234567';+ bytes bytea := uuid_send(u);+ buffer bigint := 0;+ bits int := 0;+ result text := '';+BEGIN+ FOR i IN 0..15 LOOP+ buffer := (buffer << 8) | get_byte(bytes, i);+ bits := bits + 8;+ WHILE bits >= 5 LOOP+ result := result || substr(alphabet, ((buffer >> (bits - 5)) & 31)::int + 1, 1);+ bits := bits - 5;+ END LOOP;+ buffer := buffer & ((1::bigint << bits) - 1);+ END LOOP;+ RETURN result || substr(alphabet, ((buffer << (5 - bits)) & 31)::int + 1, 1);+END+$$;++CREATE OR REPLACE FUNCTION sys.base32_str_to_uuid(s text) RETURNS uuid+LANGUAGE plpgsql IMMUTABLE STRICT AS $$+DECLARE+ alphabet constant text := 'abcdefghijklmnopqrstuvwxyz234567';+ value int;+ buffer bigint := 0;+ bits int := 0;+ hex text := '';+BEGIN+ IF length(s) <> 26 THEN+ RAISE EXCEPTION USING ERRCODE = '22P02', MESSAGE = 'Unable to convert text to UUID';+ END IF;+ FOR i IN 1..26 LOOP+ value := strpos(alphabet, substr(lower(s), i, 1)) - 1;+ IF value < 0 THEN+ RAISE EXCEPTION USING ERRCODE = '22P02', MESSAGE = 'Unable to convert text to UUID';+ END IF;+ buffer := (buffer << 5) | value;+ bits := bits + 5;+ IF bits >= 8 THEN+ hex := hex || lpad(to_hex((buffer >> (bits - 8)) & 255), 2, '0');+ bits := bits - 8;+ buffer := buffer & ((1::bigint << bits) - 1);+ END IF;+ END LOOP;+ IF buffer <> 0 THEN+ RAISE EXCEPTION USING ERRCODE = '22P02', MESSAGE = 'Unable to convert text to UUID';+ END IF;+ RETURN hex::uuid;+END+$$;++-- ── Sessions and the cluster ──────────────────────────────────────────────────-- Each connection's IAM principal and session id, written by Floci's endpoint before the client's-- first statement, keyed by the backend serving it. Only the definer functions read it, so a client@@ -38,7 +95,126 @@ CREATE OR REPLACE FUNCTION sys.current_session_id() RETURNS textLANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS$$ SELECT session_id FROM sys.session_identity WHERE pid = pg_backend_pid() $$;--- A statement DSQL refuses, raised with DSQL's SQLSTATE and message.+CREATE OR REPLACE FUNCTION sys.dsql_major_version() RETURNS integer+LANGUAGE sql IMMUTABLE AS $$ SELECT 1 $$;++CREATE OR REPLACE FUNCTION sys.cluster_size_limit() RETURNS bigint+LANGUAGE sql IMMUTABLE AS $$ SELECT 10995116277760::bigint $$;++CREATE OR REPLACE FUNCTION sys.cluster_size() RETURNS bigint+LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ SELECT pg_database_size('postgres') $$;++CREATE OR REPLACE VIEW sys.roles AS+SELECT rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb, rolcanlogin, rolreplication,+ rolconnlimit, '********'::text AS rolpassword, rolvaliduntil, rolbypassrls,+ s.setconfig AS rolconfig, pg_authid.oid+FROM pg_authid+LEFT JOIN pg_db_role_setting s ON pg_authid.oid = s.setrole AND s.setdatabase = 0::oid+WHERE pg_authid.rolname !~~ 'pg_%';+GRANT SELECT ON sys.roles TO PUBLIC;++-- ── A transaction's limits: one DDL statement, no DDL with DML, 3,000 rows ────++-- What each session's open transaction has done so far. Only the definer functions below write it,+-- so a client cannot reset its counts, as it could a setting of its own session.+CREATE TABLE IF NOT EXISTS sys.transaction_usage (+ pid integer PRIMARY KEY,+ xid xid8 NOT NULL,+ ddl_count bigint NOT NULL,+ dml_count bigint NOT NULL,+ row_count bigint NOT NULL+);+REVOKE ALL ON sys.transaction_usage FROM PUBLIC;++CREATE OR REPLACE FUNCTION sys._usage() RETURNS sys.transaction_usage+LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$+DECLARE+ used sys.transaction_usage;+BEGIN+ INSERT INTO sys.transaction_usage AS u VALUES (pg_backend_pid(), pg_current_xact_id(), 0, 0, 0)+ ON CONFLICT (pid) DO UPDATE SET xid = excluded.xid, ddl_count = 0, dml_count = 0, row_count = 0+ WHERE u.xid <> excluded.xid;+ SELECT * INTO used FROM sys.transaction_usage WHERE pid = pg_backend_pid();+ RETURN used;+END+$$;+REVOKE EXECUTE ON FUNCTION sys._usage() FROM PUBLIC;++CREATE OR REPLACE FUNCTION sys._count_ddl() RETURNS void+LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$+DECLARE+ used sys.transaction_usage := sys._usage();+BEGIN+ IF used.ddl_count >= 1 THEN+ RAISE EXCEPTION USING ERRCODE = '0A000',+ MESSAGE = 'multiple ddl statements not supported in a transaction';+ END IF;+ IF used.dml_count >= 1 THEN+ RAISE EXCEPTION USING ERRCODE = '0A000',+ MESSAGE = 'ddl and dml are not supported in the same transaction',+ DETAIL = format('ddl count: %s, dml count: %s', used.ddl_count + 1, used.dml_count);+ END IF;+ UPDATE sys.transaction_usage SET ddl_count = ddl_count + 1 WHERE pid = pg_backend_pid();+END+$$;++CREATE OR REPLACE FUNCTION sys._count_dml() RETURNS trigger+LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$+DECLARE+ changed bigint;+ used sys.transaction_usage := sys._usage();+BEGIN+ SELECT count(*) INTO changed FROM dsql_rows;+ IF used.ddl_count >= 1 THEN+ RAISE EXCEPTION USING ERRCODE = '0A000',+ MESSAGE = 'ddl and dml are not supported in the same transaction',+ DETAIL = format('ddl count: %s, dml count: %s', used.ddl_count, used.dml_count + 1);+ END IF;+ IF used.row_count + changed > 3000 THEN+ RAISE EXCEPTION USING ERRCODE = '54000', MESSAGE = 'transaction row limit exceeded';+ END IF;+ UPDATE sys.transaction_usage SET dml_count = dml_count + 1, row_count = row_count + changed+ WHERE pid = pg_backend_pid();+ RETURN NULL;+END+$$;++-- Whether the statement running was issued by the sys function named, a pattern for its name and+-- arguments. The call stack says, and a client can put no PL/pgSQL function on it, since DSQL+-- refuses the language, nor change it, as it could a setting.+CREATE OR REPLACE FUNCTION sys._issued_by(function_pattern text) RETURNS boolean+LANGUAGE plpgsql AS $$+DECLARE+ stack text;+BEGIN+ GET DIAGNOSTICS stack = PG_CONTEXT;+ RETURN stack ~ ('(^|\n)PL/pgSQL function (sys\.)?' || function_pattern || ' line ');+END+$$;++-- Every table a client creates gets three statement triggers that count its writes, and gets them+-- back, enabled, after any ALTER TABLE that disabled them. It runs as the table's owner, the only+-- role that can create or alter it.+CREATE OR REPLACE FUNCTION sys._watch_table(relation regclass) RETURNS void+LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp AS $$+DECLARE+ watcher record;+ enabled "char";+BEGIN+ FOR watcher IN SELECT * FROM (VALUES ('dsql_rows_inserted', 'INSERT', 'NEW'), ('dsql_rows_updated', 'UPDATE', 'NEW'),+ ('dsql_rows_deleted', 'DELETE', 'OLD')) AS w (name, event, transition) LOOP+ SELECT t.tgenabled INTO enabled FROM pg_trigger t WHERE t.tgrelid = relation AND t.tgname = watcher.name;+ IF enabled IS NULL THEN+ EXECUTE format('CREATE TRIGGER %I AFTER %s ON %s REFERENCING %s TABLE AS dsql_rows'+ ' FOR EACH STATEMENT EXECUTE FUNCTION sys._count_dml()', watcher.name, watcher.event, relation,+ watcher.transition);+ ELSIF enabled <> 'O' THEN+ EXECUTE format('ALTER TABLE %s ENABLE TRIGGER %I', relation, watcher.name);+ END IF;+ END LOOP;+END+$$;+CREATE OR REPLACE FUNCTION sys._reject(state text, message text, detail text DEFAULT NULL) RETURNS voidLANGUAGE plpgsql AS $$BEGIN@@ -49,6 +225,246 @@ BEGINEND$$;+-- ── What DDL DSQL refuses, read from the catalog ───────────────────────────────++CREATE OR REPLACE FUNCTION sys._on_ddl_start() RETURNS event_trigger+LANGUAGE plpgsql AS $$+BEGIN+ IF sys._issued_by('_watch_table\(regclass\)') THEN+ RETURN;+ END IF;+ IF tg_tag = 'CREATE INDEX' AND NOT sys._issued_by('create_index_async\(text,text,text\)') THEN+ RAISE EXCEPTION USING ERRCODE = '0A000', MESSAGE = 'unsupported mode. please use CREATE INDEX ASYNC.';+ END IF;+ IF tg_tag IN ('CREATE TABLE AS', 'SELECT INTO', 'CREATE MATERIALIZED VIEW') THEN+ RAISE EXCEPTION USING ERRCODE = '0A000', MESSAGE = 'unsupported statement: CreateTableAs';+ END IF;+ IF tg_tag = 'CREATE TRIGGER' THEN+ RAISE EXCEPTION USING ERRCODE = '0A000', MESSAGE = 'CREATE TRIGGER not supported';+ END IF;+ IF tg_tag = 'CREATE TYPE' THEN+ RAISE EXCEPTION USING ERRCODE = '0A000', MESSAGE = 'CREATE TYPE not supported';+ END IF;+ IF tg_tag = 'CREATE EXTENSION' THEN+ RAISE EXCEPTION USING ERRCODE = '0A000', MESSAGE = 'unsupported statement: CreateExtension';+ END IF;+ PERFORM sys._count_ddl();+END+$$;++-- The type a domain stands for, through every domain it is built on; any other type itself.+CREATE OR REPLACE FUNCTION sys._base_type(type_oid oid) RETURNS oid+LANGUAGE sql STABLE SET search_path = pg_catalog, pg_temp AS $$+ WITH RECURSIVE chain AS (+ SELECT t.oid, t.typtype, t.typbasetype FROM pg_type t WHERE t.oid = type_oid+ UNION ALL+ SELECT t.oid, t.typtype, t.typbasetype FROM pg_type t JOIN chain c ON t.oid = c.typbasetype+ WHERE c.typtype = 'd'+ )+ SELECT oid FROM chain WHERE typtype <> 'd'+$$;++CREATE OR REPLACE FUNCTION sys._on_ddl_end() RETURNS event_trigger+LANGUAGE plpgsql AS $$+DECLARE+ command record;+ relation record;+ key_type text;+BEGIN+ IF sys._issued_by('_watch_table\(regclass\)') THEN+ RETURN;+ END IF;+ FOR command IN SELECT * FROM pg_event_trigger_ddl_commands() LOOP+ IF command.object_type IN ('table', 'index') THEN+ SELECT c.relkind, c.relpersistence INTO relation FROM pg_class c WHERE c.oid = command.objid;+ IF relation.relpersistence = 't' THEN+ RAISE EXCEPTION USING ERRCODE = '0A000',+ MESSAGE = 'TEMPORARY or TEMP table not supported for CREATE TABLE';+ END IF;+ IF relation.relkind = 'p' THEN+ RAISE EXCEPTION USING ERRCODE = '0A000',+ MESSAGE = 'PARTITION BY clause not supported for CREATE TABLE';+ END IF;+ IF command.object_type = 'table' THEN+ SELECT format_type(a.atttypid, a.atttypmod) INTO key_type+ FROM pg_attribute a JOIN pg_type t ON t.oid = a.atttypid+ WHERE a.attrelid = command.objid AND a.attnum > 0 AND NOT a.attisdropped AND t.typcategory = 'A'+ LIMIT 1;+ IF key_type IS NOT NULL THEN+ RAISE EXCEPTION USING ERRCODE = '0A000', MESSAGE = format('datatype %s not supported', key_type);+ END IF;+ END IF;+ -- A key may not hold jsonb or bytea: the table's own unique keys, or the index created. The+ -- index's own columns say, expressions included, named as declared, a domain checked+ -- through to its base type (measured).+ SELECT format_type(a.atttypid, a.atttypmod) INTO key_type+ FROM pg_index i+ JOIN pg_attribute a ON a.attrelid = i.indexrelid AND a.attnum BETWEEN 1 AND i.indnkeyatts+ WHERE (i.indrelid = command.objid OR i.indexrelid = command.objid)+ AND sys._base_type(a.atttypid) IN ('jsonb'::regtype, 'bytea'::regtype)+ LIMIT 1;+ IF key_type IS NOT NULL THEN+ RAISE EXCEPTION USING ERRCODE = '0A000', MESSAGE = format('datatype %s is not supported in a key', key_type);+ END IF;+ IF command.object_type = 'table' AND relation.relkind = 'r'+ AND command.command_tag IN ('CREATE TABLE', 'ALTER TABLE') THEN+ PERFORM sys._watch_table(command.objid::regclass);+ END IF;+ ELSIF command.object_type IN ('function', 'procedure') THEN+ IF EXISTS (SELECT 1 FROM pg_proc p JOIN pg_language l ON l.oid = p.prolang+ WHERE p.oid = command.objid AND l.lanname = 'plpgsql') THEN+ RAISE EXCEPTION USING ERRCODE = '0A000',+ MESSAGE = format('CREATE %s with language plpgsql not supported', upper(command.object_type));+ END IF;+ END IF;+ END LOOP;+END+$$;++DROP EVENT TRIGGER IF EXISTS dsql_ddl_start;+CREATE EVENT TRIGGER dsql_ddl_start ON ddl_command_start EXECUTE FUNCTION sys._on_ddl_start();+DROP EVENT TRIGGER IF EXISTS dsql_ddl_end;+CREATE EVENT TRIGGER dsql_ddl_end ON ddl_command_end EXECUTE FUNCTION sys._on_ddl_end();++-- The triggers that count a table's writes do not exist for a client, as no trigger does on DSQL.+CREATE OR REPLACE FUNCTION sys._on_sql_drop() RETURNS event_trigger+LANGUAGE plpgsql AS $$+DECLARE+ dropped record;+BEGIN+ FOR dropped IN SELECT * FROM pg_event_trigger_dropped_objects()+ WHERE original AND object_type = 'trigger' AND address_names[3] LIKE 'dsql\_rows\_%' LOOP+ RAISE EXCEPTION USING ERRCODE = '42704',+ MESSAGE = format('trigger "%s" for table "%s" does not exist', dropped.address_names[3],+ dropped.address_names[2]);+ END LOOP;+END+$$;++DROP EVENT TRIGGER IF EXISTS dsql_sql_drop;+CREATE EVENT TRIGGER dsql_sql_drop ON sql_drop EXECUTE FUNCTION sys._on_sql_drop();++-- ── Asynchronous jobs: CREATE INDEX ASYNC and its job ─────────────────────────++CREATE TABLE IF NOT EXISTS sys.job (+ job_id uuid PRIMARY KEY,+ status "char" NOT NULL,+ details text,+ job_type text,+ class_id oid,+ object_id oid,+ object_name text,+ start_time timestamptz,+ update_time timestamptz+);+GRANT SELECT ON sys.job TO PUBLIC;++CREATE OR REPLACE VIEW sys.jobs AS+SELECT sys.uuid_to_base32_str(job_id) AS job_id,+ CASE status WHEN 's' THEN 'submitted' WHEN 'p' THEN 'processing' WHEN 'c' THEN 'completed'+ WHEN 'f' THEN 'failed' WHEN 'x' THEN 'cancelled' END AS status,+ details, job_type, class_id, object_id, object_name, start_time, update_time+FROM sys.job;+GRANT SELECT ON sys.jobs TO PUBLIC;++-- The job and the invalid index below are written as dbowner, so each first checks that the caller+-- owns the index it names: a client can record or invalidate only what it built itself.+CREATE OR REPLACE FUNCTION sys._require_index_owner(index_oid oid) RETURNS void+LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$+BEGIN+ IF index_oid IS NULL OR NOT coalesce(pg_has_role(session_user,+ (SELECT c.relowner FROM pg_class c WHERE c.oid = index_oid AND c.relkind = 'i'), 'USAGE'), false) THEN+ RAISE EXCEPTION USING ERRCODE = '42501', MESSAGE = 'must be owner of index';+ END IF;+END+$$;++CREATE OR REPLACE FUNCTION sys._record_job(job uuid, state "char", detail text, kind text, object oid,+ object_label text) RETURNS void+LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$+BEGIN+ PERFORM sys._require_index_owner(object);+ INSERT INTO sys.job VALUES (job, state, detail, kind, 1259, object, object_label, now(), clock_timestamp());+END+$$;++-- An index whose build failed stays, invalid, as DSQL leaves it.+CREATE OR REPLACE FUNCTION sys._invalidate_index(index_oid oid) RETURNS void+LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$+BEGIN+ PERFORM sys._require_index_owner(index_oid);+ UPDATE pg_index SET indisvalid = false WHERE indexrelid = index_oid;+END+$$;++-- CREATE INDEX ASYNC, which Floci's endpoint hands here with ASYNC taken out: the index is built at+-- once, and a job records it. A unique index over duplicate keys fails its job.+CREATE OR REPLACE FUNCTION sys.create_index_async(statement text, index_name text, table_name text)+RETURNS TABLE (job_id text)+LANGUAGE plpgsql AS $$+DECLARE+ job uuid := gen_random_uuid();+ target regclass := to_regclass(table_name);+ schema_name text;+ index_oid oid;+BEGIN+ -- Floci's rewrite of CREATE INDEX ASYNC hands one index statement here; anything else, a+ -- client calling this function itself included, is not one, and EXECUTE would run every+ -- statement a ; separates.+ IF statement !~* '^\s*CREATE\s+(UNIQUE\s+)?INDEX\s' OR position(';' IN statement) > 0 THEN+ RAISE EXCEPTION USING ERRCODE = '42883',+ MESSAGE = 'function sys.create_index_async(text, text, text) does not exist';+ END IF;+ SELECT n.nspname INTO schema_name FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE c.oid = target;+ BEGIN+ EXECUTE statement;+ SELECT i.indexrelid INTO index_oid FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid+ WHERE i.indrelid = target AND (index_name IS NULL OR c.relname = index_name)+ ORDER BY i.indexrelid DESC LIMIT 1;+ PERFORM sys._record_job(job, 'c', NULL, 'INDEX_BUILD', index_oid,+ coalesce(schema_name, current_schema()) || '.' || coalesce(index_name, (SELECT relname FROM pg_class WHERE oid = index_oid)));+ EXCEPTION WHEN unique_violation THEN+ EXECUTE regexp_replace(statement, '^\s*CREATE\s+UNIQUE\s+INDEX', 'CREATE INDEX', 'i');+ SELECT i.indexrelid INTO index_oid FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid+ WHERE i.indrelid = target AND (index_name IS NULL OR c.relname = index_name)+ ORDER BY i.indexrelid DESC LIMIT 1;+ PERFORM sys._invalidate_index(index_oid);+ PERFORM sys._record_job(job, 'f', 'found duplicate key(s) while validating index uniqueness',+ 'INDEX_BUILD', index_oid,+ coalesce(schema_name, current_schema()) || '.' || coalesce(index_name, (SELECT relname FROM pg_class WHERE oid = index_oid)));+ END;+ RETURN QUERY SELECT sys.uuid_to_base32_str(job);+END+$$;++-- DSQL's own procedure, as its catalog holds it.+CREATE OR REPLACE PROCEDURE sys.wait_for_job(IN job_uuid_base32 text, INOUT succeeded boolean DEFAULT false)+LANGUAGE plpgsql AS $$+DECLARE+job_uuid uuid := sys.base32_str_to_uuid(job_uuid_base32);+BEGIN+LOOP+ IF EXISTS (SELECT 1 FROM sys.job WHERE job_id = job_uuid AND status = 'c') THEN+ RAISE NOTICE 'Job execution succeeded for job with id %', job_uuid_base32;+ succeeded := true;+ EXIT;+ ELSIF (SELECT 1 FROM sys.job WHERE job_id = job_uuid AND status = 'f') THEN+ RAISE NOTICE 'Job execution failed for job with id %', job_uuid_base32;+ succeeded := false;+ EXIT;+ ELSIF EXISTS (SELECT 1 FROM sys.job WHERE job_id = job_uuid AND status = 'x') THEN+ RAISE NOTICE 'Job execution was cancelled for job with id %', job_uuid_base32;+ succeeded := false;+ EXIT;+ END IF;+ PERFORM pg_sleep(1);+ COMMIT;+END LOOP;+RETURN;+END;+$$;+-- ── AWS IAM GRANT and REVOKE: which IAM role may log in as which database role ─CREATE TABLE IF NOT EXISTS sys.iam_identity (@@ -113,6 +529,7 @@ DECLAREidentity bigint;granted_by text;BEGIN+ PERFORM sys._count_ddl();IF iam_arn !~ '^arn:aws[a-z-]*:iam::[0-9]{12}:(role|user)/.+' THENRAISE EXCEPTION USING ERRCODE = '0P000', MESSAGE = 'IAM role must look like an IAM ARN';END IF;@@ -139,6 +556,7 @@ DECLARErole_oid oid;identity bigint;BEGIN+ PERFORM sys._count_ddl();IF iam_arn !~ '^arn:aws[a-z-]*:iam::[0-9]{12}:(role|user)/.+' THENRAISE EXCEPTION USING ERRCODE = '0P000', MESSAGE = 'IAM role must look like an IAM ARN';END IF;@@ -164,14 +582,29 @@ LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$WHERE r.rolname = role_name$$;+-- A statement on roles, which DSQL counts as DDL (measured) though PostgreSQL fires no event trigger+-- for one: CREATE or ALTER ROLE, USER or GROUP, and GRANT or REVOKE of a role, which Floci's+-- endpoint hands here, counted, then run as the caller. Anything else is not one of them.+CREATE OR REPLACE PROCEDURE sys.run_role_ddl(statement text)+LANGUAGE plpgsql AS $$+BEGIN+ IF statement !~* '^\s*((CREATE|ALTER)\s+(ROLE|USER|GROUP)|GRANT|REVOKE)\s' OR position(';' IN statement) > 0 THEN+ RAISE EXCEPTION USING ERRCODE = '42883', MESSAGE = 'procedure sys.run_role_ddl(text) does not exist';+ END IF;+ PERFORM sys._count_ddl();+ EXECUTE statement;+END+$$;+-- DROP ROLE, USER or GROUP, which Floci's endpoint hands here: refused for a mapped role, otherwise--- run as the caller.+-- counted as DDL and run as the caller.CREATE OR REPLACE PROCEDURE sys.drop_roles(role_names text[], missing_ok boolean)LANGUAGE plpgsql AS $$DECLARErole_name text;trust text;BEGIN+ PERFORM sys._count_ddl();FOREACH role_name IN ARRAY role_names LOOPtrust := sys._trust_relationships(role_name);IF trust IS NOT NULL THEN@@ -188,3 +621,17 @@ $$;REVOKE ALL ON sys.iam_identity, sys.iam_auth_member FROM PUBLIC;REVOKE EXECUTE ON FUNCTION sys._trusted_role(text, text, text) FROM PUBLIC;REVOKE EXECUTE ON PROCEDURE sys._forget_dropped_roles() FROM PUBLIC;++-- A table created before these triggers existed counts its writes from now on too.+DO $$+DECLARE+ relation regclass;+BEGIN+ FOR relation IN SELECT c.oid::regclass FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE c.relkind = 'r' AND n.nspname NOT IN ('pg_catalog', 'information_schema', 'sys')+ AND n.nspname NOT LIKE 'pg_toast%' AND n.nspname NOT LIKE 'pg_temp%' LOOP+ PERFORM sys._watch_table(relation);+ END LOOP;+END+$$;+RESET session_replication_role;diff --git a/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlClusterFixture.java b/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlClusterFixture.javanew file mode 100644index 0000000000..0e8076ab96--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlClusterFixture.java@@ -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");+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlDataPlaneIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlDataPlaneIntegrationTest.javaindex 3e1b0760e1..61ae7780e7 100644--- a/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlDataPlaneIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlDataPlaneIntegrationTest.java@@ -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 static io.restassured.RestAssured.given;-import static org.awaitility.Awaitility.await;+import java.util.concurrent.CompletableFuture;+import java.util.concurrent.TimeUnit;++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";@InjectDockerClient dockerClient;@@ -80,35 +68,22 @@ class DsqlDataPlaneIntegrationTest {@RegisterExtensionfinal PartitionCleanup cleanup = new PartitionCleanup();- private String identifier;- private String host;+ private DsqlClusterFixture cluster;@BeforeAllvoid 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);}@AfterAllvoid deleteCluster() {- if (identifier != null) {- dsql().delete("/cluster/" + identifier);- await().atMost(Duration.ofMinutes(1)).until(() ->- dsql().get("/cluster/" + identifier).then().extract().statusCode() == 404);- }+ cluster.delete();}@Testvoid 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 {@Testvoid 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 {@Testvoid 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 {@Testvoid 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 {*/@Testvoid 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");+ }+ }+@Testvoid 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 {@Testvoid 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,106 +392,234 @@ class DsqlDataPlaneIntegrationTest {}}- /**- * 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.- */@Test- void aLongTermKeySignsInOnlyToItsOwnAccountsClusters() throws Exception {- 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());- 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);+ 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");}- out.flush();+ 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();}+ }- /** 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 -> {- }- }+ /**+ * 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");}+ }- @Override- public void close() throws IOException {- socket.close();+ /**+ * 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();}}- private static byte[] query(String sql) throws IOException {- return message('Q', PostgresWire.cStringBytes(sql));- }+ @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));+ }- private static byte[] parse(String statement, String sql) throws IOException {- return message('P', PostgresWire.cStringBytes(statement), PostgresWire.cStringBytes(sql), new byte[2]);+ 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());+ }}- /** 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]);+ @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());+ }}- private static byte[] execute() throws IOException {- return message('E', PostgresWire.cStringBytes(""), PostgresWire.int32(0));+ @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();+ }+ }}- private static byte[] close(String statement) throws IOException {- return message('C', new byte[] {'S'}, PostgresWire.cStringBytes(statement));- }+ /**+ * 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.+ */+ @Test+ void aLongTermKeySignsInOnlyToItsOwnAccountsClusters() throws Exception {+ EnforcementFixtures.UserCredentials own = accessKey(ACCOUNT);+ EnforcementFixtures.UserCredentials other = accessKey("000000000000");- private static byte[] sync() throws IOException {- return message('S');+ 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());}- 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");- }}diff --git a/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlWireClient.java b/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlWireClient.javanew file mode 100644index 0000000000..c8a0a3f8c0--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/dsql/DsqlWireClient.java@@ -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();+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlSessionTest.java b/src/test/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlSessionTest.javaindex f52535e49e..3315f1fdeb 100644--- a/src/test/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlSessionTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlSessionTest.java@@ -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"));diff --git a/src/test/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlStatementsTest.java b/src/test/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlStatementsTest.javaindex 30dac8b657..ca49356338 100644--- a/src/test/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlStatementsTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlStatementsTest.java@@ -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());+ }+@Testvoid 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());+ }+@Testvoid aQueryWithNothingToRewriteGoesToTheDatabaseExactlyAsSent() {String query = "-- comment\nSELECT 1;\n/* two */ SELECT 'a;b';";diff --git a/src/test/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlTransactionAgeIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlTransactionAgeIntegrationTest.javanew file mode 100644index 0000000000..4d047951d1--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/dsql/dataplane/DsqlTransactionAgeIntegrationTest.java@@ -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);+ }+}