mirror of
https://github.com/floci-io/floci.git
synced 2026-11-29 16:35:29 -05:00
feat(dsql): speak DSQL's dialect and keep its transaction limits (#6185)
* feat(dsql): speak DSQL's dialect and keep its transaction limits The third part of the DSQL data plane, after #6102 and #6143: the cluster's database answers the way Aurora DSQL does, as measured on AWS. CREATE [UNIQUE] INDEX ASYNC answers a job_id, with sys.jobs and sys.wait_for_job; a plain CREATE INDEX is refused. What DSQL refuses is refused with its SQLSTATE and message: what the statement shows (TRUNCATE, DO, LISTEN, VACUUM, sequence caches, isolation levels, locking clauses, advisory locks, ADD CONSTRAINT) in DsqlStatements, and what only the catalog can tell (column types, a function's language, temporary and partitioned tables, triggers) inside the database, by event triggers, since the statement alone cannot say. A transaction runs one DDL statement, never with DML, and modifies at most 3,000 rows, a cascade's included. Its age follows what was measured with a client that only reads: the client's next message after 300 seconds ends it with 54000 and closes the connection with 08P01, an idle one is ended unasked 15 seconds later, a statement running across the limit completes and then fails with 54000, and a failed transaction left idle as long is closed with 25P03. A first model, the age checked at the next statement, was dropped once the reading client showed DSQL's own timer. A write conflict is DSQL's 40001 OC000, and an error's context keeps the statement a cascade ran while dropping what sys functions ran. * fix(dsql): close the dialect's gaps found in review, as measured on DSQL Measured on Aurora DSQL before each change: - set_config of default_transaction_isolation or transaction_isolation, a quoted SET of one and ALTER ROLE ... SET of one answer 0A000 "not supported"; ALTER DATABASE ... SET or RESET is AlterDatabaseSet. - CREATE TABLE AS, SELECT INTO and materialized views are CreateTableAs, refused by the event trigger so a function body cannot reach them either. - An expression key, or a domain over jsonb or bytea, is refused like the type itself, named as declared: the check reads the index's own columns and follows a domain to its base type. - CREATE, ALTER and DROP ROLE and GRANT or REVOKE of a role are DDL. PostgreSQL fires no event trigger for them, so they run through sys.run_role_ddl, which counts them first, under PostgreSQL's tags. - A statement past the transaction age limit fails with 54000, in a transaction block or not, nothing its transaction wrote is kept, and the rest of its query, a COMMIT included, does not run. The age limit is reworked as the review asked. Each session has one check scheduled at a time, on the endpoint's scheduler and by the injected Clock, cancelled when the transaction or the connection ends; a failed transaction's idle wait restarts after every client message. At the limit a statement still running is cancelled with the client's own cancel request, and its 57014 reaches the client as DSQL's 54000. DSQL lets the statement finish and fails it then; stopping it at the limit ends the same way. Two other ways were tried and dropped: dropping a late statement's answer in the relay let a COMMIT in the same query commit, and a mark the endpoint writes for the database to check is invisible to the client's repeatable read snapshot. The age test now moves the clock and holds a row instead of sleeping, and shares its cluster setup with the data plane test through DsqlClusterFixture. Also fixed: a -- comment ends at a carriage return, a quoted advisory lock name is refused, CACHE is read from tokens rather than the raw text, a BEGIN queued behind a long statement starts once that statement is answered, tables that predate the counting triggers get them, and sys.create_index_async runs one index statement and nothing else. sys.wait_for_job with an unknown id keeps waiting, as DSQL's does.
This commit is contained in:
1 parent
6355474ad2
commit
42fd858311
12 files changed
+2220
-309
No files matched your search
@@ -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 {
|
||||
|
||||
@Inject
|
||||
public 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 {
|
||||
|
||||
@PreDestroy
|
||||
public 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 action
|
||||
|
||||
+345
-73
@@ -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)));
|
||||
}
|
||||
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));
|
||||
}
|
||||
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);
|
||||
}
|
||||
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));
|
||||
}
|
||||
PostgresWire.write(backendOut, message);
|
||||
}
|
||||
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);
|
||||
}
|
||||
case 'X' -> {
|
||||
PostgresWire.write(backendOut, message);
|
||||
backendOut.flush();
|
||||
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;
|
||||
}
|
||||
default -> PostgresWire.write(backendOut, message);
|
||||
if (message.type() == 'Q' || message.type() == 'S' || message.type() == 'F') {
|
||||
awaitingReady.incrementAndGet();
|
||||
}
|
||||
}
|
||||
if (in.available() == 0) {
|
||||
backendOut.flush();
|
||||
synchronized (databaseWrites) {
|
||||
if (relayOne(message, backendOut)) {
|
||||
return;
|
||||
}
|
||||
if (in.available() == 0) {
|
||||
backendOut.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 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));
|
||||
}
|
||||
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()));
|
||||
}
|
||||
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));
|
||||
}
|
||||
PostgresWire.write(backendOut, message);
|
||||
}
|
||||
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 'Z' -> {
|
||||
synchronized (batches) {
|
||||
batches.pollFirst();
|
||||
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) {
|
||||
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) {
|
||||
|
||||
+287
-8
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user