Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

feat(dsql): partial indexes, `dsql.enable_batched_nestloop`, extended statistics limits, and bound `sys.wait_for_job` (#1990)

Edoardo Viviani859abaceb39a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 169a518c..da49bc0b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,18 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Added
+
+- **Aurora DSQL — partial indexes** — `CREATE INDEX ASYNC ... WHERE predicate` was refused `0A000` although the service supports it since 2026-09-15; the predicate now reaches the backend and builds a real partial index (unique partial indexes scope uniqueness to the rows they cover). A predicate calling a volatile function fails at submit with `42P17` "functions in index predicate must be marked IMMUTABLE", and a subquery with `0A000`, instead of coming back as a failed job; both are checked in the order the live service uses (eu-central-1, 2026-10-04). Contributed by @vivedo.
+- **Aurora DSQL — `dsql.enable_batched_nestloop` and the reserved `dsql.` prefix** — the session setting added with batched nested-loop joins (2026-09-11) shows `on` before any `SET`, `RESET` returns to `on`, and a non-Boolean value (through `SET` or `set_config`) or a value list is refused `22023` in the service's wording. Any other `dsql.*` name is refused `42602` with the service's "reserved prefix" detail, and `work_mem`, `statement_timeout` and `default_statistics_target` can no longer be set (`0A000`), as on the live service. Plans stay Postgres-shaped: no `Nested Loop (Batched Join)` node. Contributed by @vivedo.
+- **Aurora DSQL — extended statistics limits** — `CREATE STATISTICS` reached the backend without a cap; a sixth object on a table now fails with the service's `54000` "more than 5 extended statistics per table are not allowed", after the statement's own errors and with `IF NOT EXISTS` on an existing name still a no-op. Statistics targets above 100 are refused (`22023`) and `ALTER TABLE ... ALTER COLUMN ... SET STATISTICS` is refused (`0A000`), in the service's wordings. Contributed by @vivedo.
+
+### Fixed
+
+- **Aurora DSQL — the 8-key index limit comes first** — measured live, DSQL reports `54011` before the mode, key-expression and `INCLUDE` rules; the proxy reported those first, so a plain `CREATE INDEX` on nine columns drew "unsupported mode". `sys.jobs.details` is now NULL for a job that succeeded, where it was an empty string. Contributed by @vivedo.
+- **Aurora DSQL — `CALL sys.wait_for_job($1)` with a bound job id** — a job id bound as a parameter over the extended protocol went through to the backing Postgres and failed `3F000` schema "sys" does not exist, after the index had been built. Bound job ids now work for `sys.wait_for_job` and for `sys.jobs ... WHERE job_id = $1`, and `CALL` answers the procedure's `succeeded` column with the `CALL` tag, as measured on the live service (eu-central-1, 2026-10-04); a malformed id is refused `22P02`. `CREATE INDEX ASYNC` and `ALTER TABLE ASYNC` answer the `CREATE INDEX` / `ALTER TABLE` tags, `sys.jobs` declares its `oid` and `timestamptz` columns, a constraint validation job carries `class_id` 2606, and a unique index that fails on duplicates reports the service's `details`. Contributed by @vivedo.
+- **Aurora DSQL — `TimeZone` missing at startup** — the proxy's startup greeting reported no `TimeZone`, so a driver that decodes `timestamptz` by it could stall on the first value; it now reports `TimeZone`, `IntervalStyle` and the rest of the parameters the live service does. Contributed by @vivedo.
+
### Fixed
- **Lambda — throttle `retryAfterSeconds` is a string** — a `TooManyRequestsException` returns `retryAfterSeconds` as a string, as the Lambda API model declares, so SDK clients such as the AWS SDK for Rust parse the response as a throttle.
diff --git a/README.md b/README.md
index 915bd695..11f1e463 100644
--- a/README.md
+++ b/README.md
@@ -696,7 +696,7 @@ only `DeleteDBCluster` removes the container and its storage.
Each `CreateCluster` returns an `ACTIVE` cluster with an endpoint. Set `DSQL_STRICT=1` to additionally spin up a real `postgres:16-alpine` container per cluster (capped by a fixed port window off `DSQL_BASE_PORT`, default 30 ports) behind an in-process Postgres wire-protocol proxy.
-**The proxy fails like real DSQL**: SQL that DSQL rejects fails here too (`serial` columns, `CREATE EXTENSION`, `TRUNCATE`, temp tables, `ALTER COLUMN TYPE`, `SET NOT NULL`, materialized views, partitioned tables, ...), index creation is always asynchronous — plain `CREATE INDEX` is refused (`unsupported mode. please use CREATE INDEX ASYNC.`), as are `CONCURRENTLY`, `USING` and partial (`WHERE`) indexes — while expression index keys are supported as long as the functions used are immutable (violations fail with `42P17`, same as the backend; `INCLUDE` columns can't be expressions), `CREATE INDEX ASYNC` and `ALTER TABLE ASYNC ... VALIDATE CONSTRAINT` return a `job_id`, `sys.jobs` / `sys.wait_for_job` are emulated (data that does not satisfy the constraint fails the job, not the submit — `sys.jobs` reports it `failed` with the violation as `details`), CHECK and FOREIGN KEY constraints via ALTER TABLE require `NOT VALID` and every other `ADD CONSTRAINT` form is refused, `ADD COLUMN` takes a name, a type and an optional `STORAGE` mode and nothing else, foreign keys are supported in full (all five referential actions, `MATCH FULL`/`MATCH SIMPLE`, deferrable — `DEFERRABLE` on any other kind of constraint is refused), `ALTER TABLE ... DROP COLUMN` works (several columns in one statement included) except on a primary key column, identity columns are bigint-only (CACHE 1 or ≥ 65536), index limits are enforced (8 key columns/index, 24/table), transactions allow only one DDL statement with no DDL+DML mixing, `SELECT ... FOR UPDATE` and `FOR KEY SHARE` are the only locking clauses supported (`FOR SHARE` and `FOR NO KEY UPDATE` are refused, at any nesting depth; the predicate itself is unrestricted), a transaction that outlives another session's DDL fails once with `40001` (OC001) and succeeds on retry, and the transaction limits (3,000 rows / 10 MiB / 5 min) are enforced.
+**The proxy fails like real DSQL**: SQL that DSQL rejects fails here too (`serial` columns, `CREATE EXTENSION`, `TRUNCATE`, temp tables, `ALTER COLUMN TYPE`, `SET NOT NULL`, materialized views, partitioned tables, ...), index creation is always asynchronous — plain `CREATE INDEX` is refused (`unsupported mode. please use CREATE INDEX ASYNC.`), as are `CONCURRENTLY` and `USING` — while expression index keys and partial indexes (`WHERE` predicate) are supported as long as the functions used are immutable (violations fail with `42P17` at submit, same as the backend; `INCLUDE` columns can't be expressions, the predicate can't hold a subquery), `CREATE INDEX ASYNC` and `ALTER TABLE ASYNC ... VALIDATE CONSTRAINT` return a `job_id`, `sys.jobs` / `sys.wait_for_job` are emulated (with the job id written literally or bound as `$1`; `CALL sys.wait_for_job` answers DSQL's `succeeded` column) (data that does not satisfy the constraint fails the job, not the submit — `sys.jobs` reports it `failed` with the violation as `details`), CHECK and FOREIGN KEY constraints via ALTER TABLE require `NOT VALID` and every other `ADD CONSTRAINT` form is refused, `ADD COLUMN` takes a name, a type and an optional `STORAGE` mode and nothing else, foreign keys are supported in full (all five referential actions, `MATCH FULL`/`MATCH SIMPLE`, deferrable — `DEFERRABLE` on any other kind of constraint is refused), `ALTER TABLE ... DROP COLUMN` works (several columns in one statement included) except on a primary key column, identity columns are bigint-only (CACHE 1 or ≥ 65536), index limits are enforced (8 key columns/index — checked before anything but `CONCURRENTLY`/`USING`, even the mode — 24/table), `CREATE`/`ALTER`/`DROP STATISTICS` work with DSQL's 5-per-table limit and statistics targets capped at 100 (`ALTER TABLE ... SET STATISTICS` is refused), `dsql.enable_batched_nestloop` defaults to `on` and takes only Boolean values, the rest of the `dsql.` prefix is reserved (`42602`), `work_mem`, `statement_timeout` and `default_statistics_target` can't be set, transactions allow only one DDL statement with no DDL+DML mixing, `SELECT ... FOR UPDATE` and `FOR KEY SHARE` are the only locking clauses supported (`FOR SHARE` and `FOR NO KEY UPDATE` are refused, at any nesting depth; the predicate itself is unrestricted), a transaction that outlives another session's DDL fails once with `40001` (OC001) and succeeds on retry, and the transaction limits (3,000 rows / 10 MiB / 5 min) are enforced.
CDC streams are metadata only: `CreateStream` validates its Kinesis target definition, enforces the 5-streams-per-cluster quota (`ServiceQuotaExceededException`) and reports `ACTIVE` right away, but no change record is ever delivered — a target whose Kinesis stream is absent (or, with `AUTH=true`, whose role cannot be assumed) lands `FAILED` with the service's `statusReason` code instead. Deleting a cluster deletes its streams.
@@ -704,7 +704,7 @@ CDC streams are metadata only: `CreateStream` validates its Kinesis target defin
**Both wire protocols are validated**: the simple protocol (psql, psycopg2) and the extended `Parse`/`Bind`/`Execute` protocol used by pgjdbc, pgx, asyncpg, psycopg3 and every ORM built on prepared statements. Transaction state is read from the backend's `ReadyForQuery` status byte rather than inferred from statement text, so `BEGIN`/`COMMIT` sent over either protocol keeps the transaction rules accurate. A statement the proxy rejects inside a transaction aborts that block exactly as a real error would — later statements fail with `25P02` and `COMMIT` reports `ROLLBACK`.
-Limitations: SQL analysis is heuristic regex, not a real parser (statement splitting, comment stripping and parenthesis matching are lexer-aware, but clause-level rules are pattern matches); the proxy's immutability check for index expressions is a denylist of well-known volatile functions — the backend catalog enforces the rest; transaction row counting is static (VALUES tuples only — `INSERT ... SELECT`/UPDATE/DELETE row counts aren't tracked); OC001 emulation is optimistic (catalog version bumps on forwarded DDL, not on successful commit); foreign keys are enforced by the backend, so a referencing write racing a change to the referenced key waits on a row lock instead of failing the loser with `40001` (OC000) the way DSQL's optimistic resolution does; the 1 KiB PK/index key-size limit is not enforced; and in a pipelined extended-protocol batch (several statements before one `Sync`) the rules that need to inspect backend state — the 24-index limit and the `FOR UPDATE` key check — are skipped, while `CREATE INDEX ASYNC` is rejected as it is in multi-statement `Q` batches. Error messages match live Aurora DSQL where verified, otherwise Postgres-style approximations (`0A000`, `25006`).
+Limitations: SQL analysis is heuristic regex, not a real parser (statement splitting, comment stripping and parenthesis matching are lexer-aware, but clause-level rules are pattern matches); the proxy's immutability check for index expressions and predicates is a denylist of well-known volatile functions — the backend catalog enforces the rest; transaction row counting is static (VALUES tuples only — `INSERT ... SELECT`/UPDATE/DELETE row counts aren't tracked); OC001 emulation is optimistic (catalog version bumps on forwarded DDL, not on successful commit); foreign keys are enforced by the backend, so a referencing write racing a change to the referenced key waits on a row lock instead of failing the loser with `40001` (OC000) the way DSQL's optimistic resolution does; the 1 KiB PK/index key-size limit is not enforced; and in a pipelined extended-protocol batch (several statements before one `Sync`) the rules that need to inspect backend state — the 24-index and 5-statistics limits and the primary-key `DROP COLUMN` check — are skipped; `EXPLAIN` output is Postgres-shaped, not DSQL's plan nodes (`Full Scan (btree-table)`, `Nested Loop (Batched Join)`, ...); `dsql.*` settings are Postgres placeholders, so they're missing from `pg_settings`; DSQL refuses more settings than the three listed above (only those were measured), while `CREATE INDEX ASYNC` is rejected as it is in multi-statement `Q` batches. Error messages match live Aurora DSQL where verified, otherwise Postgres-style approximations (`0A000`, `25006`).
---
diff --git a/ministack/core/pgproxy.py b/ministack/core/pgproxy.py
index 226ed074..6f9270fa 100644
--- a/ministack/core/pgproxy.py
+++ b/ministack/core/pgproxy.py
@@ -61,13 +61,23 @@ _GSSENC_REQUEST = 80877104
_CANCEL_REQUEST = 80877102
_PROTOCOL_3 = 196608
+# ParameterStatus sent at startup. Drivers depend on these: one that decodes
+# timestamptz by TimeZone can stall on the first value without it. Values
+# as real DSQL reports them (measured, eu-central-1 2026-10-04), bar the
+# per-session session_authorization.
_STARTUP_PARAMS = (
("server_version", "16.4"),
("server_encoding", "UTF8"),
("client_encoding", "UTF8"),
- ("DateStyle", "ISO"),
+ ("DateStyle", "ISO, MDY"),
+ ("IntervalStyle", "postgres"),
+ ("TimeZone", "UTC"),
("integer_datetimes", "on"),
("standard_conforming_strings", "on"),
+ ("application_name", ""),
+ ("is_superuser", "off"),
+ ("default_transaction_read_only", "off"),
+ ("in_hot_standby", "off"),
)
_TEXT_OID = 25
@@ -77,11 +87,12 @@ def _frame(type_byte, payload):
return type_byte + struct.pack("!I", len(payload) + 4) + payload
-def _error_response(sqlstate, message):
+def _error_response(sqlstate, message, detail=None):
payload = (
b"SERROR\0VERROR\0"
+ b"C" + sqlstate.encode() + b"\0"
+ b"M" + message.encode() + b"\0"
+ + (b"D" + detail.encode() + b"\0" if detail else b"")
+ b"\0"
)
return _frame(b"E", payload)
@@ -140,12 +151,39 @@ _proxies = {} # cluster_id -> asyncio.Server
_jobs = {} # cluster_id -> [job dict]
_catalog_versions = {} # cluster_id -> int, bumped on every DDL statement
-_ID_ALPHABET = string.ascii_lowercase + string.digits
+# DSQL job ids are 26 base32 characters (a UUID); wait_for_job refuses any
+# other text with 22P02 "Unable to convert text to UUID".
+_ID_ALPHABET = string.ascii_lowercase + "234567"
_JOB_COLUMNS = (
"job_id", "status", "details", "job_type", "class_id", "object_id",
"object_name", "start_time", "update_time",
)
+# Column types sys.jobs declares on real DSQL (measured, eu-central-1
+# 2026-10-04); the rest are text. Drivers decode values by these oids.
+_OID_OID, _TIMESTAMPTZ_OID = 26, 1184
+_JOB_COLUMN_TYPES = {
+ "class_id": _OID_OID, "object_id": _OID_OID,
+ "start_time": _TIMESTAMPTZ_OID, "update_time": _TIMESTAMPTZ_OID,
+}
+# Catalog a job's object lives in: pg_class for an index, pg_constraint for
+# a constraint validation.
+_JOB_CLASS_IDS = {"INDEX_BUILD": "1259", "VALIDATE_CONSTRAINT": "2606"}
+# What CREATE INDEX ASYNC / ALTER TABLE ASYNC answer, as on real DSQL.
+_JOB_COMMAND_TAGS = {"INDEX_BUILD": "CREATE INDEX", "VALIDATE_CONSTRAINT": "ALTER TABLE"}
+
+
+def _pg_timestamptz(value):
+ """Postgres' text output for a UTC timestamptz (DSQL keeps whole seconds).
+
+ Jobs persisted by older versions hold ISO 8601 strings; they render the
+ same way.
+ """
+ if isinstance(value, str) and "T" in value:
+ value = datetime.fromisoformat(value)
+ if isinstance(value, datetime):
+ return value.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M:%S+00")
+ return value
def get_jobs(cluster_id):
@@ -169,14 +207,14 @@ def _bump_catalog(cluster_id):
def _register_job(cluster_id, object_name, job_type="INDEX_BUILD",
- status="completed", details=""):
- now = datetime.now(timezone.utc).isoformat()
+ status="completed", details=None):
+ now = _pg_timestamptz(datetime.now(timezone.utc))
job = {
"job_id": "".join(secrets.choice(_ID_ALPHABET) for _ in range(26)),
"status": status,
"details": details,
"job_type": job_type,
- "class_id": "1259",
+ "class_id": _JOB_CLASS_IDS.get(job_type, "1259"),
"object_id": str(16384 + secrets.randbelow(100000)),
"object_name": object_name,
"start_time": now,
@@ -389,9 +427,10 @@ def _sql_tokens(sql):
class DsqlError:
"""Validator rejection: rendered as a PG ErrorResponse."""
- def __init__(self, sqlstate, message):
+ def __init__(self, sqlstate, message, detail=None):
self.sqlstate = sqlstate
self.message = message
+ self.detail = detail
def __repr__(self):
return f"DsqlError({self.sqlstate!r}, {self.message!r})"
@@ -873,6 +912,12 @@ def _check_alter_table(sql):
return DsqlError(
"0A000", "SET NOT NULL is not supported (only DROP NOT NULL)"
)
+ if re.search(r"\bALTER\s+(?:COLUMN\s+)?[\w\"]+\s+SET\s+STATISTICS\b", sql, re.I):
+ # Exact message from real DSQL (eu-central-1, 2026-10-04).
+ return DsqlError(
+ "0A000",
+ "unsupported ALTER TABLE ALTER COLUMN ... SET STATISTICS statement",
+ )
add = re.search(r"\bADD\s+(?:CONSTRAINT\s+[\w\"]+\s+)?(\w+)", sql, re.I)
if add and add.group(1).upper() != "COLUMN":
what = add.group(1).upper()
@@ -1014,14 +1059,20 @@ def _check_cache_value(sql):
# DSQL index rules, verified against a live Aurora DSQL cluster (Aug 2026):
# index creation is always asynchronous — plain CREATE INDEX fails with
-# "unsupported mode". No CONCURRENTLY, no USING (not even btree), no partial
-# (WHERE). IF NOT EXISTS requires a name (grammar). Expression index keys are
-# supported, but every function must be immutable (42P17) and INCLUDE columns
-# can't be expressions. At most 8 key columns per index (54011); 24 indexes
-# per table is enforced at runtime.
+# "unsupported mode". No CONCURRENTLY, no USING (not even btree). IF NOT
+# EXISTS requires a name (grammar). Expression index keys are supported, but
+# every function must be immutable (42P17) and INCLUDE columns can't be
+# expressions. At most 8 key columns per index (54011); 24 indexes per table
+# is enforced at runtime.
#
-# Error precedence (observed on real DSQL): name-grammar → CONCURRENTLY →
-# USING → WHERE → mode → key-expression rules → key count.
+# Partial indexes (WHERE predicate) are supported since 2026-09-15. The
+# predicate follows the same immutability rule as key expressions; the proxy
+# checks it up front so a bad predicate fails the submit, not the job.
+#
+# Error precedence (measured, eu-central-1 2026-10-04): name-grammar →
+# CONCURRENTLY → USING → key count → mode → predicate (subquery, then
+# immutability) → key-expression immutability → INCLUDE expressions. The key
+# count comes before the mode: a plain CREATE INDEX on 9 columns draws 54011.
_VOLATILE_FUNCTIONS = frozenset({
"now", "random", "setseed", "nextval", "currval", "lastval", "setval",
"gen_random_uuid", "uuid_generate_v1", "uuid_generate_v4",
@@ -1042,29 +1093,37 @@ def _check_index_rules(sql):
return DsqlError("0A000", "CONCURRENTLY not supported for CREATE INDEX")
if re.search(r"\bUSING\s+\w+", sql, re.I):
return DsqlError("0A000", "USING not supported for CREATE INDEX")
- if re.search(r"\bWHERE\b", sql, re.I):
- return DsqlError("0A000", "WHERE not supported for CREATE INDEX")
+ start = sql.find("(", m.end())
+ end = _match_paren(sql, start) if start >= 0 else -1
+ parts = _split_top_level(sql[start + 1 : end]) if end > 0 else []
+ if len(parts) > 8:
+ return DsqlError(
+ "54011", "more than 8 column keys in an index are not supported"
+ )
if not _INDEX_ASYNC_RE.match(sql):
return DsqlError(
"0A000", "unsupported mode. please use CREATE INDEX ASYNC."
)
- start = sql.find("(", m.end())
- if start < 0:
- return None
- end = _match_paren(sql, start)
if end < 0:
return None
- parts = _split_top_level(sql[start + 1 : end])
- for part in parts:
- for fn in re.findall(r"(\w+)\s*\(", part):
- if fn.lower() in _VOLATILE_FUNCTIONS:
- # Same code/message the backend (and real DSQL) produce; the
- # proxy fails fast so CREATE INDEX ASYNC rejects at submit
- # time instead of returning a job_id.
- return DsqlError(
- "42P17",
- "functions in index expression must be marked IMMUTABLE",
- )
+ # Neither INCLUDE (...) nor NULLS [NOT] DISTINCT can hold a WHERE, so the
+ # first one after the key list starts the partial-index predicate.
+ pred = re.search(r"\bWHERE\b", sql[end + 1 :], re.I)
+ if pred:
+ predicate = sql[end + 1 + pred.end() :]
+ if re.search(r"\bSELECT\b", _strip_literals(predicate), re.I):
+ return DsqlError("0A000", "cannot use subquery in index predicate")
+ if _calls_volatile_function(predicate):
+ return DsqlError(
+ "42P17", "functions in index predicate must be marked IMMUTABLE"
+ )
+ if any(_calls_volatile_function(part) for part in parts):
+ # Same code/message the backend (and real DSQL) produce; the proxy
+ # fails fast so CREATE INDEX ASYNC rejects at submit time instead of
+ # returning a job_id.
+ return DsqlError(
+ "42P17", "functions in index expression must be marked IMMUTABLE"
+ )
# INCLUDE columns are non-key: expressions are not supported there.
inc = re.search(r"\bINCLUDE\s*\(", sql[end:], re.I)
if inc:
@@ -1076,13 +1135,20 @@ def _check_index_rules(sql):
return DsqlError(
"0A000", "expressions are not supported in included columns"
)
- if len(parts) > 8:
- return DsqlError(
- "54011", "more than 8 column keys in an index are not supported"
- )
return None
+def _strip_literals(text):
+ return re.sub(r"'(?:[^']|'')*'", "''", text)
+
+
+def _calls_volatile_function(text):
+ return any(
+ fn.lower() in _VOLATILE_FUNCTIONS
+ for fn in re.findall(r"(\w+)\s*\(", _strip_literals(text))
+ )
+
+
_ALTER_ASYNC_VALIDATE_RE = re.compile(
r"\s*ALTER\s+TABLE\s+ASYNC\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?"
r"([\w\".]+)\s*\*?\s*VALIDATE\s+CONSTRAINT\s+([\w\"]+)",
@@ -1149,12 +1215,29 @@ def _index_object_name(sql, on_end, index_name, table):
# --- sys.jobs / sys.wait_for_job (rules 5 & 6) ------------------------------
_SYS_JOBS_RE = re.compile(r"\s*SELECT\s+(.+?)\s+FROM\s+sys\.jobs\b", re.I | re.S)
-_JOB_ID_FILTER_RE = re.compile(r"job_id\s*=\s*'([^']*)'", re.I)
+_JOB_ID_FILTER_RE = re.compile(
+ r"job_id\s*=\s*(?:'([^']*)'|\$(\d+))(?:\s*::\s*\w+)?", re.I
+)
_WAIT_JOB_RE = re.compile(
- r"\s*(?:SELECT|CALL)\s+sys\.wait_for_job\s*\(\s*"
- r"(?:job_id\s*\)\s*'([^']*)'|'([^']*)'\s*\))",
+ r"\s*(SELECT|CALL)\s+sys\.wait_for_job\s*\(\s*"
+ r"(?:job_id\s*\)\s*'([^']*)'|'([^']*)'(?:\s*::\s*\w+)?\s*\)"
+ r"|\$(\d+)(?:\s*::\s*\w+)?\s*\))",
re.I,
)
+_JOB_ID_RE = re.compile(r"[a-z2-7]{26}")
+
+
+class BindParam:
+ """A ``$n`` placeholder whose value only arrives with Bind."""
+
+ def __init__(self, index):
+ self.index = index
+
+ def __eq__(self, other):
+ return isinstance(other, BindParam) and other.index == self.index
+
+ def __repr__(self):
+ return f"BindParam({self.index})"
def match_sys_jobs(sql):
@@ -1171,16 +1254,29 @@ def match_sys_jobs(sql):
if select_list != "*":
columns = [c.strip().strip('"') for c in select_list.split(",")]
f = _JOB_ID_FILTER_RE.search(sql)
- return columns, (f.group(1) if f else None)
+ if not f:
+ return columns, None
+ return columns, (BindParam(int(f.group(2))) if f.group(2) else f.group(1))
def match_wait_for_job(sql):
- """Match both documented call forms: ``sys.wait_for_job(job_id) '<id>'``
- and the conventional ``sys.wait_for_job('<id>')``."""
+ """The job id ``sys.wait_for_job`` is called with, or None.
+
+ A ``BindParam`` when the id is a ``$n`` placeholder (the client binds it
+ over the extended protocol). Accepts the literal forms
+ ``sys.wait_for_job('<id>')`` and ``sys.wait_for_job(job_id) '<id>'``.
+ """
m = _WAIT_JOB_RE.match(sql)
if not m:
return None
- return m.group(1) or m.group(2)
+ if m.group(4):
+ return BindParam(int(m.group(4)))
+ return m.group(2) or m.group(3)
+
+
+def _wait_is_call(sql):
+ m = _WAIT_JOB_RE.match(sql)
+ return bool(m) and m.group(1).upper() == "CALL"
# --- Locking clauses (measured against Aurora DSQL, 2026-08-18) -------------
@@ -1222,6 +1318,108 @@ def _check_locking_clause(sql):
# --- Top-level validator -----------------------------------------------------
+# DSQL-specific planner settings (all boolean). Postgres takes any dotted name
+# as an untyped placeholder, so the backend would accept SET ... = 'banana';
+# real DSQL rejects it. The backend container starts with each one set to its
+# DSQL default (dsql.py), so SHOW and RESET behave too.
+DSQL_SETTINGS = {
+ "dsql.enable_batched_nestloop": "on", # 2026-09-11
+}
+
+# Settings DSQL refuses to change (SET, SET LOCAL, set_config); RESET and
+# SET ... TO DEFAULT are accepted. Observed, not exhaustive (eu-central-1,
+# 2026-10-04): planner switches like enable_hashjoin and search_path are
+# settable.
+_UNSETTABLE_PARAMS = frozenset({
+ "default_statistics_target", "statement_timeout", "work_mem",
+})
+
+_SET_RE = re.compile(
+ r"\s*SET\s+(?:SESSION\s+|LOCAL\s+)?([\w.]+)\s*(?:=|\bTO\b)\s*(.*?)\s*;?\s*$",
+ re.I | re.S,
+)
+_RESET_RE = re.compile(r"\s*RESET\s+([\w.]+)", re.I)
+_SET_CONFIG_RE = re.compile(
+ r"\bset_config\s*\(\s*'([^']*)'\s*,\s*'((?:[^']|'')*)'", re.I
+)
+
+
+def _parse_pg_bool(value):
+ """Postgres parse_bool: case-insensitive unique prefixes, plus 1/0."""
+ v = value.strip().lower()
+ if v in ("1", "0"):
+ return True
+ if len(v) >= 2 and v in ("on", "off"[: len(v)]):
+ return True
+ return bool(v) and any(w.startswith(v) for w in ("true", "false", "yes", "no"))
+
+
+def _check_setting(name, values):
+ """Rules for one assignment; ``values`` is None for RESET / TO DEFAULT."""
+ name = name.lower()
+ if name.startswith("dsql.") and name not in DSQL_SETTINGS:
+ # Exact message and detail from real DSQL (eu-central-1, 2026-10-04).
+ return DsqlError(
+ "42602",
+ f'invalid configuration parameter name "{name}"',
+ '"dsql" is a reserved prefix.',
+ )
+ if values is None:
+ return None
+ if name in _UNSETTABLE_PARAMS:
+ return DsqlError(
+ "0A000", f'setting configuration parameter "{name}" not supported'
+ )
+ if name in DSQL_SETTINGS and values:
+ if len(values) > 1:
+ return DsqlError("22023", f"SET {name} takes only one argument")
+ if not _parse_pg_bool(values[0]):
+ return DsqlError("22023", f'parameter "{name}" requires a Boolean value')
+ return None
+
+
+def _unquote(value):
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"":
+ return value[1:-1]
+ return value
+
+
+_ALTER_STATISTICS_TARGET_RE = re.compile(
+ r"\s*ALTER\s+STATISTICS\s+.+?\s+SET\s+STATISTICS\s+(-?\d+)", re.I | re.S
+)
+
+
+def _check_statistics_target(sql):
+ """DSQL caps statistics targets at 100 (Postgres allows 10000)."""
+ m = _ALTER_STATISTICS_TARGET_RE.match(sql)
+ if m and int(m.group(1)) > 100:
+ # Exact message from real DSQL (eu-central-1, 2026-10-04).
+ return DsqlError(
+ "22023",
+ f"statistics target {m.group(1)} exceeds maximum allowed value of 100",
+ )
+ return None
+
+
+def _check_settings(sql):
+ m = _SET_RE.match(sql)
+ if m:
+ raw = m.group(2)
+ values = (
+ None if raw.upper() == "DEFAULT"
+ else [_unquote(v.strip()) for v in _split_top_level(raw)]
+ )
+ return _check_setting(m.group(1), values)
+ m = _RESET_RE.match(sql)
+ if m:
+ return _check_setting(m.group(1), None)
+ for name, value in _SET_CONFIG_RE.findall(sql):
+ err = _check_setting(name, [value.replace("''", "'")])
+ if err:
+ return err
+ return None
+
+
def validate(sql, txn_state=None):
"""Validate one statement. Returns DsqlError | Rewrite | None.
@@ -1291,6 +1489,12 @@ def validate(sql, txn_state=None):
if err:
return err
err = _check_locking_clause(s)
+ if err:
+ return err
+ err = _check_settings(s)
+ if err:
+ return err
+ err = _check_statistics_target(s)
if err:
return err
@@ -1433,13 +1637,18 @@ async def _index_count(conn, b_writer, table):
schema, _, bare = table.rpartition(".")
schema = schema.strip('"') or "public"
bare = bare.strip('"')
+ return await _probe_count(
+ conn,
+ b_writer,
+ "SELECT count(*) FROM pg_indexes "
+ f"WHERE schemaname = '{schema}' AND tablename = '{bare}'",
+ )
+
+
+async def _probe_count(conn, b_writer, query):
+ """Run a single-integer probe on the backend. None on probe error."""
try:
- frames = await _run_backend_capture(
- conn,
- b_writer,
- "SELECT count(*) FROM pg_indexes "
- f"WHERE schemaname = '{schema}' AND tablename = '{bare}'",
- )
+ frames = await _run_backend_capture(conn, b_writer, query)
except Exception:
return None
for type_byte, payload in frames:
@@ -1474,7 +1683,7 @@ def _reject(conn, c_writer, err):
"""
if conn.txn.in_txn:
conn.txn.synthetic_abort = True
- c_writer.write(_error_response(err.sqlstate, err.message) + _ready(_status(conn)))
+ c_writer.write(_error_response(err.sqlstate, err.message, err.detail) + _ready(_status(conn)))
_ABORTED_ERR = DsqlError(
@@ -1599,11 +1808,106 @@ async def _check_drop_column(conn, b_writer, sql):
return None
+# At most 5 extended statistics objects per table (AWS DSQL, 2026-08-27).
+# Message and SQLSTATE measured on real DSQL (eu-central-1, 2026-10-04).
+_CREATE_STATISTICS_RE = re.compile(
+ r"\s*CREATE\s+STATISTICS\b.*\bFROM\s+([\w\".]+)\s*;?\s*$", re.I | re.S
+)
+_STATISTICS_LIMIT_ERR = DsqlError(
+ "54000", "more than 5 extended statistics per table are not allowed"
+)
+
+
+async def _check_statistics_limit(conn, b_writer, sql):
+ m = _CREATE_STATISTICS_RE.match(sql)
+ if not m:
+ return None
+ # regclass resolves the name the way the backend will (search_path,
+ # quoting); an unknown table fails the probe and the backend answers.
+ count_sql = (
+ "SELECT count(*) FROM pg_statistic_ext "
+ f"WHERE stxrelid = '{m.group(1)}'::regclass"
+ )
+ before = await _probe_count(conn, b_writer, count_sql)
+ if before is None or before < 5:
+ return None
+ # At the limit, dry-run the statement and roll it back. DSQL reports the
+ # statement's own errors (fewer than two columns, an unknown column) ahead
+ # of the limit, and IF NOT EXISTS on an existing name is still a no-op;
+ # only a statement that would really add a sixth object is refused.
+ if conn.txn.in_txn:
+ begin = "SAVEPOINT ministack_statistics"
+ undo = (
+ "ROLLBACK TO SAVEPOINT ministack_statistics; "
+ "RELEASE SAVEPOINT ministack_statistics"
+ )
+ else:
+ begin, undo = "BEGIN", "ROLLBACK"
+ after = None
+ await _run_backend_capture(conn, b_writer, begin)
+ try:
+ frames = await _run_backend_capture(conn, b_writer, sql)
+ if not any(t == b"E" for t, _ in frames):
+ after = await _probe_count(conn, b_writer, count_sql)
+ finally:
+ await _run_backend_capture(conn, b_writer, undo)
+ if after is not None and after > before:
+ return _STATISTICS_LIMIT_ERR
+ return None
+
+
_ASYNC_BATCH_ERR = DsqlError(
"0A000", "asynchronous DDL is not supported in multi-statement queries"
)
+def _sys_jobs_rows(conn, cols, job_filter):
+ jobs = get_jobs(conn.cluster_id)
+ if job_filter is not None:
+ jobs = [j for j in jobs if j["job_id"] == job_filter]
+ return {
+ "cols": [(c, _JOB_COLUMN_TYPES.get(c, _TEXT_OID)) for c in cols],
+ "rows": [
+ [_pg_timestamptz(job[c]) if c.endswith("_time") else job[c] for c in cols]
+ for job in jobs
+ ],
+ "tag": f"SELECT {len(jobs)}",
+ }
+
+
+def _wait_columns(call):
+ # Real DSQL: wait_for_job is a procedure whose one OUT parameter is
+ # ``succeeded`` (bool), so CALL answers a "succeeded" column and the CALL
+ # tag (measured, eu-central-1 2026-10-04). The SELECT form, which DSQL
+ # refuses with 42809, is kept as a lenient alias.
+ return [("succeeded" if call else "wait_for_job", 16)] # bool oid
+
+
+def _wait_for_job_rows(conn, job_id, call):
+ if call and (job_id is None or not _JOB_ID_RE.fullmatch(job_id)):
+ return DsqlError("22P02", "Unable to convert text to UUID")
+ known = any(
+ j["job_id"] == job_id and j["status"] == "completed"
+ for j in get_jobs(conn.cluster_id)
+ )
+ return {
+ "cols": _wait_columns(call),
+ "rows": [["t" if known else "f"]],
+ "tag": "CALL" if call else "SELECT 1",
+ }
+
+
+def _deferred(cols, param, resolve):
+ """A synthetic result that needs a bound parameter: resolved at Bind."""
+ return {
+ "cols": cols,
+ "nparams": param.index,
+ "resolve": lambda params: resolve(
+ params[param.index - 1] if len(params) >= param.index else None
+ ),
+ }
+
+
async def _plan_statement(conn, s, b_writer, allow_probe=True):
"""Decide what to do with one statement, for either wire protocol.
@@ -1625,26 +1929,25 @@ async def _plan_statement(conn, s, b_writer, allow_probe=True):
bad = [c for c in cols if c not in _JOB_COLUMNS]
if bad:
return "error", DsqlError("42703", f'column "{bad[0]}" does not exist')
- jobs = get_jobs(conn.cluster_id)
- if job_filter:
- jobs = [j for j in jobs if j["job_id"] == job_filter]
- return "rows", {
- "cols": cols,
- "rows": [[job[c] for c in cols] for job in jobs],
- "tag": f"SELECT {len(jobs)}",
- }
+ if isinstance(job_filter, BindParam):
+ return "rows", _deferred(
+ [(c, _JOB_COLUMN_TYPES.get(c, _TEXT_OID)) for c in cols],
+ job_filter, lambda v: _sys_jobs_rows(conn, cols, v),
+ )
+ return "rows", _sys_jobs_rows(conn, cols, job_filter)
job_id = match_wait_for_job(s)
if job_id is not None:
- known = any(
- j["job_id"] == job_id and j["status"] == "completed"
- for j in get_jobs(conn.cluster_id)
- )
- return "rows", {
- "cols": [("wait_for_job", 16)], # bool oid
- "rows": [["t" if known else "f"]],
- "tag": "SELECT 1",
- }
+ call = _wait_is_call(s)
+ if isinstance(job_id, BindParam):
+ return "rows", _deferred(
+ _wait_columns(call), job_id,
+ lambda v: _wait_for_job_rows(conn, v, call),
+ )
+ result = _wait_for_job_rows(conn, job_id, call)
+ if isinstance(result, DsqlError):
+ return "error", result
+ return "rows", result
result = validate(s, conn.txn)
if isinstance(result, DsqlError):
@@ -1665,6 +1968,9 @@ async def _plan_statement(conn, s, b_writer, allow_probe=True):
err = await _check_drop_column(conn, b_writer, s)
if err:
return "error", err
+ err = await _check_statistics_limit(conn, b_writer, s)
+ if err:
+ return "error", err
return "forward", None
@@ -1721,6 +2027,9 @@ async def _run_rewrite(conn, b_writer, rewrite):
# unresolvable relation, a syntax error — is refused on the spot. In a
# transaction the backend is left aborted, so relay there either way.
if sqlstate.startswith("23") and not conn.txn.in_txn:
+ if sqlstate == "23505" and rewrite.job_type == "INDEX_BUILD":
+ # DSQL's own wording (measured, eu-central-1 2026-10-04).
+ message = "found duplicate key(s) while validating index uniqueness"
job = _register_job(
conn.cluster_id, rewrite.object_name, rewrite.job_type,
status="failed", details=message,
@@ -1743,7 +2052,7 @@ async def _handle_query(conn, sql, b_writer, c_writer):
err, forward_sql = _abort_gate(conn, s)
if err:
c_writer.write(
- _error_response(err.sqlstate, err.message) + _ready(_status(conn))
+ _error_response(err.sqlstate, err.message, err.detail) + _ready(_status(conn))
)
await c_writer.drain()
return
@@ -1762,6 +2071,11 @@ async def _handle_query(conn, sql, b_writer, c_writer):
return
kind, result = await _plan_statement(conn, s, b_writer)
+ if kind == "rows" and "resolve" in result:
+ # A $n placeholder means nothing outside the extended protocol.
+ kind, result = "error", DsqlError(
+ "42P02", f"there is no parameter ${result['nparams']}"
+ )
if kind == "error":
_reject(conn, c_writer, result)
await c_writer.drain()
@@ -1787,7 +2101,7 @@ async def _handle_query(conn, sql, b_writer, c_writer):
return
out = _row_description(["job_id"])
out += _data_row([job["job_id"]])
- out += _command_complete("SELECT 1")
+ out += _command_complete(_JOB_COMMAND_TAGS.get(result.job_type, "SELECT 1"))
c_writer.write(out + _ready(_status(conn)))
await c_writer.drain()
return
@@ -1895,7 +2209,7 @@ async def _ext_error(conn, c_writer, err):
if conn.txn.in_txn:
conn.txn.synthetic_abort = True
conn.ext_skip = True
- c_writer.write(_error_response(err.sqlstate, err.message))
+ c_writer.write(_error_response(err.sqlstate, err.message, err.detail))
await c_writer.drain()
@@ -1954,14 +2268,46 @@ async def _ext_bind(conn, payload, b_writer, c_writer):
if entry is None:
await _ext_forward(conn, b_writer, b"B", payload)
return
- conn.ext_portals[portal] = entry
if entry["synth"] is None:
+ conn.ext_portals[portal] = entry
await _ext_forward(conn, b_writer, b"B", payload)
return
+ kind, result = entry["synth"]
+ if kind == "rows" and "resolve" in result:
+ resolved = result["resolve"](_bind_params(payload))
+ if isinstance(resolved, DsqlError):
+ await _ext_error(conn, c_writer, resolved)
+ return
+ entry = {**entry, "synth": ("rows", resolved)}
+ conn.ext_portals[portal] = entry
c_writer.write(_frame(b"2", b"")) # BindComplete
await c_writer.drain()
+def _bind_params(payload):
+ """Parameter values of a Bind payload, as text (None for NULL)."""
+ try:
+ i = payload.index(b"\0")
+ i = payload.index(b"\0", i + 1) + 1
+ (nfmt,) = struct.unpack("!H", payload[i : i + 2])
+ i += 2 + 2 * nfmt
+ (nparams,) = struct.unpack("!H", payload[i : i + 2])
+ i += 2
+ values = []
+ for _ in range(nparams):
+ (vlen,) = struct.unpack("!i", payload[i : i + 4])
+ i += 4
+ if vlen < 0:
+ values.append(None)
+ continue
+ # A job id is text; its binary encoding is the same UTF-8 bytes.
+ values.append(payload[i : i + vlen].decode("utf-8", "replace"))
+ i += vlen
+ return values
+ except (ValueError, struct.error):
+ return []
+
+
async def _ext_describe(conn, payload, b_writer, c_writer):
target, name = _target_name(payload)
store = conn.ext_stmts if target == b"S" else conn.ext_portals
@@ -1971,7 +2317,10 @@ async def _ext_describe(conn, payload, b_writer, c_writer):
return
out = b""
if target == b"S":
- out += _frame(b"t", struct.pack("!H", 0)) # ParameterDescription
+ nparams = entry["synth"][1].get("nparams", 0)
+ out += _frame( # ParameterDescription: every placeholder is text
+ b"t", struct.pack("!H", nparams) + struct.pack("!I", 25) * nparams
+ )
out += _row_description(_synth_columns(*entry["synth"]))
c_writer.write(out)
await c_writer.drain()
@@ -2001,7 +2350,10 @@ async def _ext_execute(conn, payload, b_writer, c_writer):
c_writer.write(_frame(b"E", backend_err))
await c_writer.drain()
return
- c_writer.write(_data_row([job["job_id"]]) + _command_complete("SELECT 1"))
+ c_writer.write(
+ _data_row([job["job_id"]])
+ + _command_complete(_JOB_COMMAND_TAGS.get(result.job_type, "SELECT 1"))
+ )
await c_writer.drain()
diff --git a/ministack/services/dsql.py b/ministack/services/dsql.py
index 7b788bd0..b0f36ada 100644
--- a/ministack/services/dsql.py
+++ b/ministack/services/dsql.py
@@ -43,6 +43,13 @@ BASE_PORT = int(os.environ.get("DSQL_BASE_PORT", "25432"))
# served metadata-only.
_BACKEND_PORT_WINDOW = 30
PG_IMAGE = os.environ.get("DSQL_PG_IMAGE", "postgres:16-alpine")
+# DSQL-only settings start at their DSQL defaults, so SHOW works before any
+# SET and RESET returns to the DSQL value rather than an empty placeholder.
+PG_COMMAND = ["postgres"] + [
+ arg
+ for name, default in pgproxy.DSQL_SETTINGS.items()
+ for arg in ("-c", f"{name}={default}")
+]
DSQL_PERSIST = os.environ.get("DSQL_PERSIST", "0").lower() in ("1", "true", "yes")
# Backend containers are opt-in: default is control-plane-only (metadata stubs).
DSQL_STRICT = os.environ.get("DSQL_STRICT", "0").lower() in ("1", "true", "yes")
@@ -242,6 +249,7 @@ def _run_backend_container(identifier):
ms_network = rds._get_ministack_network(docker_client)
container_kwargs = dict(
image=PG_IMAGE,
+ command=PG_COMMAND,
detach=True,
environment={
"POSTGRES_USER": "postgres",
diff --git a/tests/test_dsql.py b/tests/test_dsql.py
index 5f9c71ad..0693fc32 100644
--- a/tests/test_dsql.py
+++ b/tests/test_dsql.py
@@ -1205,10 +1205,6 @@ class TestIndexLimits:
"USING not supported for CREATE INDEX"),
("CREATE INDEX ASYNC i ON t USING btree (a)", "0A000",
"USING not supported for CREATE INDEX"),
- ("CREATE INDEX i ON t (a) WHERE a > 0", "0A000",
- "WHERE not supported for CREATE INDEX"),
- ("CREATE INDEX ASYNC i ON t (a) WHERE a > 0", "0A000",
- "WHERE not supported for CREATE INDEX"),
# plain (synchronous) mode is rejected outright, empty table or not
("CREATE INDEX i ON t (a)", "0A000",
"unsupported mode. please use CREATE INDEX ASYNC."),
@@ -1228,6 +1224,42 @@ class TestIndexLimits:
"expressions are not supported in included columns"),
("CREATE UNIQUE INDEX ASYNC i ON t (a) INCLUDE ((b + c))", "0A000",
"included columns"),
+ # partial indexes: plain mode still needs ASYNC
+ ("CREATE INDEX i ON t (a) WHERE a > 0", "0A000",
+ "unsupported mode. please use CREATE INDEX ASYNC."),
+ # the predicate must be immutable too (Postgres' own message)
+ ("CREATE INDEX ASYNC i ON t (a) WHERE created > now()", "42P17",
+ "functions in index predicate must be marked IMMUTABLE"),
+ ("CREATE INDEX ASYNC i ON t (a) INCLUDE (b) WHERE random() < 0.5",
+ "42P17", "index predicate"),
+ ("CREATE INDEX ASYNC i ON t (a) WHERE b IN (SELECT id FROM u)",
+ "0A000", "cannot use subquery in index predicate"),
+ # Precedence measured on real DSQL (eu-central-1, 2026-10-04):
+ # key count -> mode -> predicate -> key expressions -> INCLUDE.
+ ("CREATE INDEX i ON t (a,b,c,d,e,f,g,h,i)", "54011",
+ "more than 8 column keys"),
+ ("CREATE INDEX i ON t (now(),a,b,c,d,e,f,g,h)", "54011",
+ "more than 8 column keys"),
+ ("CREATE INDEX ASYNC i ON t (now(),a,b,c,d,e,f,g,h)", "54011",
+ "more than 8 column keys"),
+ ("CREATE INDEX ASYNC i ON t (a,b,c,d,e,f,g,h,i) INCLUDE ((b + c))",
+ "54011", "more than 8 column keys"),
+ ("CREATE INDEX ASYNC i ON t (a,b,c,d,e,f,g,h,i) WHERE b IN (SELECT 1)",
+ "54011", "more than 8 column keys"),
+ ("CREATE INDEX CONCURRENTLY i ON t (a,b,c,d,e,f,g,h,i)", "0A000",
+ "CONCURRENTLY"),
+ ("CREATE INDEX i ON t (a) WHERE random() < 0.5", "0A000",
+ "unsupported mode"),
+ ("CREATE INDEX i ON t (a) INCLUDE ((b + c))", "0A000",
+ "unsupported mode"),
+ ("CREATE INDEX ASYNC i ON t (now()) WHERE random() < 0.5", "42P17",
+ "index predicate"),
+ ("CREATE INDEX ASYNC i ON t (now()) WHERE b IN (SELECT 1)", "0A000",
+ "subquery"),
+ ("CREATE INDEX ASYNC i ON t (a) INCLUDE ((b + c)) WHERE random() < 0.5",
+ "42P17", "index predicate"),
+ ("CREATE INDEX ASYNC i ON t (now()) INCLUDE ((b + c))", "42P17",
+ "index expression"),
],
)
def test_unsupported_index_forms_denied(self, sql, sqlstate, message):
@@ -1246,12 +1278,27 @@ class TestIndexLimits:
"CREATE INDEX ASYNC i ON t (lower(email))",
"CREATE INDEX ASYNC i ON t ((data->>'city'))",
"CREATE INDEX ASYNC ON t (upper(title), (a + b) NULLS LAST)",
+ # partial indexes (AWS DSQL, 2026-09-15)
+ "CREATE INDEX ASYNC high_rating_idx ON films (title) WHERE rating > 5",
+ "CREATE UNIQUE INDEX ASYNC i ON t (email) WHERE NOT archived",
+ "CREATE UNIQUE INDEX ASYNC i ON t (a) INCLUDE (b) NULLS NOT DISTINCT "
+ "WHERE status = 'active'",
+ "CREATE INDEX ASYNC i ON t (lower(title)) WHERE deleted_at IS NULL",
+ # function names and keywords inside literals aren't calls
+ "CREATE INDEX ASYNC i ON t (a) WHERE note <> 'now() or SELECT'",
],
)
def test_supported_index_forms_allowed(self, sql):
result = pgproxy.validate(sql, pgproxy.TxnState())
assert isinstance(result, pgproxy.Rewrite), sql
+ def test_partial_index_predicate_reaches_the_backend(self):
+ result = pgproxy.validate(
+ "CREATE INDEX ASYNC i ON t (a) WHERE a > 0", pgproxy.TxnState()
+ )
+ assert result.sql == "CREATE INDEX i ON t (a) WHERE a > 0"
+ assert result.job_type == "INDEX_BUILD"
+
def test_more_than_8_columns_denied(self):
err = pgproxy.validate(
"CREATE INDEX ASYNC i ON t (a,b,c,d,e,f,g,h,i)", pgproxy.TxnState()
@@ -1267,6 +1314,150 @@ class TestIndexLimits:
assert isinstance(result, pgproxy.Rewrite)
+class TestDsqlSettings:
+ """dsql.* planner settings (dsql.enable_batched_nestloop, 2026-09-11)."""
+
+ @pytest.mark.parametrize(
+ "sql",
+ [
+ "SET dsql.enable_batched_nestloop = off",
+ "SET dsql.enable_batched_nestloop TO on",
+ "SET SESSION dsql.enable_batched_nestloop = 'false'",
+ "SET LOCAL dsql.enable_batched_nestloop = true",
+ "set dsql.enable_batched_nestloop = 0;",
+ "SET dsql.enable_batched_nestloop = of", # unique prefix of off
+ "SET dsql.enable_batched_nestloop = y",
+ "SET dsql.enable_batched_nestloop TO DEFAULT",
+ 'SET dsql.enable_batched_nestloop = "on"',
+ "SET DSQL.ENABLE_BATCHED_NESTLOOP = OFF",
+ "RESET dsql.enable_batched_nestloop",
+ "SHOW dsql.enable_batched_nestloop",
+ "SELECT set_config('dsql.enable_batched_nestloop', 'off', false)",
+ # Ordinary settings DSQL lets a session change.
+ "SET enable_hashjoin = off",
+ "SET search_path = public",
+ # Refused settings can still be reset.
+ "RESET default_statistics_target",
+ "SET default_statistics_target TO DEFAULT",
+ ],
+ )
+ def test_accepted(self, sql):
+ assert pgproxy.validate(sql, pgproxy.TxnState()) is None, sql
+
+ def test_value_list_rejected(self):
+ err = pgproxy.validate(
+ "SET dsql.enable_batched_nestloop = on, off", pgproxy.TxnState()
+ )
+ assert (err.sqlstate, err.message) == (
+ "22023", "SET dsql.enable_batched_nestloop takes only one argument",
+ )
+
+ def test_set_config_validates_the_value(self):
+ err = pgproxy.validate(
+ "SELECT set_config('dsql.enable_batched_nestloop', 'banana', false)",
+ pgproxy.TxnState(),
+ )
+ assert err.sqlstate == "22023"
+ assert "requires a Boolean value" in err.message
+
+ @pytest.mark.parametrize(
+ "sql",
+ [
+ "SET dsql.bogus = 1",
+ "SET LOCAL dsql.bogus = 1",
+ "SET SESSION dsql.bogus TO 1",
+ "RESET dsql.bogus",
+ "SET dsql.bogus TO DEFAULT",
+ "SELECT set_config('dsql.bogus', '1', false)",
+ ],
+ )
+ def test_dsql_prefix_is_reserved(self, sql):
+ # Exact message and detail from real DSQL (eu-central-1, 2026-10-04).
+ err = pgproxy.validate(sql, pgproxy.TxnState())
+ assert err.sqlstate == "42602", sql
+ assert err.message == 'invalid configuration parameter name "dsql.bogus"'
+ assert err.detail == '"dsql" is a reserved prefix.'
+
+ @pytest.mark.parametrize(
+ "sql,param",
+ [
+ ("SET default_statistics_target = 200", "default_statistics_target"),
+ ("SET LOCAL default_statistics_target = 50", "default_statistics_target"),
+ ("SELECT set_config('default_statistics_target', '50', false)",
+ "default_statistics_target"),
+ ("SET work_mem = '64MB'", "work_mem"),
+ ("SET statement_timeout = '5s'", "statement_timeout"),
+ ],
+ )
+ def test_unsettable_parameters_rejected(self, sql, param):
+ err = pgproxy.validate(sql, pgproxy.TxnState())
+ assert err.sqlstate == "0A000", sql
+ assert err.message == f'setting configuration parameter "{param}" not supported'
+
+ @pytest.mark.parametrize(
+ "value", ["banana", "'maybe'", "2", "o", "''", "onn"],
+ )
+ def test_non_boolean_rejected(self, value):
+ err = pgproxy.validate(
+ f"SET dsql.enable_batched_nestloop = {value}", pgproxy.TxnState()
+ )
+ assert isinstance(err, pgproxy.DsqlError), value
+ assert err.sqlstate == "22023"
+ assert err.message == (
+ 'parameter "dsql.enable_batched_nestloop" requires a Boolean value'
+ )
+
+ def test_backend_starts_with_dsql_defaults(self):
+ from ministack.services import dsql as dsql_mod
+
+ assert dsql_mod.PG_COMMAND == [
+ "postgres", "-c", "dsql.enable_batched_nestloop=on",
+ ]
+
+
+class TestStatisticsRules:
+ """Extended statistics (AWS DSQL, 2026-08-27); messages measured live."""
+
+ @pytest.mark.parametrize("target", ["100", "-1", "0"])
+ def test_statistics_target_up_to_100_allowed(self, target):
+ sql = f"ALTER STATISTICS s SET STATISTICS {target}"
+ assert pgproxy.validate(sql, pgproxy.TxnState()) is None
+
+ def test_statistics_target_over_100_rejected(self):
+ err = pgproxy.validate(
+ "ALTER STATISTICS s SET STATISTICS 101", pgproxy.TxnState()
+ )
+ assert (err.sqlstate, err.message) == (
+ "22023", "statistics target 101 exceeds maximum allowed value of 100",
+ )
+
+ @pytest.mark.parametrize(
+ "sql",
+ [
+ "ALTER TABLE t ALTER COLUMN a SET STATISTICS 50",
+ "ALTER TABLE t ALTER a SET STATISTICS 200",
+ ],
+ )
+ def test_column_statistics_target_rejected(self, sql):
+ err = pgproxy.validate(sql, pgproxy.TxnState())
+ assert (err.sqlstate, err.message) == (
+ "0A000",
+ "unsupported ALTER TABLE ALTER COLUMN ... SET STATISTICS statement",
+ )
+
+ @pytest.mark.parametrize(
+ "sql",
+ [
+ "CREATE STATISTICS s1 (dependencies) ON a, b FROM t",
+ "CREATE STATISTICS ON (lower(a)) FROM public.t",
+ "ALTER STATISTICS s1 RENAME TO s2",
+ "DROP STATISTICS s1",
+ ],
+ )
+ def test_statements_pass_text_validation(self, sql):
+ assert pgproxy.validate(sql, pgproxy.TxnState()) is None
+
+
class TestWaitForJob:
def test_documented_form(self):
sql = "SELECT sys.wait_for_job(job_id) 'abc123'"
@@ -1283,6 +1474,33 @@ class TestWaitForJob:
assert pgproxy.match_wait_for_job("SELECT 1") is None
assert pgproxy.match_wait_for_job("SELECT sys.wait_for_job(job_id)") is None
+ @pytest.mark.parametrize(
+ "sql",
+ [
+ "CALL sys.wait_for_job($1)",
+ "CALL sys.wait_for_job( $1::text )",
+ "SELECT sys.wait_for_job($1)",
+ ],
+ )
+ def test_bound_parameter_form(self, sql):
+ # A client that binds the job id over the extended protocol sends
+ # the statement text as ...($1).
+ assert pgproxy.match_wait_for_job(sql) == pgproxy.BindParam(1)
+
+ def test_literal_with_cast(self):
+ sql = "CALL sys.wait_for_job('abc123'::text)"
+ assert pgproxy.match_wait_for_job(sql) == "abc123"
+
+ def test_sys_jobs_bound_filter(self):
+ assert pgproxy.match_sys_jobs(
+ "SELECT job_id, status FROM sys.jobs WHERE job_id = $2"
+ ) == (["job_id", "status"], pgproxy.BindParam(2))
+
+ def test_job_ids_are_base32(self):
+ job = pgproxy._register_job("idtest", "public.i")
+ assert re.fullmatch(r"[a-z2-7]{26}", job["job_id"])
+ pgproxy._jobs.pop("idtest", None)
+
class TestReset:
def test_reset_stops_proxies_and_clears_jobs(self):
@@ -1694,8 +1912,11 @@ def pg_backend(pg_image):
docker = pytest.importorskip("docker")
psycopg2 = pytest.importorskip("psycopg2")
client = docker.from_env()
+ from ministack.services import dsql as dsql_mod
+
container = client.containers.run(
image=pg_image,
+ command=dsql_mod.PG_COMMAND,
detach=True,
environment={
"POSTGRES_USER": "postgres",
@@ -1839,7 +2060,7 @@ class _WireClient:
params = f"user\0{user}\0database\0{database}\0\0".encode()
payload = struct.pack("!I", 196608) + params
self.sock.sendall(struct.pack("!I", len(payload) + 4) + payload)
- self._until_ready()
+ self.startup = self._until_ready()
def __enter__(self):
return self
@@ -1911,9 +2132,19 @@ class _WireResult:
self.sqlstate = None
self.message = None
self.rows = []
+ self.columns = [] # (name, type oid) from RowDescription
self.tag = None
self.txn_status = None
for type_byte, payload in frames:
+ if type_byte == b"T":
+ (n,) = struct.unpack("!H", payload[:2])
+ off = 2
+ for _ in range(n):
+ end = payload.index(b"\0", off)
+ name = payload[off:end].decode()
+ (oid,) = struct.unpack("!I", payload[end + 7 : end + 11])
+ self.columns.append((name, oid))
+ off = end + 19
if type_byte == b"E":
for part in payload.split(b"\0"):
if part[:1] == b"C":
@@ -2288,6 +2519,156 @@ class TestLockingReads:
assert result.ok, f"{result.sqlstate} {result.message}"
+@requires_docker
+class TestWaitForJobOverTheWire:
+ """``CALL sys.wait_for_job`` as drivers send it. Shapes measured on Aurora
+ DSQL (eu-central-1, 2026-10-04): one bool OUT column named ``succeeded``,
+ command tag ``CALL``, with a literal or a bound ``$1`` alike."""
+
+ def _job(self, c, table, unique=False, dup=False):
+ c.simple(f"DROP TABLE IF EXISTS {table}")
+ c.simple(f"CREATE TABLE {table} (id int PRIMARY KEY, a int)")
+ if dup:
+ c.simple(f"INSERT INTO {table} VALUES (1, 1), (2, 1)")
+ kind = "UNIQUE INDEX" if unique else "INDEX"
+ result = c.extended(f"CREATE {kind} ASYNC {table}_a ON {table} (a)")
+ assert result.ok, result.message
+ return result.rows[0][0]
+
+ def test_bound_job_id(self, dsql_proxy):
+ """``CALL sys.wait_for_job($1)`` with the id bound, read back through
+ the ``succeeded`` column."""
+ with _WireClient(dsql_proxy) as c:
+ job = self._job(c, "wfj_drz")
+ result = c.extended("CALL sys.wait_for_job($1)", params=(job,))
+ assert result.ok, f"{result.sqlstate} {result.message}"
+ assert result.columns == [("succeeded", 16)]
+ assert result.rows == [("t",)]
+ assert result.tag == "CALL"
+ c.simple("DROP TABLE wfj_drz")
+
+ def test_cast_and_literal_forms(self, dsql_proxy):
+ with _WireClient(dsql_proxy) as c:
+ job = self._job(c, "wfj_forms")
+ cast = c.extended("CALL sys.wait_for_job($1::text)", params=(job,))
+ assert (cast.columns, cast.rows, cast.tag) == (
+ [("succeeded", 16)], [("t",)], "CALL",
+ )
+ literal = c.simple(f"CALL sys.wait_for_job('{job}')")
+ assert (literal.columns, literal.rows, literal.tag) == (
+ [("succeeded", 16)], [("t",)], "CALL",
+ )
+ c.simple("DROP TABLE wfj_forms")
+
+ def test_failed_job_answers_false(self, dsql_proxy):
+ with _WireClient(dsql_proxy) as c:
+ job = self._job(c, "wfj_fail", unique=True, dup=True)
+ result = c.extended("CALL sys.wait_for_job($1)", params=(job,))
+ assert result.rows == [("f",)]
+ jobs = c.extended(
+ "SELECT status, details FROM sys.jobs WHERE job_id = $1",
+ params=(job,),
+ )
+ assert jobs.rows == [
+ ("failed", "found duplicate key(s) while validating index uniqueness")
+ ]
+ c.simple("DROP TABLE wfj_fail")
+
+ def test_sys_jobs_bound_filter(self, dsql_proxy):
+ with _WireClient(dsql_proxy) as c:
+ job = self._job(c, "wfj_jobs")
+ result = c.extended(
+ "SELECT job_id, status FROM sys.jobs WHERE job_id = $1", params=(job,)
+ )
+ assert result.rows == [(job, "completed")]
+ assert result.tag == "SELECT 1"
+ c.simple("DROP TABLE wfj_jobs")
+
+ def test_async_ddl_command_tags(self, dsql_proxy):
+ """CREATE INDEX ASYNC answers CREATE INDEX, ALTER TABLE ASYNC answers
+ ALTER TABLE; both carry the job_id row."""
+ with _WireClient(dsql_proxy) as c:
+ c.simple("DROP TABLE IF EXISTS wfj_tags")
+ c.simple("CREATE TABLE wfj_tags (id int PRIMARY KEY, a int)")
+ c.simple("ALTER TABLE wfj_tags ADD CONSTRAINT wfj_ck CHECK (a > 0) NOT VALID")
+ for result in (
+ c.simple("CREATE INDEX ASYNC wfj_tags_a ON wfj_tags (a)"),
+ c.extended("CREATE INDEX ASYNC wfj_tags_b ON wfj_tags (a)"),
+ ):
+ assert (result.tag, result.columns) == ("CREATE INDEX", [("job_id", 25)])
+ for sql in (
+ "ALTER TABLE ASYNC wfj_tags VALIDATE CONSTRAINT wfj_ck",
+ ):
+ result = c.simple(sql)
+ assert result.tag == "ALTER TABLE", sql
+ validate_job = result.rows[0][0]
+ jobs = c.extended(
+ "SELECT class_id, start_time FROM sys.jobs WHERE job_id = $1",
+ params=(validate_job,),
+ )
+ # oid and timestamptz, rendered the way Postgres renders them
+ assert jobs.columns == [("class_id", 26), ("start_time", 1184)]
+ assert jobs.rows[0][0] == "2606" # pg_constraint
+ assert re.fullmatch(
+ r"\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\+00", jobs.rows[0][1]
+ )
+ c.simple("DROP TABLE wfj_tags")
+
+ def test_startup_reports_timezone(self, dsql_proxy):
+ """Drivers decode timestamptz by the reported TimeZone. Values as
+ real DSQL reports them."""
+ with _WireClient(dsql_proxy) as c:
+ status = dict(
+ p[:-1].decode().split("\0", 1) for t, p in c.startup if t == b"S"
+ )
+ assert status["TimeZone"] == "UTC"
+ assert status["DateStyle"] == "ISO, MDY"
+ assert status["IntervalStyle"] == "postgres"
+
+ def test_malformed_job_id_rejected(self, dsql_proxy):
+ with _WireClient(dsql_proxy) as c:
+ result = c.extended("CALL sys.wait_for_job($1)", params=("not-a-job",))
+ assert (result.sqlstate, result.message) == (
+ "22P02", "Unable to convert text to UUID",
+ )
+ # The error ends at Sync; the session carries on.
+ assert c.simple("SELECT 1").rows == [("1",)]
+
+ def test_placeholder_in_a_simple_query(self, dsql_proxy):
+ with _WireClient(dsql_proxy) as c:
+ result = c.simple("CALL sys.wait_for_job($1)")
+ assert (result.sqlstate, result.message) == (
+ "42P02", "there is no parameter $1",
+ )
+
+ def test_named_statement_rebinds(self, dsql_proxy):
+ """One prepared statement, two Binds: each portal gets its own answer."""
+ with _WireClient(dsql_proxy) as c:
+ job = self._job(c, "wfj_named")
+ f = c._frame
+
+ def bind(portal, value):
+ raw = value.encode()
+ return f(
+ b"B",
+ portal + b"\0wfj\0" + struct.pack("!HHi", 0, 1, len(raw)) + raw
+ + struct.pack("!H", 0),
+ )
+
+ msg = f(b"P", b"wfj\0CALL sys.wait_for_job($1)\0" + struct.pack("!H", 0))
+ msg += f(b"D", b"Swfj\0")
+ msg += bind(b"p1", job) + f(b"E", b"p1\0" + struct.pack("!I", 0))
+ msg += bind(b"p2", "a" * 26) + f(b"E", b"p2\0" + struct.pack("!I", 0))
+ msg += f(b"S", b"")
+ c.sock.sendall(msg)
+ frames = c._until_ready()
+ param_desc = next(p for t, p in frames if t == b"t")
+ assert param_desc == struct.pack("!HI", 1, 25) # one text parameter
+ assert _WireResult(frames).rows == [("t",), ("f",)]
+ c.simple("DROP TABLE wfj_named")
+
+
@requires_docker
@pytest.mark.data_plane
class TestTransactionAbortSemantics:
@@ -2360,9 +2741,10 @@ class TestLiveProxy:
job_id = cur.fetchone()[0]
assert re.match(r"^[a-z0-9]{26}$", job_id)
- cur.execute("SELECT job_id, status, job_type FROM sys.jobs")
+ cur.execute("SELECT job_id, status, job_type, details FROM sys.jobs")
jobs = cur.fetchall()
- assert (job_id, "completed", "INDEX_BUILD") in jobs
+ # details is NULL for a job that succeeded (as on real DSQL).
+ assert (job_id, "completed", "INDEX_BUILD", None) in jobs
finally:
conn.close()
@@ -2498,7 +2880,9 @@ class TestLiveProxy:
("CREATE INDEX fi1 ON form_live USING gin (data)", "0A000",
"USING not supported"),
("CREATE INDEX fi2 ON form_live (a) WHERE a > 0", "0A000",
- "WHERE not supported"),
+ "unsupported mode"),
+ ("CREATE INDEX ASYNC fi5 ON form_live (a) WHERE now() > now()",
+ "42P17", "index predicate"),
("CREATE INDEX fi3 ON form_live (now())", "0A000",
"unsupported mode"),
("CREATE INDEX ASYNC fi4 ON form_live (now())", "42P17",
@@ -2531,6 +2915,177 @@ class TestLiveProxy:
finally:
conn.close()
+ def test_partial_index_built(self, dsql_proxy):
+ """Partial indexes (AWS DSQL, 2026-09-15) are built with their predicate."""
+ conn = _pg_connect(dsql_proxy)
+ try:
+ cur = conn.cursor()
+ cur.execute("CREATE TABLE pi_live (id int PRIMARY KEY, rating int, title text)")
+ cur.execute(
+ "CREATE INDEX ASYNC pi_live_high ON pi_live (title) WHERE rating > 5"
+ )
+ job_id = cur.fetchone()[0]
+ cur.execute(f"SELECT sys.wait_for_job('{job_id}')")
+ assert cur.fetchone()[0] is True
+ cur.execute(
+ "SELECT pg_get_expr(indpred, indrelid) FROM pg_index "
+ "WHERE indexrelid = 'pi_live_high'::regclass"
+ )
+ assert cur.fetchone()[0] == "(rating > 5)"
+ cur.execute("DROP TABLE pi_live")
+ finally:
+ conn.close()
+
+ def test_unique_partial_index_scopes_uniqueness(self, dsql_proxy):
+ psycopg2 = pytest.importorskip("psycopg2")
+ conn = _pg_connect(dsql_proxy)
+ try:
+ cur = conn.cursor()
+ cur.execute(
+ "CREATE TABLE upi_live (id int PRIMARY KEY, email text, archived bool)"
+ )
+ cur.execute(
+ "CREATE UNIQUE INDEX ASYNC upi_live_email ON upi_live (email) "
+ "WHERE NOT archived"
+ )
+ job_id = cur.fetchone()[0]
+ cur.execute(f"SELECT sys.wait_for_job('{job_id}')")
+ assert cur.fetchone()[0] is True
+ # Duplicates are fine among archived rows...
+ cur.execute(
+ "INSERT INTO upi_live VALUES (1, 'a@x', true), (2, 'a@x', true), "
+ "(3, 'a@x', false)"
+ )
+ # ...but not among the rows the predicate covers.
+ with pytest.raises(psycopg2.Error) as exc:
+ cur.execute("INSERT INTO upi_live VALUES (4, 'a@x', false)")
+ assert exc.value.pgcode == "23505"
+ cur.execute("DROP TABLE upi_live")
+ finally:
+ conn.close()
+
+ def test_volatile_predicate_fails_the_submit(self, dsql_proxy):
+ """A bad predicate is refused up front, not handed back as a failed job."""
+ psycopg2 = pytest.importorskip("psycopg2")
+ conn = _pg_connect(dsql_proxy)
+ try:
+ cur = conn.cursor()
+ cur.execute("CREATE TABLE vp_live (id int, created timestamptz)")
+ cur.execute("SELECT job_id FROM sys.jobs")
+ jobs_before = len(cur.fetchall())
+ with pytest.raises(psycopg2.Error) as exc:
+ cur.execute(
+ "CREATE INDEX ASYNC vp_live_i ON vp_live (id) WHERE created > now()"
+ )
+ assert exc.value.pgcode == "42P17"
+ assert "index predicate must be marked IMMUTABLE" in str(exc.value)
+ cur.execute("SELECT job_id FROM sys.jobs")
+ assert len(cur.fetchall()) == jobs_before
+ cur.execute("DROP TABLE vp_live")
+ finally:
+ conn.close()
+
+ def test_batched_nestloop_setting(self, dsql_proxy):
+ """dsql.enable_batched_nestloop (AWS DSQL, 2026-09-11) defaults to on."""
+ psycopg2 = pytest.importorskip("psycopg2")
+ conn = _pg_connect(dsql_proxy)
+ try:
+ cur = conn.cursor()
+ cur.execute("SHOW dsql.enable_batched_nestloop")
+ assert cur.fetchone()[0] == "on"
+ cur.execute("SET dsql.enable_batched_nestloop = off")
+ cur.execute("SHOW dsql.enable_batched_nestloop")
+ assert cur.fetchone()[0] == "off"
+ cur.execute("RESET dsql.enable_batched_nestloop")
+ cur.execute("SHOW dsql.enable_batched_nestloop")
+ assert cur.fetchone()[0] == "on"
+ with pytest.raises(psycopg2.Error) as exc:
+ cur.execute("SET dsql.enable_batched_nestloop = banana")
+ assert exc.value.pgcode == "22023"
+ with pytest.raises(psycopg2.Error) as exc:
+ cur.execute("SET dsql.bogus_setting = 1")
+ assert exc.value.pgcode == "42602"
+ assert exc.value.diag.message_detail == '"dsql" is a reserved prefix.'
+ with pytest.raises(psycopg2.Error) as exc:
+ cur.execute("SHOW dsql.bogus_setting")
+ assert exc.value.pgcode == "42704"
+ finally:
+ conn.close()
+
+ def test_max_5_statistics_per_table(self, dsql_proxy):
+ """Extended statistics (AWS DSQL, 2026-08-27): at most 5 per table."""
+ psycopg2 = pytest.importorskip("psycopg2")
+ conn = _pg_connect(dsql_proxy)
+ try:
+ cur = conn.cursor()
+ cur.execute("CREATE TABLE st_live (a int, b int, c int)")
+ for i in range(5):
+ cur.execute(f"CREATE STATISTICS st_live_{i} ON a, b FROM st_live")
+ with pytest.raises(psycopg2.Error) as exc:
+ cur.execute("CREATE STATISTICS st_live_5 ON a, c FROM st_live")
+ assert exc.value.pgcode == "54000"
+ assert "more than 5 extended statistics per table are not allowed" in str(
+ exc.value
+ )
+ with pytest.raises(psycopg2.Error):
+ cur.execute("CREATE STATISTICS ON (a + b) FROM st_live")
+ # IF NOT EXISTS on an existing name is a no-op, not a sixth object;
+ # on a new name it is refused like any other.
+ cur.execute(
+ "CREATE STATISTICS IF NOT EXISTS st_live_0 ON a, b FROM st_live"
+ )
+ with pytest.raises(psycopg2.Error) as exc:
+ cur.execute(
+ "CREATE STATISTICS IF NOT EXISTS st_live_9 ON a, b FROM st_live"
+ )
+ assert exc.value.pgcode == "54000"
+ # The statement's own errors come before the limit, as on DSQL.
+ with pytest.raises(psycopg2.Error) as exc:
+ cur.execute("CREATE STATISTICS st_live_x ON a FROM st_live")
+ assert exc.value.pgcode == "42P17"
+ assert "at least 2 columns" in str(exc.value)
+ # The dry run leaves nothing behind.
+ cur.execute(
+ "SELECT count(*) FROM pg_statistic_ext "
+ "WHERE stxrelid = 'st_live'::regclass"
+ )
+ assert cur.fetchone()[0] == 5
+ # The limit holds inside a transaction too, and aborts it.
+ cur.execute("BEGIN")
+ with pytest.raises(psycopg2.Error) as exc:
+ cur.execute("CREATE STATISTICS st_live_t ON a, c FROM st_live")
+ assert exc.value.pgcode == "54000"
+ with pytest.raises(psycopg2.Error) as exc:
+ cur.execute("SELECT 1")
+ assert exc.value.pgcode == "25P02"
+ cur.execute("ROLLBACK")
+ # ALTER and DROP pass through; dropping one frees a slot.
+ cur.execute("ALTER STATISTICS st_live_0 SET STATISTICS 100")
+ with pytest.raises(psycopg2.Error) as exc:
+ cur.execute("ALTER STATISTICS st_live_0 SET STATISTICS 200")
+ assert exc.value.pgcode == "22023"
+ cur.execute("DROP STATISTICS st_live_0")
+ cur.execute("CREATE STATISTICS st_live_5 (mcv) ON a, c FROM st_live")
+ cur.execute("DROP TABLE st_live")
+ finally:
+ conn.close()
+
+ def test_numeric_precision_and_scale_limits(self, dsql_proxy):
+ """numeric takes precision up to 1000, scale -1000..1000 (2026-08-25)."""
+ conn = _pg_connect(dsql_proxy)
+ try:
+ cur = conn.cursor()
+ cur.execute(
+ "CREATE TABLE num_live (id int PRIMARY KEY, "
+ "big numeric(1000, 500), neg numeric(1000, -1000))"
+ )
+ cur.execute("INSERT INTO num_live VALUES (1, 1.5, 1234)")
+ cur.execute("SELECT neg FROM num_live")
+ assert cur.fetchone()[0] == 0 # rounded to the 10^1000 place
+ cur.execute("DROP TABLE num_live")
+ finally:
+ conn.close()
+
def test_alter_column_type_rejected(self, dsql_proxy):
psycopg2 = pytest.importorskip("psycopg2")
conn = _pg_connect(dsql_proxy)