Skip to content

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

dsql: expression index keys + index/DDL error parity with live Aurora DSQL (#1387)

Ryan84d082e5a6ce
diff --git a/README.md b/README.md
index 40aace12..4d5ef206 100644
--- a/README.md
+++ b/README.md
@@ -645,13 +645,13 @@ 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, foreign keys, `CREATE EXTENSION`, `TRUNCATE`, temp tables, `ALTER COLUMN TYPE`, `SET NOT NULL`, materialized views, partitioned tables, non-btree/partial/expression indexes, ...), plain `CREATE INDEX` on a non-empty table is refused (`use CREATE INDEX ASYNC instead`), `CREATE INDEX ASYNC` and `ALTER TABLE ASYNC ... VALIDATE CONSTRAINT` return a `job_id`, `sys.jobs` / `sys.wait_for_job` are emulated, CHECK constraints via ALTER TABLE require `NOT VALID`, `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 columns/index, 24/table), transactions allow only one DDL statement with no DDL+DML mixing, `SELECT ... FOR UPDATE` requires a single table with equality predicates on the key, 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, foreign keys, `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, CHECK constraints via ALTER TABLE require `NOT VALID`, `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` requires a single table with equality predicates on the key, 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.
`GetCluster` returns an `endpoint` of the form `localhost:<port>` (ports allocated from `DSQL_BASE_PORT`, default `25432`). Any user/password is accepted — IAM auth tokens from `generate_db_connect_auth_token` work but aren't validated. Connect with e.g. `psql "postgresql://admin@localhost:25432/postgres"` and enter any test password when prompted (no TLS — use `sslmode=disable`/`prefer`; with psycopg2 use `autocommit=True`).
**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); 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); 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 `CREATE INDEX` non-empty-table probe, 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 AWS-documented text where published, 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 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); 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`).
---
diff --git a/ministack/core/pgproxy.py b/ministack/core/pgproxy.py
index b4bbbf26..380ed764 100644
--- a/ministack/core/pgproxy.py
+++ b/ministack/core/pgproxy.py
@@ -838,24 +838,42 @@ def _check_cache_value(sql):
return None
-# DSQL index rules: btree only (no USING gin/gist/brin/hash/spgist), no
-# CONCURRENTLY (use ASYNC), no partial (WHERE) or expression indexes, and at
-# most 8 columns per index (24 indexes per table is enforced at runtime).
+# 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.
+#
+# Error precedence (observed on real DSQL): name-grammar → CONCURRENTLY →
+# USING → WHERE → mode → key-expression rules → key count.
+_VOLATILE_FUNCTIONS = frozenset({
+ "now", "random", "setseed", "nextval", "currval", "lastval", "setval",
+ "gen_random_uuid", "uuid_generate_v1", "uuid_generate_v4",
+ "txid_current", "pg_backend_pid", "pg_notification_queue_usage",
+ "current_setting", "set_config", "version", "clock_timestamp",
+ "statement_timestamp", "transaction_timestamp", "timeofday",
+})
+
+
def _check_index_rules(sql):
m = _INDEX_RE.match(sql) or _INDEX_ASYNC_RE.match(sql)
if not m:
return None
- using = re.search(r"\bUSING\s+(\w+)", sql, re.I)
- if using and using.group(1).lower() not in ("btree", "btree_index"):
- return DsqlError(
- "0A000", f"USING {using.group(1)} is not supported (btree only)"
- )
+ # IF NOT EXISTS without a name is a grammar error on real DSQL.
+ if re.search(r"\bIF\s+NOT\s+EXISTS\b", sql, re.I) and not m.group(1):
+ return DsqlError("42601", 'syntax error at or near "ON"')
if re.search(r"\bCONCURRENTLY\b", sql, re.I):
+ 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")
+ if not _INDEX_ASYNC_RE.match(sql):
return DsqlError(
- "0A000", "CREATE INDEX CONCURRENTLY is not supported — use CREATE INDEX ASYNC"
+ "0A000", "unsupported mode. please use CREATE INDEX ASYNC."
)
- if re.search(r"\bWHERE\b", sql, re.I):
- return DsqlError("0A000", "partial indexes (WHERE) are not supported")
start = sql.find("(", m.end())
if start < 0:
return None
@@ -863,11 +881,30 @@ def _check_index_rules(sql):
if end < 0:
return None
parts = _split_top_level(sql[start + 1 : end])
- if any("(" in part for part in parts):
- return DsqlError("0A000", "expression indexes are not supported")
+ 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",
+ )
+ # INCLUDE columns are non-key: expressions are not supported there.
+ inc = re.search(r"\bINCLUDE\s*\(", sql[end:], re.I)
+ if inc:
+ istart = end + inc.end() - 1
+ iend = _match_paren(sql, istart)
+ if iend > 0 and any(
+ "(" in p for p in _split_top_level(sql[istart + 1 : iend])
+ ):
+ return DsqlError(
+ "0A000", "expressions are not supported in included columns"
+ )
if len(parts) > 8:
return DsqlError(
- "0A000", f"indexes cannot have more than 8 columns ({len(parts)} given)"
+ "54011", "more than 8 column keys in an index are not supported"
)
return None
@@ -907,15 +944,6 @@ def rewrite_index_async(sql):
)
-def is_plain_create_index(sql):
- return bool(_INDEX_RE.match(sql)) and not _INDEX_ASYNC_RE.match(sql)
-
-
-def create_index_table(sql):
- m = _INDEX_RE.match(sql) or _INDEX_ASYNC_RE.match(sql)
- return m.group(2) if m else None
-
-
def _index_object_name(sql, on_end, index_name, table):
"""Schema-qualified index name for the sys.jobs object_name field.
@@ -1184,22 +1212,6 @@ async def _run_backend_capture(conn, b_writer, sql):
conn.capture = None
-async def _table_has_rows(conn, b_writer, table):
- """Probe SELECT 1 FROM <table> LIMIT 1 on the client's backend connection."""
- try:
- frames = await _run_backend_capture(
- conn, b_writer, f"SELECT 1 FROM {table} LIMIT 1"
- )
- except Exception:
- return False
- for type_byte, _ in frames:
- if type_byte == b"E":
- return False # probe failed — forward original; backend errors
- if type_byte == b"D":
- return True
- return False
-
-
async def _index_count(conn, b_writer, table):
"""Count the table's existing indexes via pg_indexes. None on probe error."""
schema, _, bare = table.rpartition(".")
@@ -1342,10 +1354,8 @@ async def _check_drop_column(conn, b_writer, sql):
lowered = {c.lower() for c in pk_cols}
for col in cols:
if col.lower() in lowered:
- return DsqlError(
- "0A000",
- f'dropping primary key column "{col}" is not supported',
- )
+ # Exact message from real DSQL (verified in eu-west-2, Aug 2026).
+ return DsqlError("0A000", f"cannot drop primary key column {col}")
return None
@@ -1458,18 +1468,6 @@ async def _plan_statement(conn, s, b_writer, allow_probe=True):
)
return "rewrite", result
- if is_plain_create_index(s):
- table = create_index_table(s)
- if table and allow_probe:
- count = await _index_count(conn, b_writer, table)
- if count is not None and count >= 24:
- return "error", DsqlError(
- "0A000", f"table {table} already has the maximum of 24 indexes"
- )
- if await _table_has_rows(conn, b_writer, table):
- return "error", DsqlError("0A000", "use CREATE INDEX ASYNC instead")
- return "forward", None
-
if allow_probe:
err = await _check_drop_column(conn, b_writer, s)
if err:
diff --git a/tests/test_dsql.py b/tests/test_dsql.py
index a9df1d47..c5cfb90e 100644
--- a/tests/test_dsql.py
+++ b/tests/test_dsql.py
@@ -868,52 +868,76 @@ class TestIdentityAndSequences:
class TestIndexLimits:
+ # Messages, sqlstates and precedence verified against a live Aurora DSQL
+ # cluster (eu-west-2, Aug 2026).
@pytest.mark.parametrize(
- "sql",
+ "sql,sqlstate,message",
[
- "CREATE INDEX i ON t USING gin (data)",
- "CREATE INDEX i ON t USING gist (coords)",
- "CREATE INDEX i ON t USING brin (created_at)",
- "CREATE INDEX i ON t USING hash (a)",
- "CREATE INDEX ASYNC i ON t USING gin (data)",
- "CREATE INDEX CONCURRENTLY i ON t (a)",
- "CREATE INDEX i ON t (a) WHERE a > 0", # partial index
- "CREATE INDEX ASYNC i ON t (a) WHERE a > 0",
- "CREATE INDEX i ON t (lower(email))", # expression index
- "CREATE INDEX ASYNC i ON t ((data->>'city'))",
+ # IF NOT EXISTS requires a name (grammar-level)
+ ("CREATE INDEX ASYNC IF NOT EXISTS ON t (a)", "42601",
+ 'syntax error at or near "ON"'),
+ ("CREATE INDEX CONCURRENTLY i ON t (a)", "0A000",
+ "CONCURRENTLY not supported for CREATE INDEX"),
+ ("CREATE INDEX i ON t USING gin (data)", "0A000",
+ "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."),
+ ("CREATE UNIQUE INDEX i ON t (a NULLS LAST) INCLUDE (b)", "0A000",
+ "unsupported mode"),
+ # mode is reported before immutability
+ ("CREATE INDEX i ON t (now())", "0A000", "unsupported mode"),
+ # volatile functions in index expressions (must be immutable)
+ ("CREATE INDEX ASYNC i ON t (now())", "42P17",
+ "functions in index expression must be marked IMMUTABLE"),
+ ("CREATE INDEX ASYNC i ON t (random())", "42P17", "IMMUTABLE"),
+ ("CREATE INDEX ASYNC i ON t (gen_random_uuid())", "42P17", "IMMUTABLE"),
+ ("CREATE INDEX ASYNC i ON t (lower(email), nextval('s'))", "42P17",
+ "IMMUTABLE"),
+ # INCLUDE takes plain columns only (no expressions)
+ ("CREATE INDEX ASYNC i ON t (a) INCLUDE (lower(b))", "0A000",
+ "expressions are not supported in included columns"),
+ ("CREATE UNIQUE INDEX ASYNC i ON t (a) INCLUDE ((b + c))", "0A000",
+ "included columns"),
],
)
- def test_unsupported_index_forms_denied(self, sql):
+ def test_unsupported_index_forms_denied(self, sql, sqlstate, message):
err = pgproxy.validate(sql, pgproxy.TxnState())
assert isinstance(err, pgproxy.DsqlError), sql
- assert err.sqlstate == "0A000"
+ assert err.sqlstate == sqlstate, sql
+ assert message in err.message, sql
@pytest.mark.parametrize(
"sql",
[
- "CREATE INDEX i ON t (a)",
- "CREATE INDEX i ON t USING btree (a)",
- "CREATE UNIQUE INDEX i ON t (a NULLS LAST) INCLUDE (b)",
+ "CREATE INDEX ASYNC i ON t (a)",
"CREATE INDEX ASYNC i ON t (a, b DESC) INCLUDE (c)",
+ "CREATE UNIQUE INDEX ASYNC i ON t (a NULLS LAST) NULLS NOT DISTINCT",
+ # expression index keys (immutable functions/operators)
+ "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)",
],
)
def test_supported_index_forms_allowed(self, sql):
result = pgproxy.validate(sql, pgproxy.TxnState())
- assert not isinstance(result, pgproxy.DsqlError), sql
+ assert isinstance(result, pgproxy.Rewrite), sql
def test_more_than_8_columns_denied(self):
- for kw in ("", "ASYNC "):
- err = pgproxy.validate(
- f"CREATE INDEX {kw}i ON t (a,b,c,d,e,f,g,h,i)", pgproxy.TxnState()
- )
- assert isinstance(err, pgproxy.DsqlError), kw
- assert err.sqlstate == "0A000"
- assert "8 columns" in err.message
+ err = pgproxy.validate(
+ "CREATE INDEX ASYNC i ON t (a,b,c,d,e,f,g,h,i)", pgproxy.TxnState()
+ )
+ assert isinstance(err, pgproxy.DsqlError)
+ assert err.sqlstate == "54011"
+ assert err.message == "more than 8 column keys in an index are not supported"
def test_exactly_8_columns_allowed(self):
- assert pgproxy.validate(
- "CREATE INDEX i ON t (a,b,c,d,e,f,g,h)", pgproxy.TxnState()
- ) is None
result = pgproxy.validate(
"CREATE INDEX ASYNC i ON t (a,b,c,d,e,f,g,h)", pgproxy.TxnState()
)
@@ -1076,13 +1100,13 @@ class TestIndexAsync:
assert isinstance(result, pgproxy.Rewrite)
assert result.object_name == "public.t_email_idx"
- def test_plain_create_index_not_rewritten(self):
- result = pgproxy.validate(
- "CREATE INDEX idx ON t (a)", pgproxy.TxnState()
- )
- assert result is None
- assert pgproxy.is_plain_create_index("CREATE INDEX idx ON t (a)")
- assert not pgproxy.is_plain_create_index("CREATE INDEX ASYNC idx ON t (a)")
+ def test_plain_create_index_rejected(self):
+ # Real DSQL: index creation is always asynchronous; plain CREATE
+ # INDEX fails regardless of table contents.
+ err = pgproxy.validate("CREATE INDEX idx ON t (a)", pgproxy.TxnState())
+ assert isinstance(err, pgproxy.DsqlError)
+ assert err.sqlstate == "0A000"
+ assert "unsupported mode" in err.message
class TestTxnDiscipline:
@@ -1587,7 +1611,8 @@ class TestDropColumn:
c.simple("CREATE TABLE dc_c (id int PRIMARY KEY, x int)")
result = c.simple("ALTER TABLE dc_c DROP COLUMN id")
assert result.sqlstate == "0A000"
- assert "primary key" in result.message
+ # exact message from real DSQL (verified in eu-west-2, Aug 2026)
+ assert result.message == "cannot drop primary key column id"
# The column must still be there.
assert c.simple("SELECT id FROM dc_c").ok
@@ -1725,29 +1750,18 @@ class TestLiveProxy:
finally:
conn.close()
- def test_plain_create_index_empty_table_ok(self, dsql_proxy):
- conn = _pg_connect(dsql_proxy)
- try:
- cur = conn.cursor()
- cur.execute("CREATE TABLE ci_live (a int)")
- cur.execute("CREATE INDEX ci_live_a ON ci_live (a)")
- cur.execute("DROP TABLE ci_live")
- finally:
- conn.close()
-
- def test_plain_create_index_nonempty_table_rejected(self, dsql_proxy):
+ def test_plain_create_index_rejected_even_on_empty_table(self, dsql_proxy):
psycopg2 = pytest.importorskip("psycopg2")
conn = _pg_connect(dsql_proxy)
try:
cur = conn.cursor()
- cur.execute("CREATE TABLE cn_live (a int)")
- cur.execute("INSERT INTO cn_live VALUES (1)")
+ cur.execute("CREATE TABLE ci_live (a int)")
with pytest.raises(psycopg2.Error) as exc:
- cur.execute("CREATE INDEX cn_live_a ON cn_live (a)")
+ cur.execute("CREATE INDEX ci_live_a ON ci_live (a)")
assert exc.value.pgcode == "0A000"
- # exact message published in the AWS DSQL troubleshooting docs
- assert "use CREATE INDEX ASYNC instead" in str(exc.value)
- cur.execute("DROP TABLE cn_live")
+ # exact message from real DSQL (verified in eu-west-2, Aug 2026)
+ assert "unsupported mode. please use CREATE INDEX ASYNC." in str(exc.value)
+ cur.execute("DROP TABLE ci_live")
finally:
conn.close()
@@ -1795,21 +1809,43 @@ class TestLiveProxy:
try:
cur = conn.cursor()
cur.execute("CREATE TABLE form_live (a int, data jsonb)")
- for sql, fragment in [
- ("CREATE INDEX fi1 ON form_live USING gin (data)", "btree"),
- ("CREATE INDEX fi2 ON form_live (a) WHERE a > 0", "partial"),
- ("CREATE INDEX fi3 ON form_live (lower(data::text))", "expression"),
- ("CREATE MATERIALIZED VIEW mv_live AS SELECT 1", "materialized"),
- ("CREATE TABLE part_live (a int) PARTITION BY RANGE (a)", "partition"),
+ for sql, sqlstate, fragment in [
+ ("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"),
+ ("CREATE INDEX fi3 ON form_live (now())", "0A000",
+ "unsupported mode"),
+ ("CREATE INDEX ASYNC fi4 ON form_live (now())", "42P17",
+ "IMMUTABLE"),
+ ("CREATE MATERIALIZED VIEW mv_live AS SELECT 1", "0A000",
+ "materialized"),
+ ("CREATE TABLE part_live (a int) PARTITION BY RANGE (a)", "0A000",
+ "partition"),
]:
with pytest.raises(psycopg2.Error) as exc:
cur.execute(sql)
- assert exc.value.pgcode == "0A000", sql
+ assert exc.value.pgcode == sqlstate, sql
assert fragment in str(exc.value), sql
cur.execute("DROP TABLE form_live")
finally:
conn.close()
+ def test_expression_index_accepted(self, dsql_proxy):
+ """Expression index keys with immutable functions are supported."""
+ psycopg2 = pytest.importorskip("psycopg2")
+ conn = _pg_connect(dsql_proxy)
+ try:
+ cur = conn.cursor()
+ cur.execute("CREATE TABLE expr_live (id int, title text)")
+ cur.execute("CREATE INDEX ASYNC ei_live ON expr_live (lower(title))")
+ job_id = cur.fetchone()[0]
+ cur.execute(f"SELECT sys.wait_for_job('{job_id}')")
+ assert cur.fetchone()[0] is True
+ cur.execute("DROP TABLE expr_live")
+ finally:
+ conn.close()
+
def test_alter_column_type_rejected(self, dsql_proxy):
psycopg2 = pytest.importorskip("psycopg2")
conn = _pg_connect(dsql_proxy)