From 3a29fd7d422c58dc6e65d32314924a0b2c3adc34 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 00:56:16 -0600 Subject: [PATCH 1/7] Server schema check: read more DDL forms or raise, and keep table and index takes apart BACKLOG #5062 remainder and BACKLOG #8302 items 3, 5 and 6, in messagefoundry/store/server_schema_verify.py. - A second CREATE INDEX of a name no DROP INDEX freed raises: the expected shape keys an index by name, so a same-named SQL Server index on another table replaced the first (#8302 item 3). - _statement_end ends an opaque index's text at an ELSE or END outside a CASE, so it no longer reads on into the rest of a T-SQL block (#8302 item 5). - _string_spans reads quoted runs through _quoted_end, so a [ is a name or a subscript as the other scanners read it (#8302 item 6). - server_schema_differences takes taken_tables apart from taken, so an index name taken on SQL Server no longer hides a table of that name. - An ALTER COLUMN or added PRIMARY KEY that opens its statement reaches every store; one with anything before it reaches only an older store, so the two follow one rule. - DDL in a string literal no EXEC runs, or that a + joins to more text, raises (one join read: DROP CONSTRAINT named by QUOTENAME). - A default of more than one token raises naming the default. - test_store_schema_hash: the previous-revision marker is checked against what _schema_hash writes at that revision. The shipped PostgreSQL and SQL Server expected shapes are identical to main's, so SCHEMA_CHECK_REV is not bumped. --- messagefoundry/store/server_schema_verify.py | 178 +++++++++++------ tests/test_server_schema_verify_5062.py | 182 +++++++++++++++++- ...t_sqlserver_postgres_schema_verify_1720.py | 23 ++- tests/test_store_schema_hash.py | 5 + 4 files changed, 317 insertions(+), 71 deletions(-) diff --git a/messagefoundry/store/server_schema_verify.py b/messagefoundry/store/server_schema_verify.py index 1d0e3e41b8..366c303149 100644 --- a/messagefoundry/store/server_schema_verify.py +++ b/messagefoundry/store/server_schema_verify.py @@ -40,7 +40,9 @@ DDL the reader cannot place raises ``ValueError`` rather than being skipped or misread, at least: a ``CREATE ... INDEX``, ``CREATE TABLE``, ``DROP TABLE``, ``DROP INDEX`` or ``sp_rename`` its patterns do not match, an ``ALTER TABLE`` with more than one clause or an action it does not know, a table rename, -an ``ALTER INDEX``, a second ``CREATE TABLE`` of a table no ``DROP`` removed, a ``USING`` access +an ``ALTER INDEX``, a second ``CREATE TABLE`` of a table no ``DROP`` removed, a second ``CREATE +INDEX`` of a name no ``DROP INDEX`` freed, DDL in a string literal that no ``EXEC`` runs or that a +``+`` joins to more text, a default of more than one token, a ``USING`` access method, a key column or expression carrying a collation, an operator class or a ``NULLS`` order, a key that opens with a ``::`` or ``CAST`` cast of a column, a key built ``USING INDEX``, a SQL Server inline ``INDEX``, a ``NOT NULL`` table constraint, a column type or clause it does not know, a SQL @@ -48,8 +50,11 @@ or ``/*`` inside a quoted string, which may be dynamic SQL's comment or a literal's text. A unit test reads each shipped batch, so a new form fails there before it reaches an open. -Not every misread raises (BACKLOG #5062). At least: DDL text inside a string literal is read as run, -and an ``ALTER COLUMN`` is read as reaching only an older store, whether or not either holds. A +An ``ALTER COLUMN`` or added ``PRIMARY KEY`` that opens its statement is read as reaching every +store, and one with anything before it as reaching only an older store, so the latter raises where +its result differs from the ``CREATE TABLE``, even if its guard would hold on a new store too. + +Not every misread raises (BACKLOG #5062). At least: a ``DROP COLUMN`` raises where the reader finds the column's name among the words of an expression, ``INCLUDE`` or partial index on its table, other than as a key column, but that word search can miss a name, so a ``DROP COLUMN`` that should raise may instead keep an index PostgreSQL drops. @@ -317,27 +322,17 @@ def _strip_comments(raw: str) -> str: def _string_spans(text: str) -> list[tuple[int, int]]: """The ``(start, end)`` of each single-quoted string in ``text``, end exclusive. A doubled quote - inside one is its escape, so it continues the string.""" + inside one is its escape, so it continues the string. Quoted runs are read by + :func:`_quoted_end`, so a ``[`` is a name or a subscript here as it is there (BACKLOG #8302).""" spans: list[tuple[int, int]] = [] - i, n = 0, len(text) - while i < n: - ch = text[i] - if ch in '"[': - end = text.find("]" if ch == "[" else ch, i + 1) - i = n if end < 0 else end + 1 - elif ch == "'": - j = i + 1 - while j < n: - if text[j] == "'": - if text.startswith("''", j): - j += 2 - continue - break - j += 1 - spans.append((i, j + 1)) - i = j + 1 - else: + i = 0 + while i < len(text): + if (end := _quoted_end(text, i)) is None: i += 1 + continue + if text[i] == "'": + spans.append((i, end)) + i = end return spans @@ -462,12 +457,12 @@ def _clause(segment: str) -> str: def _statement_end(text: str, start: int, dialect: Dialect | None) -> int: """Where the statement that ``text[start:]`` continues ends: a top-level ``;``, an unmatched - ``)``, a word that starts the next statement, or the end. Unlike :func:`_clause` it reads on - through ``ELSE`` and ``END``, which a ``CASE`` in an index predicate holds, so it may read into a - following block. Off SQL Server it reads through a data word too, which PostgreSQL takes as a - column's name, so it may also read into a following statement; on SQL Server a data word is - reserved and ends it.""" - depth, i = 0, start + ``)``, a word that starts the next statement, or the end. An ``ELSE`` or ``END`` ends it only + outside a ``CASE``, which an index predicate may hold, so it does not read on into the rest of + a T-SQL block (BACKLOG #8302). Off SQL Server it reads through a data word, which PostgreSQL + takes as a column's name, so it may read into a following statement no ``;`` comes before; on + SQL Server a data word is reserved and ends it.""" + depth, cases, i = 0, 0, start while i < len(text): if (end := _quoted_end(text, i)) is not None: i = end @@ -489,8 +484,13 @@ def _statement_end(text: str, start: int, dialect: Dialect | None) -> int: word = re.match(r"[\w$]+", text[i:]) assert word is not None lower = word.group(0).lower() - if ( + if lower == "case": + cases += 1 + elif lower == "end" and cases: + cases -= 1 + elif ( lower in ("if", "begin", "exec", "execute", "declare", "go", "create") + or (lower in ("else", "end") and not cases) or (dialect == "sqlserver" and lower in _DATA_STATEMENT) or (lower in ("alter", "drop") and _DDL_OBJECT.match(text, i + len(lower))) ): @@ -726,6 +726,10 @@ def word(k: int) -> str: i = _skip_group(tokens, i - 1) elif word(i) == "(": i = _skip_group(tokens, i) + if i < len(tokens) and word(i) not in _COLUMN_CLAUSES: + # A default of more than one token, such as now() + interval '1 day', is named + # as the default, not as the clause its second token would start (BACKLOG #5062). + raise ValueError(f"a default the live-schema check cannot read: {text!r}") elif w == "constraint" and i + 1 < len(tokens): i += 2 elif w == "collate" and i + 1 < len(tokens): @@ -878,9 +882,11 @@ def key_column(text: str) -> str: class _Built: """Every shape a store may hold one column in. ``create`` is what ``CREATE TABLE`` builds on a new store. ``later`` is what a guarded ``ADD`` builds on an older store that lacked the column, - and what an ``ALTER COLUMN`` leaves on an older store. Every guard in a shipped batch tests for - the old state, so an ``ALTER COLUMN`` is not taken to reach a new store: its result must equal - ``create``, or the column is built two ways.""" + and what an ``ALTER COLUMN`` or an added ``PRIMARY KEY`` leaves on an older store. A guarded + one is not taken to reach a new store, because its guard may test for the old state: its result + must equal ``create``, or the column is built two ways. An ``ALTER TABLE`` that opens its + statement, with nothing before it, runs on every store, so it changes ``create`` too (BACKLOG + #5062).""" create: ColumnShape | None = None later: set[ColumnShape] = field(default_factory=set) @@ -888,8 +894,12 @@ class _Built: def ways(self) -> set[ColumnShape]: return self.later | ({self.create} if self.create else set()) - def altered(self, change: Callable[[ColumnShape], ColumnShape]) -> None: - self.later = {change(s) for s in (self.later or self.ways())} + def altered(self, change: Callable[[ColumnShape], ColumnShape], *, everywhere: bool) -> None: + if everywhere: + self.create = self.create and change(self.create) + self.later = {change(s) for s in self.later} + else: + self.later = {change(s) for s in (self.later or self.ways())} def _pk_columns(text: str) -> set[str]: @@ -997,6 +1007,14 @@ def index(self, text: str, m: re.Match[str]) -> None: if text[end - 1] == "(": end = _balanced(text, end)[1] name = _bare(m["name"]) + if name in self.indexes: + # The expected shape holds one index per name (BACKLOG #8302). A guarded second CREATE + # INDEX of a name no DROP INDEX freed never runs where the first did, and on SQL Server + # it may name an index on another table, which both sides would key the same. + raise ValueError( + f"a second create index named {name}: its guard skips it, or it is on another" + " table, which the reader does not tell apart" + ) shape = IndexShape( _bare(m["table"]), tuple(_declared_key(item) for item in _top_level_items(body)), @@ -1032,6 +1050,9 @@ def _built(self, table: str, name: str, action: str) -> _Built: def alter(self, text: str, m: re.Match[str], spans: list[tuple[int, int]]) -> None: table = _bare(m["table"]) segment = text[m.end() :] + # Only an ALTER TABLE that opens its statement is known to run on every store; anything + # before it, an IF or an EXEC among them, may guard it (BACKLOG #5062). + everywhere = not text[: m.start()].strip() for start, end in spans: if start < m.start() < end: # inside an EXEC string: its own text, quotes undoubled segment = text[m.end() : end - 1].replace("''", "'") @@ -1049,7 +1070,9 @@ def alter(self, text: str, m: re.Match[str], spans: list[tuple[int, int]]) -> No # After ADD COLUMN what follows is a column, whatever its name (BACKLOG #5062). if not head.group(1) and _is_constraint(rest, self.dialect): for key in _pk_columns(rest): - self._not_null(table, key) + self._built(table, key, "a primary key").altered( + lambda s: replace(s, nullable=False), everywhere=everywhere + ) return if self.dialect is None: self.columns.setdefault(table, {}).setdefault( @@ -1081,18 +1104,13 @@ def alter(self, text: str, m: re.Match[str], spans: list[tuple[int, int]]) -> No elif verb[:1] == ["set"] and clause[3:].lstrip().startswith("("): return # a table's storage options, such as LOCK_ESCALATION: not compared elif verb == ["alter", "column"]: - self._alter_column(table, clause, words) + self._alter_column(table, clause, words, everywhere=everywhere) elif verb == ["rename", "column"] and len(words) == 5 and words[3].lower() == "to": self._rename(table, _bare(words[2]), _bare(words[4])) else: raise ValueError(f"an alter table the live-schema check cannot read: {clause[:120]!r}") - def _not_null(self, table: str, name: str) -> None: - built = self._built(table, name, "a primary key") - built.create = built.create and replace(built.create, nullable=False) - built.later = {replace(s, nullable=False) for s in built.later} - - def _alter_column(self, table: str, clause: str, words: list[str]) -> None: + def _alter_column(self, table: str, clause: str, words: list[str], *, everywhere: bool) -> None: if len(words) < 3: raise ValueError(f"an alter column with no column: {clause!r}") if self.dialect is None: @@ -1106,24 +1124,24 @@ def _alter_column(self, table: str, clause: str, words: list[str]) -> None: raise ValueError(f"an alter column the live-schema check cannot read: {clause!r}") col.identity = {s.identity for s in built.ways()} == {True} new = _finish(self.dialect, col, clause) - built.altered(lambda _s: new) + built.altered(lambda _s: new, everywhere=everywhere) return upper = rest.upper() if upper in ("SET NOT NULL", "DROP NOT NULL"): nullable = upper.startswith("DROP") - built.altered(lambda s: replace(s, nullable=nullable)) + built.altered(lambda s: replace(s, nullable=nullable), everywhere=everywhere) elif upper == "DROP DEFAULT" or upper.startswith("SET DEFAULT "): # A nextval() default numbers the column as the live read sees it, and any other # default, or none, does not. PostgreSQL refuses either on an identity column. numbered = _numbers(rest[len("SET DEFAULT ") :]) # empty after DROP DEFAULT - built.altered(lambda s: replace(s, identity=numbered)) + built.altered(lambda s: replace(s, identity=numbered), everywhere=everywhere) elif match := re.match( r"(?:SET\s+DATA\s+)?TYPE\s+(.+?)(?:\s+USING\s+.*)?$", rest, re.I | re.S ): if re.search(r"\bCOLLATE\b", match.group(1), re.I): raise ValueError(f"a PostgreSQL column collation is not compared: {clause!r}") new_type, _numbered = _canonical_type(self.dialect, match.group(1)) - built.altered(lambda s: replace(s, type=new_type)) + built.altered(lambda s: replace(s, type=new_type), everywhere=everywhere) else: raise ValueError(f"an alter column the live-schema check cannot read: {clause!r}") @@ -1218,6 +1236,40 @@ def shape(self) -> ServerSchemaShape: ) +#: What opens a string literal that SQL Server runs as SQL: an ``EXEC`` or ``sp_executesql`` +#: argument, or a value assigned to a variable, which counts only once an ``EXEC`` runs that +#: variable later in the statement. +_EXEC_LITERAL = re.compile(r"\b(?:EXEC(?:UTE)?\s*\(|sp_executesql)\s*N?$", re.I) +_ASSIGNED_LITERAL = re.compile(r"@(?P\w+)(?:\s+\w+(?:\s*\([^()]*\))?)?\s*=\s*N?$", re.I) +#: A literal joined to a quoted name and nothing else, as a ``DROP CONSTRAINT`` takes its name. +_QUOTENAME_TAIL = re.compile(r"\s*\+\s*QUOTENAME\s*\(\s*@\w+\s*\)\s*(?:;|$)", re.I) + + +def _check_literal(text: str, spans: list[tuple[int, int]], kind: str, m: re.Match[str]) -> None: + """Raise when DDL the reader matched sits in a string literal it cannot read as run (BACKLOG + #5062): one that no ``EXEC`` runs, which the server never executes, or one joined to more text + by ``+``, whose clause the literal cuts short. The one join read is an ``ALTER TABLE ... DROP + CONSTRAINT`` given its name by ``QUOTENAME``, a clause the reader does not apply.""" + span = next(((start, end) for start, end in spans if start < m.start() < end), None) + if span is None: + return + start, end = span + before = text[:start] + run = _EXEC_LITERAL.search(before) is not None + if not run and (assigned := _ASSIGNED_LITERAL.search(before)): + var = assigned["var"] + runs = rf"\b(?:EXEC(?:UTE)?\s*\(\s*@{var}\s*\)|sp_executesql\s+@{var}\b)" + run = re.search(runs, text[end:], re.I) is not None + if not run: + raise ValueError(f"DDL inside a string literal that no EXEC runs: {m.group(0)[:120]!r}") + if text[end:].lstrip().startswith("+") and not ( + kind == "alter" + and re.fullmatch(r"\s*DROP\s+CONSTRAINT\s*", text[m.end() : end - 1], re.I) + and _QUOTENAME_TAIL.match(text, end) + ): + raise ValueError(f"DDL in a string literal that a + joins to more text: {m.group(0)!r}") + + @cache def declared_schema( statements: tuple[str, ...], dialect: Dialect | None = None @@ -1252,6 +1304,7 @@ def declared_schema( ): events.extend((m.start(), kind, m) for m in pattern.finditer(text)) for _pos, kind, m in sorted(events, key=lambda e: e[0]): + _check_literal(text, spans, kind, m) if kind == "table": reader.table(text, m) elif kind == "index": @@ -1279,23 +1332,29 @@ def server_schema_differences( live: SchemaShape, taken: Mapping[str, str], unusable: Mapping[str, str] | None = None, + *, + taken_tables: Mapping[str, str] | None = None, ) -> list[str]: """Every way ``live`` falls short of ``expected``, one clause each. Extras are not listed. - ``taken`` maps an expected table or index name to the kind of object that holds it instead (a - table holding an index's name, a view holding a table's). Such a name gets its own clause, which - says why the guarded ``CREATE`` skipped it, in place of a bare "is missing". ``unusable`` maps an + ``taken`` maps an expected index name to the kind of object that holds it instead (a table + holding an index's name), and ``taken_tables`` an expected table name (a view holding a + table's). They are kept apart because on SQL Server an index may share a table's name, so a + name taken from one must not hide the other's clauses (BACKLOG #5062). Such a name gets its own + clause, which says why the guarded ``CREATE`` skipped it, in place of a bare "is missing". + ``unusable`` maps an expected index that exists under its name to why it cannot serve, such as ``disabled``. A column both shapes describe is compared by :meth:`ColumnShape.core_differs` and :meth:`ColumnShape.collation_differs`, one clause for each that differs.""" unusable = unusable or {} + taken_tables = taken_tables or {} problems: list[str] = [] - for name in sorted(taken): - if name in expected.columns: + for name in sorted({*taken_tables, *taken}): + if name in taken_tables and name in expected.columns: problems.append( - f"table {name!r} was never created: the name is taken by {_a(taken[name])}" + f"table {name!r} was never created: the name is taken by {_a(taken_tables[name])}" ) - elif name in expected.named_indexes: + if name in taken and name in expected.named_indexes: problems.append( f"index {name!r} was never built: the name is taken by {_a(taken[name])}" f" (expected {expected.named_indexes[name].describe()})" @@ -1306,9 +1365,7 @@ def server_schema_differences( f"index {name!r} exists but is {unusable[name]}" f" (expected {expected.named_indexes[name].describe()})" ) - # Kept apart: on SQL Server an index name is unique only within its table, so an index named - # like a table must not hide that table's columns. - skip_tables = {n for n in taken if n in expected.columns} + skip_tables = {n for n in taken_tables if n in expected.columns} skip_indexes = {n for n in (set(taken) | set(unusable)) if n in expected.named_indexes} # A table that exists with no columns is not missing; the shared compare cannot tell the two # apart, because SQLite's read lists every table it asked for. @@ -1444,16 +1501,17 @@ def refuse_short_schema( name nothing holds, ``"table"`` for a table, and otherwise the kind of object that holds the name; ``column`` is ``None`` for a table with no columns; ``shape`` is the column's :class:`ColumnShape`, or ``None`` where the read gave none. ``taken`` names the indexes another - kind of object holds; the tables are added to it here. ``unusable`` is + kind of object holds; the tables another kind holds are read from ``column_rows`` and passed + apart, as :func:`server_schema_differences`' ``taken_tables``. ``unusable`` is :func:`server_schema_differences`'. ``schema`` is :class:`ServerSchemaMismatchError`'s.""" - taken = dict(taken) + taken_tables: dict[str, str] = {} columns: dict[str, set[str]] = {} shapes: dict[str, dict[str, ColumnShape]] = {} for table, kind, column, shape in column_rows: if kind is None: continue # nothing holds the name: the compare reports the table missing if kind != "table": - taken[table] = kind + taken_tables[table] = kind continue names = columns.setdefault(table, set()) if column is not None: @@ -1461,7 +1519,7 @@ def refuse_short_schema( if shape is not None: shapes.setdefault(table, {})[column] = shape problems = server_schema_differences( - expected, live_shape(columns, indexes, shapes), taken, unusable + expected, live_shape(columns, indexes, shapes), taken, unusable, taken_tables=taken_tables ) if problems: exc = ServerSchemaMismatchError(backend, database, problems, schema) diff --git a/tests/test_server_schema_verify_5062.py b/tests/test_server_schema_verify_5062.py index f3eb84228f..238996c6db 100644 --- a/tests/test_server_schema_verify_5062.py +++ b/tests/test_server_schema_verify_5062.py @@ -12,7 +12,11 @@ import pytest -from messagefoundry.store.server_schema_verify import declared_schema +from messagefoundry.store.server_schema_verify import ( + ServerSchemaMismatchError, + declared_schema, + refuse_short_schema, +) def test_add_column_takes_any_name_as_a_column() -> None: @@ -491,15 +495,16 @@ def test_a_data_word_in_a_predicate_does_not_end_the_opaque_words(word: str) -> def test_opaque_words_are_kept_per_table_on_sqlserver() -> None: - """A SQL Server index name is unique only within its table, so a plain ix on u must not hide - the partial ix on t.""" + """A SQL Server index name is unique only within its table, so dropping ix on u must not forget + the partial ix on t. (A second ix on u now raises on its own: see + test_a_second_create_index_of_a_held_name_raises.)""" with pytest.raises(ValueError, match="drop column"): declared_schema( ( "CREATE TABLE t (a INT NULL, c INT NULL)", "CREATE TABLE u (a INT NULL, c INT NULL)", "CREATE INDEX ix ON t (a) WHERE c > 0", - "CREATE INDEX ix ON u (a)", + "DROP INDEX ix ON u", "ALTER TABLE t DROP COLUMN c", ), "sqlserver", @@ -518,3 +523,172 @@ def test_a_sqlserver_data_statement_ends_an_unterminated_predicate() -> None: "sqlserver", ) assert "ix" in shape.named_indexes + + +# --- BACKLOG #8302 items 3, 5 and 6, and the #5062 remainder built with them ------------------- + + +@pytest.mark.parametrize("second", ["CREATE INDEX ix ON u (a)", "CREATE INDEX ix ON t (c)"]) +def test_a_second_create_index_of_a_held_name_raises(second: str) -> None: + """The expected shape keys an index by name alone. A second ix on another SQL Server table + replaced the first, and one on the same table is skipped by its guard where the first ran.""" + with pytest.raises(ValueError, match="second create index"): + declared_schema( + ( + "CREATE TABLE t (a INT NULL, c INT NULL)", + "CREATE TABLE u (a INT NULL)", + "CREATE INDEX ix ON t (a)", + second, + ), + "sqlserver", + ) + + +def test_an_index_dropped_first_may_be_created_again() -> None: + shape = declared_schema( + ( + "CREATE TABLE t (a INT NULL, c INT NULL)", + "CREATE INDEX ix ON t (a)", + "DROP INDEX ix ON t", + "CREATE INDEX ix ON t (c)", + ), + "sqlserver", + ) + assert shape.named_indexes["ix"].columns == ("c",) + + +def test_an_else_outside_a_case_ends_an_unterminated_predicate() -> None: + """On SQL Server an IF's ELSE starts another statement, whose words are not the index's, so + dropping a column only that statement names keeps the index rather than raising.""" + shape = declared_schema( + ( + "CREATE TABLE t (a INT NULL, c INT NULL, d INT NULL)", + "IF 1 = 1 CREATE INDEX ix ON t (a) WHERE c > 0 ELSE PRINT d", + "ALTER TABLE t DROP COLUMN d", + ), + "sqlserver", + ) + assert "ix" in shape.named_indexes + + +def test_an_else_and_end_inside_a_case_stay_in_the_predicate() -> None: + with pytest.raises(ValueError, match="drop column"): + declared_schema( + ( + "CREATE TABLE t (a INT, c INT, d INT)", + "CREATE INDEX ix ON t (a) WHERE CASE WHEN c > 0 THEN 1 ELSE d END = 1", + "ALTER TABLE t DROP COLUMN d", + ), + "postgres", + ) + + +def test_a_quote_inside_a_subscript_is_a_string() -> None: + """``m['...']`` is a PostgreSQL subscript, not a bracketed name, so the literal inside it is + blanked before the reader looks for the table's PRIMARY KEY, as the other scanners read it.""" + shape = declared_schema( + ("CREATE TABLE t (m JSONB, b INT, CHECK (m['PRIMARY KEY (b)'] IS NULL))",), "postgres" + ) + assert shape.column_shapes["t"]["b"].nullable is True + + +def test_an_index_taking_a_table_name_does_not_hide_that_table() -> None: + """On SQL Server an index may share a table's name. A statistics object holding the index's + name once hid the table's own missing column, and named the table as never created.""" + expected = declared_schema( + ( + "CREATE TABLE foo (a INT NULL, b INT NULL)", + "CREATE TABLE bar (x INT NULL)", + "CREATE INDEX foo ON bar (x)", + ), + "sqlserver", + ) + rows = [("foo", "table", "a", None), ("bar", "table", "x", None)] + with pytest.raises(ServerSchemaMismatchError) as caught: + refuse_short_schema("sqlserver", None, expected, rows, {}, {"foo": "statistics object"}) + assert caught.value.differences == ( + "index 'foo' was never built: the name is taken by a statistics object" + " (expected on bar(x))", + "table 'foo' is missing column 'b'", + ) + + +def test_an_alter_column_that_opens_its_statement_reaches_every_store() -> None: + shape = declared_schema( + ("CREATE TABLE t (a VARCHAR(64))", "ALTER TABLE t ALTER COLUMN a TYPE TEXT"), "postgres" + ) + assert shape.column_shapes["t"]["a"].type == "text" + bin2 = "CREATE TABLE t (a NVARCHAR(64) COLLATE Latin1_General_100_BIN2 NOT NULL)" + plain = "ALTER TABLE t ALTER COLUMN a NVARCHAR(64) NOT NULL" + assert declared_schema((bin2, plain), "sqlserver").column_shapes["t"]["a"].collation is None + + +def test_an_added_primary_key_follows_the_alter_column_rule() -> None: + """An added PRIMARY KEY is read as an ALTER COLUMN SET NOT NULL is: everywhere when it opens + its statement, and otherwise only on an older store, so a nullable CREATE TABLE raises.""" + created = "CREATE TABLE t (a INT)" + unguarded = declared_schema((created, "ALTER TABLE t ADD PRIMARY KEY (a)"), "postgres") + assert unguarded.column_shapes["t"]["a"].nullable is False + for guarded in ( + "DO $$ BEGIN ALTER TABLE t ADD PRIMARY KEY (a); END $$", + "DO $$ BEGIN ALTER TABLE t ALTER COLUMN a SET NOT NULL; END $$", + ): + with pytest.raises(ValueError, match="built two ways"): + declared_schema((created, guarded), "postgres") + + +@pytest.mark.parametrize( + "statement", + [ + "IF 1 = 0 PRINT 'ALTER TABLE t ADD b INT NULL'", + "DECLARE @s nvarchar(100) = N'ALTER TABLE t ADD b INT NULL'", + "SELECT 'CREATE INDEX ix ON t (a)'", + ], +) +def test_ddl_in_a_literal_no_exec_runs_raises(statement: str) -> None: + with pytest.raises(ValueError, match="no EXEC runs"): + declared_schema(("CREATE TABLE t (a INT NULL)", statement), "sqlserver") + + +@pytest.mark.parametrize( + "statement", + [ + "EXEC(N'ALTER TABLE t ADD b INT NULL')", + "DECLARE @s nvarchar(100) = N'ALTER TABLE t ADD b INT NULL'; EXEC(@s)", + "EXEC sp_executesql N'ALTER TABLE t ADD b INT NULL'", + ], +) +def test_ddl_in_a_literal_an_exec_runs_is_read(statement: str) -> None: + shape = declared_schema(("CREATE TABLE t (a INT NULL)", statement), "sqlserver") + assert shape.columns["t"] == frozenset({"a", "b"}) + + +def test_ddl_in_a_literal_joined_to_more_text_raises() -> None: + """The literal cut the clause short: ``DROP COLUMN b`` read alone left c expected.""" + with pytest.raises(ValueError, match="joins to more text"): + declared_schema( + ( + "CREATE TABLE t (a INT NULL, b INT NULL, c INT NULL)", + "EXEC(N'ALTER TABLE t DROP COLUMN b' + N', COLUMN c')", + ), + "sqlserver", + ) + + +def test_a_drop_constraint_named_by_quotename_is_still_read() -> None: + shape = declared_schema( + ( + "CREATE TABLE t (a INT NOT NULL)", + "DECLARE @drop nvarchar(400) = N'ALTER TABLE t DROP CONSTRAINT ' + QUOTENAME(@pk);" + " EXEC(@drop);", + ), + "sqlserver", + ) + assert shape.columns["t"] == frozenset({"a"}) + + +def test_a_default_of_more_than_one_token_is_named_as_the_default() -> None: + with pytest.raises(ValueError, match="a default the live-schema check cannot read"): + declared_schema( + ("CREATE TABLE t (a TIMESTAMPTZ DEFAULT now() + interval '1 day')",), "postgres" + ) diff --git a/tests/test_sqlserver_postgres_schema_verify_1720.py b/tests/test_sqlserver_postgres_schema_verify_1720.py index 518351367b..6333bafb56 100644 --- a/tests/test_sqlserver_postgres_schema_verify_1720.py +++ b/tests/test_sqlserver_postgres_schema_verify_1720.py @@ -344,7 +344,10 @@ def test_the_compare_names_each_shortfall_and_tolerates_extras() -> None: def test_a_name_held_by_another_kind_of_object_says_so() -> None: expected = live_shape({"queue": {"seq"}, "messages": {"id"}}, {_FIFO: _FIFO_SHAPE}) live = live_shape({"queue": {"seq"}}, {}) - assert server_schema_differences(expected, live, {_FIFO: "table", "messages": "index"}) == [ + taken_tables = {"messages": "index"} + assert server_schema_differences( + expected, live, {_FIFO: "table"}, taken_tables=taken_tables + ) == [ f"index {_FIFO!r} was never built: the name is taken by a table" " (expected on queue(stage, channel_id, status, seq))", "table 'messages' was never created: the name is taken by an index", @@ -1493,14 +1496,17 @@ def test_a_guarded_alter_column_that_a_new_store_never_runs_must_match_the_creat declared_schema((create, widen), "sqlserver") # SQL Server resets an altered column's collation unless the ALTER restates it. bin2 = "CREATE TABLE t (a NVARCHAR(64) COLLATE Latin1_General_100_BIN2 NOT NULL)" - plain = "ALTER TABLE t ALTER COLUMN a NVARCHAR(64) NOT NULL" + plain = "IF 1 = 1 ALTER TABLE t ALTER COLUMN a NVARCHAR(64) NOT NULL" with pytest.raises(ValueError, match="built two ways"): declared_schema((bin2, plain), "sqlserver") restated = "ALTER TABLE t ALTER COLUMN a NVARCHAR(64) COLLATE Latin1_General_100_BIN2 NOT NULL" assert declared_schema((bin2, restated), "sqlserver").column_shapes["t"]["a"].collation with pytest.raises(ValueError, match="built two ways"): declared_schema( - ("CREATE TABLE t (a VARCHAR(64))", "ALTER TABLE t ALTER COLUMN a TYPE TEXT"), + ( + "CREATE TABLE t (a VARCHAR(64))", + "DO $$ BEGIN ALTER TABLE t ALTER COLUMN a TYPE TEXT; END $$", + ), "postgres", ) @@ -1651,8 +1657,8 @@ def test_a_nextval_default_reads_as_numbered_without_not_null() -> None: assert declared_column("postgres", "a BIGINT DEFAULT 0") == ColumnShape("bigint", True) created = declared_schema(("CREATE TABLE t (a BIGINT DEFAULT nextval('s'))",), "postgres") assert created.column_shapes["t"]["a"] == ColumnShape("bigint", True, True) - # An ALTER COLUMN reaches only an older store, so its result must match the CREATE: a nextval() - # default it sets or drops changes the numbering, and any other default does not. + # A guarded ALTER COLUMN reaches only an older store, so its result must match the CREATE: a + # nextval() default it sets or drops changes the numbering, and any other default does not. same = declared_schema( ( "CREATE TABLE t (a BIGINT DEFAULT nextval('s'), b INT)", @@ -1666,13 +1672,16 @@ def test_a_nextval_default_reads_as_numbered_without_not_null() -> None: declared_schema( ( "CREATE TABLE t (a BIGINT DEFAULT nextval('s'))", - "ALTER TABLE t ALTER COLUMN a DROP DEFAULT", + "DO $$ BEGIN ALTER TABLE t ALTER COLUMN a DROP DEFAULT; END $$", ), "postgres", ) with pytest.raises(ValueError, match="built two ways"): declared_schema( - ("CREATE TABLE t (a BIGINT)", "ALTER TABLE t ALTER COLUMN a SET DEFAULT nextval('s')"), + ( + "CREATE TABLE t (a BIGINT)", + "DO $$ BEGIN ALTER TABLE t ALTER COLUMN a SET DEFAULT nextval('s'); END $$", + ), "postgres", ) diff --git a/tests/test_store_schema_hash.py b/tests/test_store_schema_hash.py index 82f1ad8599..b873c03c72 100644 --- a/tests/test_store_schema_hash.py +++ b/tests/test_store_schema_hash.py @@ -144,7 +144,12 @@ def test_a_marker_from_before_the_live_schema_check_takes_the_slow_path() -> Non ms_input = unchecked + f"\nschema_check_rev={rev}" assert hashlib.sha256(ms_input.encode()).hexdigest() == sqlserver._schema_hash() # SQL Server alone wrote a revision before this one; Postgres's earlier marker is pg_before. + # Given the control above, an inequality against a hand-built marker cannot fail, so the marker + # one revision back is the one _schema_hash itself writes at that revision (BACKLOG #5062). previous = "\n".join(sqlserver._SCHEMA) + f"\nschema_check_rev={rev - 1}" + with pytest.MonkeyPatch.context() as patch: + patch.setattr(server_schema_verify, "SCHEMA_CHECK_REV", rev - 1) + assert sqlserver._schema_hash() == hashlib.sha256(previous.encode()).hexdigest() assert hashlib.sha256(previous.encode()).hexdigest() != sqlserver._schema_hash() From 3bc23a088df69a13316c625991fee73d54299d06 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 01:38:09 -0600 Subject: [PATCH 2/7] Server schema check: hold nested literals to the EXEC rule, keyword the taken maps Review round 1 (round-63db071ad9) repairs, BACKLOG #5062. - A literal an EXEC runs is read again as SQL of its own, its quotes undoubled, so DDL in a literal inside it is held to the same rule. - An EXEC(@var) found only inside a literal no longer counts as running the variable. EXECUTE without a parenthesis, sp_executesql @stmt = and DECLARE @v AS are read as running their literal. - server_schema_differences takes taken_indexes, taken_tables and unusable as keyword arguments, so a caller passing tables where only indexes now go fails loudly rather than compares them as indexes. - Module docstring: what raises is stated as the code does it, the every-store rule is per batch entry, and the PostgreSQL dollar-quoted body caveat is kept. - test_store_schema_hash is back to main's text: the added assertion covered nothing the existing tests miss. --- messagefoundry/store/server_schema_verify.py | 109 +++++++++++------- tests/test_keyring_schema_3411.py | 4 +- tests/test_server_schema_verify_5062.py | 17 ++- ...t_sqlserver_postgres_schema_verify_1720.py | 24 ++-- tests/test_store_schema_hash.py | 5 - 5 files changed, 97 insertions(+), 62 deletions(-) diff --git a/messagefoundry/store/server_schema_verify.py b/messagefoundry/store/server_schema_verify.py index 366c303149..7799e546b0 100644 --- a/messagefoundry/store/server_schema_verify.py +++ b/messagefoundry/store/server_schema_verify.py @@ -41,8 +41,10 @@ ``CREATE ... INDEX``, ``CREATE TABLE``, ``DROP TABLE``, ``DROP INDEX`` or ``sp_rename`` its patterns do not match, an ``ALTER TABLE`` with more than one clause or an action it does not know, a table rename, an ``ALTER INDEX``, a second ``CREATE TABLE`` of a table no ``DROP`` removed, a second ``CREATE -INDEX`` of a name no ``DROP INDEX`` freed, DDL in a string literal that no ``EXEC`` runs or that a -``+`` joins to more text, a default of more than one token, a ``USING`` access +INDEX`` of a name an index it read still holds, DDL in a single-quoted string literal the reader +sees no ``EXEC`` run, at any depth of ``EXEC``, or that a ``+`` joins to more text (other than a +``DROP CONSTRAINT`` named by ``QUOTENAME``), a default followed by a token that opens no column +clause, a ``USING`` access method, a key column or expression carrying a collation, an operator class or a ``NULLS`` order, a key that opens with a ``::`` or ``CAST`` cast of a column, a key built ``USING INDEX``, a SQL Server inline ``INDEX``, a ``NOT NULL`` table constraint, a column type or clause it does not know, a SQL @@ -50,11 +52,13 @@ or ``/*`` inside a quoted string, which may be dynamic SQL's comment or a literal's text. A unit test reads each shipped batch, so a new form fails there before it reaches an open. -An ``ALTER COLUMN`` or added ``PRIMARY KEY`` that opens its statement is read as reaching every -store, and one with anything before it as reaching only an older store, so the latter raises where -its result differs from the ``CREATE TABLE``, even if its guard would hold on a new store too. +An ``ALTER COLUMN`` or added ``PRIMARY KEY`` that opens its entry in the batch, with nothing +before it, is read as reaching every store, and one with anything before it, even a statement a +``;`` ends, as reaching only an older store, so the latter raises where its result differs from +the ``CREATE TABLE``, even if it would run on a new store too. -Not every misread raises (BACKLOG #5062). At least: a +Not every misread raises (BACKLOG #5062). At least: DDL in a PostgreSQL dollar-quoted body is read +as run, a function's body included, which runs only when it is called; and a ``DROP COLUMN`` raises where the reader finds the column's name among the words of an expression, ``INCLUDE`` or partial index on its table, other than as a key column, but that word search can miss a name, so a ``DROP COLUMN`` that should raise may instead keep an index PostgreSQL drops. @@ -885,7 +889,7 @@ class _Built: and what an ``ALTER COLUMN`` or an added ``PRIMARY KEY`` leaves on an older store. A guarded one is not taken to reach a new store, because its guard may test for the old state: its result must equal ``create``, or the column is built two ways. An ``ALTER TABLE`` that opens its - statement, with nothing before it, runs on every store, so it changes ``create`` too (BACKLOG + entry in the batch, with nothing before it, runs on every store, so it changes ``create`` too (BACKLOG #5062).""" create: ColumnShape | None = None @@ -1050,13 +1054,12 @@ def _built(self, table: str, name: str, action: str) -> _Built: def alter(self, text: str, m: re.Match[str], spans: list[tuple[int, int]]) -> None: table = _bare(m["table"]) segment = text[m.end() :] - # Only an ALTER TABLE that opens its statement is known to run on every store; anything + # Only an ALTER TABLE that opens its batch entry is known to run on every store; anything # before it, an IF or an EXEC among them, may guard it (BACKLOG #5062). everywhere = not text[: m.start()].strip() - for start, end in spans: - if start < m.start() < end: # inside an EXEC string: its own text, quotes undoubled - segment = text[m.end() : end - 1].replace("''", "'") - break + if span := _enclosing_span(spans, m.start()): + # Inside an EXEC string: its own text, quotes undoubled. + segment = text[m.end() : span[1] - 1].replace("''", "'") # SQL Server's WITH [NO]CHECK says whether an added constraint checks the existing rows. clause = re.sub(r"^WITH\s+(?:NO)?CHECK\s+(?=ADD\b)", "", _clause(segment), flags=re.I) words = clause.split() @@ -1236,38 +1239,55 @@ def shape(self) -> ServerSchemaShape: ) -#: What opens a string literal that SQL Server runs as SQL: an ``EXEC`` or ``sp_executesql`` -#: argument, or a value assigned to a variable, which counts only once an ``EXEC`` runs that -#: variable later in the statement. -_EXEC_LITERAL = re.compile(r"\b(?:EXEC(?:UTE)?\s*\(|sp_executesql)\s*N?$", re.I) -_ASSIGNED_LITERAL = re.compile(r"@(?P\w+)(?:\s+\w+(?:\s*\([^()]*\))?)?\s*=\s*N?$", re.I) +#: What opens a string literal the server runs as SQL: an ``EXEC`` or ``EXECUTE`` argument, an +#: ``sp_executesql`` statement, or a value assigned to a variable, which counts only once an +#: ``EXEC`` outside any literal runs that variable later in the text. +_EXEC_LITERAL = re.compile( + r"\b(?:EXEC(?:UTE)?\s*\(\s*|EXECUTE\s+|sp_executesql\s+(?:@\w+\s*=\s*)?)N?$", re.I +) +_ASSIGNED_LITERAL = re.compile( + r"@(?P\w+)(?:\s+(?:AS\s+)?\w+(?:\s*\([^()]*\))?)?\s*=\s*N?$", re.I +) #: A literal joined to a quoted name and nothing else, as a ``DROP CONSTRAINT`` takes its name. _QUOTENAME_TAIL = re.compile(r"\s*\+\s*QUOTENAME\s*\(\s*@\w+\s*\)\s*(?:;|$)", re.I) -def _check_literal(text: str, spans: list[tuple[int, int]], kind: str, m: re.Match[str]) -> None: - """Raise when DDL the reader matched sits in a string literal it cannot read as run (BACKLOG - #5062): one that no ``EXEC`` runs, which the server never executes, or one joined to more text - by ``+``, whose clause the literal cuts short. The one join read is an ``ALTER TABLE ... DROP - CONSTRAINT`` given its name by ``QUOTENAME``, a clause the reader does not apply.""" - span = next(((start, end) for start, end in spans if start < m.start() < end), None) - if span is None: +def _enclosing_span(spans: list[tuple[int, int]], pos: int) -> tuple[int, int] | None: + """The string literal of ``spans`` that ``pos`` lies inside, or ``None``.""" + return next(((start, end) for start, end in spans if start < pos < end), None) + + +def _check_literal( + text: str, spans: list[tuple[int, int]], kind: str, at: int, stop: int, label: str +) -> None: + """Raise when DDL the reader matched, ``text[at:stop]``, sits in a string literal it cannot + read as run (BACKLOG #5062): one it sees no ``EXEC`` run, or one joined to more text by ``+``, + whose clause the literal cuts short. The one join read is an ``ALTER TABLE ... DROP + CONSTRAINT`` given its name by ``QUOTENAME``, a clause the reader does not apply. A literal + that is run is read again as SQL of its own, its quotes undoubled, so a literal inside it + is held to the same rule.""" + if (span := _enclosing_span(spans, at)) is None: return start, end = span - before = text[:start] - run = _EXEC_LITERAL.search(before) is not None - if not run and (assigned := _ASSIGNED_LITERAL.search(before)): + run = _EXEC_LITERAL.search(text, 0, start) is not None + if not run and (assigned := _ASSIGNED_LITERAL.search(text, 0, start)): var = assigned["var"] - runs = rf"\b(?:EXEC(?:UTE)?\s*\(\s*@{var}\s*\)|sp_executesql\s+@{var}\b)" - run = re.search(runs, text[end:], re.I) is not None + runs = re.compile(rf"\b(?:EXEC(?:UTE)?\s*\(\s*@{var}\s*\)|sp_executesql\s+@{var}\b)", re.I) + run = any(_enclosing_span(spans, f.start()) is None for f in runs.finditer(text, end)) if not run: - raise ValueError(f"DDL inside a string literal that no EXEC runs: {m.group(0)[:120]!r}") + raise ValueError( + f"DDL inside a string literal the reader sees no EXEC run: {label[:120]!r}" + ) if text[end:].lstrip().startswith("+") and not ( kind == "alter" - and re.fullmatch(r"\s*DROP\s+CONSTRAINT\s*", text[m.end() : end - 1], re.I) + and re.fullmatch(r"\s*DROP\s+CONSTRAINT\s*", text[stop : end - 1], re.I) and _QUOTENAME_TAIL.match(text, end) ): - raise ValueError(f"DDL in a string literal that a + joins to more text: {m.group(0)!r}") + raise ValueError(f"DDL in a string literal that a + joins to more text: {label!r}") + body = text[start + 1 : end - 1].replace("''", "'") + offset = len(text[start + 1 : at].replace("''", "'")) + length = len(text[at:stop].replace("''", "'")) + _check_literal(body, _string_spans(body), kind, offset, offset + length, label) @cache @@ -1304,7 +1324,7 @@ def declared_schema( ): events.extend((m.start(), kind, m) for m in pattern.finditer(text)) for _pos, kind, m in sorted(events, key=lambda e: e[0]): - _check_literal(text, spans, kind, m) + _check_literal(text, spans, kind, m.start(), m.end(), m.group(0)) if kind == "table": reader.table(text, m) elif kind == "index": @@ -1330,23 +1350,24 @@ def _a(noun: str) -> str: def server_schema_differences( expected: SchemaShape, live: SchemaShape, - taken: Mapping[str, str], - unusable: Mapping[str, str] | None = None, *, + taken_indexes: Mapping[str, str] | None = None, taken_tables: Mapping[str, str] | None = None, + unusable: Mapping[str, str] | None = None, ) -> list[str]: """Every way ``live`` falls short of ``expected``, one clause each. Extras are not listed. - ``taken`` maps an expected index name to the kind of object that holds it instead (a table - holding an index's name), and ``taken_tables`` an expected table name (a view holding a - table's). They are kept apart because on SQL Server an index may share a table's name, so a - name taken from one must not hide the other's clauses (BACKLOG #5062). Such a name gets its own - clause, which says why the guarded ``CREATE`` skipped it, in place of a bare "is missing". - ``unusable`` maps an + ``taken_indexes`` maps an expected index name to the kind of object that holds it instead (a + table holding an index's name), and ``taken_tables`` an expected table name (a view holding a + table's). They are kept apart, and keyword-only, because on SQL Server an index may share a + table's name, so a name taken from one must not hide the other's clauses (BACKLOG #5062). Such + a name gets its own clause, which says why the guarded ``CREATE`` skipped it, in place of a + bare "is missing". ``unusable`` maps an expected index that exists under its name to why it cannot serve, such as ``disabled``. A column both shapes describe is compared by :meth:`ColumnShape.core_differs` and :meth:`ColumnShape.collation_differs`, one clause for each that differs.""" unusable = unusable or {} + taken = taken_indexes or {} taken_tables = taken_tables or {} problems: list[str] = [] for name in sorted({*taken_tables, *taken}): @@ -1519,7 +1540,11 @@ def refuse_short_schema( if shape is not None: shapes.setdefault(table, {})[column] = shape problems = server_schema_differences( - expected, live_shape(columns, indexes, shapes), taken, unusable, taken_tables=taken_tables + expected, + live_shape(columns, indexes, shapes), + taken_indexes=taken, + taken_tables=taken_tables, + unusable=unusable, ) if problems: exc = ServerSchemaMismatchError(backend, database, problems, schema) diff --git a/tests/test_keyring_schema_3411.py b/tests/test_keyring_schema_3411.py index 2feb5421cf..4c5a92453c 100644 --- a/tests/test_keyring_schema_3411.py +++ b/tests/test_keyring_schema_3411.py @@ -188,7 +188,7 @@ def test_each_server_check_refuses_a_store_without_the_keyring(backend: str) -> """The verifier expects what the batch declares: a store provisioned before the keyring existed is refused until it is provisioned again, and one with it passes.""" declared = pg_declared() if backend == "postgres" else mssql_declared() - assert server_schema_differences(declared, declared, {}) == [] + assert server_schema_differences(declared, declared) == [] columns = {t: set(c) for t, c in declared.columns.items() if t != "keyring"} before = live_shape(columns, dict(declared.named_indexes)) - assert server_schema_differences(declared, before, {}) == ["table 'keyring' is missing"] + assert server_schema_differences(declared, before) == ["table 'keyring' is missing"] diff --git a/tests/test_server_schema_verify_5062.py b/tests/test_server_schema_verify_5062.py index 238996c6db..f7d01c378a 100644 --- a/tests/test_server_schema_verify_5062.py +++ b/tests/test_server_schema_verify_5062.py @@ -643,10 +643,15 @@ def test_an_added_primary_key_follows_the_alter_column_rule() -> None: "IF 1 = 0 PRINT 'ALTER TABLE t ADD b INT NULL'", "DECLARE @s nvarchar(100) = N'ALTER TABLE t ADD b INT NULL'", "SELECT 'CREATE INDEX ix ON t (a)'", + # A literal inside an EXEC string is held to the same rule, at any depth. + "EXEC('PRINT ''ALTER TABLE t ADD b INT NULL''')", + "EXEC('EXEC(''PRINT ''''ALTER TABLE t ADD b INT NULL'''''')')", + # An EXEC that is itself only a literal's text runs nothing. + "DECLARE @s nvarchar(99) = N'ALTER TABLE t ADD b INT NULL'; PRINT 'EXEC(@s)'", ], ) def test_ddl_in_a_literal_no_exec_runs_raises(statement: str) -> None: - with pytest.raises(ValueError, match="no EXEC runs"): + with pytest.raises(ValueError, match="sees no EXEC run"): declared_schema(("CREATE TABLE t (a INT NULL)", statement), "sqlserver") @@ -655,7 +660,9 @@ def test_ddl_in_a_literal_no_exec_runs_raises(statement: str) -> None: [ "EXEC(N'ALTER TABLE t ADD b INT NULL')", "DECLARE @s nvarchar(100) = N'ALTER TABLE t ADD b INT NULL'; EXEC(@s)", + "DECLARE @s AS nvarchar(100) = N'ALTER TABLE t ADD b INT NULL'; EXEC(@s)", "EXEC sp_executesql N'ALTER TABLE t ADD b INT NULL'", + "EXEC sp_executesql @stmt = N'ALTER TABLE t ADD b INT NULL'", ], ) def test_ddl_in_a_literal_an_exec_runs_is_read(statement: str) -> None: @@ -663,6 +670,14 @@ def test_ddl_in_a_literal_an_exec_runs_is_read(statement: str) -> None: assert shape.columns["t"] == frozenset({"a", "b"}) +def test_ddl_in_a_plpgsql_execute_literal_is_read() -> None: + shape = declared_schema( + ("CREATE TABLE t (a INT)", "DO $$ BEGIN EXECUTE 'ALTER TABLE t ADD COLUMN b INT'; END $$"), + "postgres", + ) + assert shape.columns["t"] == frozenset({"a", "b"}) + + def test_ddl_in_a_literal_joined_to_more_text_raises() -> None: """The literal cut the clause short: ``DROP COLUMN b`` read alone left c expected.""" with pytest.raises(ValueError, match="joins to more text"): diff --git a/tests/test_sqlserver_postgres_schema_verify_1720.py b/tests/test_sqlserver_postgres_schema_verify_1720.py index 6333bafb56..d6f0128f68 100644 --- a/tests/test_sqlserver_postgres_schema_verify_1720.py +++ b/tests/test_sqlserver_postgres_schema_verify_1720.py @@ -310,7 +310,7 @@ def test_a_quoted_name_keeps_its_case_and_an_unquoted_one_folds() -> None: assert key_column('"ID"') == "ID" live = live_shape({"t": {"ID"}}, {}) expected = live_shape({"t": {"id"}}, {}) - assert server_schema_differences(expected, live, {}) == ["table 't' is missing column 'id'"] + assert server_schema_differences(expected, live) == ["table 't' is missing column 'id'"] def test_key_columns_normalise_the_same_way_on_both_sides() -> None: @@ -327,14 +327,14 @@ def test_key_columns_normalise_the_same_way_on_both_sides() -> None: def test_the_compare_names_each_shortfall_and_tolerates_extras() -> None: expected = live_shape({"queue": {"stage", "seq"}, "messages": {"id"}}, {_FIFO: _FIFO_SHAPE}) - assert server_schema_differences(expected, expected, {}) == [] + assert server_schema_differences(expected, expected) == [] extra = live_shape( {"queue": {"stage", "seq", "extra"}, "messages": {"id"}, "other": {"x"}}, {_FIFO: _FIFO_SHAPE, "ix_mine": IndexShape("queue", ("extra",), False, False)}, ) - assert server_schema_differences(expected, extra, {}) == [] + assert server_schema_differences(expected, extra) == [] short = live_shape({"queue": {"stage"}}, {_FIFO: IndexShape("queue", ("stage",), False, False)}) - assert server_schema_differences(expected, short, {}) == [ + assert server_schema_differences(expected, short) == [ "table 'messages' is missing", "table 'queue' is missing column 'seq'", f"index {_FIFO!r} is on queue(stage), expected on queue(stage, channel_id, status, seq)", @@ -346,7 +346,7 @@ def test_a_name_held_by_another_kind_of_object_says_so() -> None: live = live_shape({"queue": {"seq"}}, {}) taken_tables = {"messages": "index"} assert server_schema_differences( - expected, live, {_FIFO: "table"}, taken_tables=taken_tables + expected, live, taken_indexes={_FIFO: "table"}, taken_tables=taken_tables ) == [ f"index {_FIFO!r} was never built: the name is taken by a table" " (expected on queue(stage, channel_id, status, seq))", @@ -357,7 +357,7 @@ def test_a_name_held_by_another_kind_of_object_says_so() -> None: def test_an_index_that_exists_but_cannot_serve_says_why() -> None: expected = live_shape({"queue": {"seq"}}, {_FIFO: _FIFO_SHAPE}) live = live_shape({"queue": {"seq"}}, {_FIFO: _FIFO_SHAPE}) - assert server_schema_differences(expected, live, {}, {_FIFO: "disabled"}) == [ + assert server_schema_differences(expected, live, unusable={_FIFO: "disabled"}) == [ f"index {_FIFO!r} exists but is disabled" " (expected on queue(stage, channel_id, status, seq))" ] @@ -1294,8 +1294,8 @@ def test_a_column_of_another_type_nullability_or_numbering_refuses( ) -> None: expected = live_shape({"t": {"a"}}, {}, {"t": {"a": ColumnShape("integer", False)}}) got = live_shape({"t": {"a"}}, {}, {"t": {"a": live}}) - assert server_schema_differences(expected, got, {}) == [f"table 't' column 'a' {clause}"] - assert server_schema_differences(expected, expected, {}) == [] + assert server_schema_differences(expected, got) == [f"table 't' column 'a' {clause}"] + assert server_schema_differences(expected, expected) == [] def test_a_collation_is_compared_only_where_the_batch_declares_one() -> None: @@ -1305,13 +1305,13 @@ def test_a_collation_is_compared_only_where_the_batch_declares_one() -> None: live = live_shape( {"t": {"a", "b"}}, {}, {"t": {"a": ci, "b": ColumnShape("int", True, False, "any")}} ) - assert server_schema_differences(expected, live, {}) == [ + assert server_schema_differences(expected, live) == [ "table 't' column 'a' has collation 'SQL_Latin1_General_CP1_CI_AS'," " expected 'latin1_general_100_bin2'" ] upper = ColumnShape("nvarchar(64)", False, False, "Latin1_General_100_BIN2") same = live_shape({"t": {"a", "b"}}, {}, {"t": {"a": upper}}) - assert server_schema_differences(expected, same, {}) == [] + assert server_schema_differences(expected, same) == [] def test_refuse_short_schema_reads_each_columns_shape_and_an_empty_table() -> None: @@ -1565,7 +1565,7 @@ def test_an_index_named_like_a_table_does_not_hide_the_table() -> None: {"roles": IndexShape("other", ("x",), False, False)}, {"roles": {"id": ColumnShape("bigint", False)}}, ) - assert server_schema_differences(expected, live, {}, {"roles": "disabled"}) == [ + assert server_schema_differences(expected, live, unusable={"roles": "disabled"}) == [ "index 'roles' exists but is disabled (expected on other(x))", "table 'roles' is missing column 'name'", "table 'roles' column 'id' is bigint not null, expected int not null", @@ -1595,7 +1595,7 @@ def test_the_refusal_survives_the_log_redaction_and_the_safe_exc_cut() -> None: got = live_shape( {"connection_state": {"connection"}}, {}, {"connection_state": {"connection": live_col}} ) - exc = ServerSchemaMismatchError("sqlserver", None, server_schema_differences(expected, got, {})) + exc = ServerSchemaMismatchError("sqlserver", None, server_schema_differences(expected, got)) core = ( "table 'connection_state' column 'connection' is nvarchar(256) null," " expected nvarchar(256) identity not null" diff --git a/tests/test_store_schema_hash.py b/tests/test_store_schema_hash.py index b873c03c72..82f1ad8599 100644 --- a/tests/test_store_schema_hash.py +++ b/tests/test_store_schema_hash.py @@ -144,12 +144,7 @@ def test_a_marker_from_before_the_live_schema_check_takes_the_slow_path() -> Non ms_input = unchecked + f"\nschema_check_rev={rev}" assert hashlib.sha256(ms_input.encode()).hexdigest() == sqlserver._schema_hash() # SQL Server alone wrote a revision before this one; Postgres's earlier marker is pg_before. - # Given the control above, an inequality against a hand-built marker cannot fail, so the marker - # one revision back is the one _schema_hash itself writes at that revision (BACKLOG #5062). previous = "\n".join(sqlserver._SCHEMA) + f"\nschema_check_rev={rev - 1}" - with pytest.MonkeyPatch.context() as patch: - patch.setattr(server_schema_verify, "SCHEMA_CHECK_REV", rev - 1) - assert sqlserver._schema_hash() == hashlib.sha256(previous.encode()).hexdigest() assert hashlib.sha256(previous.encode()).hexdigest() != sqlserver._schema_hash() From 8fe47bc943911262a4483a229b3e0a1c4ec1db49 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 02:22:16 -0600 Subject: [PATCH 3/7] Server schema check: tighten what reads a literal as run, keep a renamed column's create shape Review round 2 (round-3b9e84ac9c) repairs, BACKLOG #5062. - A literal joined by || raises as one joined by + does. - A variable assigned a literal counts as run only when DECLARE or SET assigns it, and no SET, SELECT or compound assignment changes it before the EXEC that runs it. - EXECUTE without a parenthesis runs its literal off SQL Server only. - The QUOTENAME DROP CONSTRAINT join may also end at the EXEC's ). - A column rename keeps the CREATE TABLE shape as the create one, so a guarded ALTER COLUMN after it is still held to it. - index() takes the statement's spans, as alter() does. - Module docstring: the procedure-body and variable caveats are listed. Proposed PR title: Server schema check reads more DDL forms or raises (BACKLOG #5062, #8302 items 3, 5, 6) Proposed banners: #5062 PARTIAL: built skip_tables from taken, the unguarded ALTER COLUMN, DDL in a literal no EXEC runs, EXEC-string cut clauses, ADD PRIMARY KEY against SET NOT NULL, multi-token DEFAULT messages. Remains: cross-type default opclass, the first parse on the event loop, scratch-schema altitude, the lower-cased refusal, item 6, item 7's postgres.py rollback finding, the dead label branch, test_store_schema_hash's cannot-fail assertion. #8302 PARTIAL: items 3, 5 and 6 built. --- messagefoundry/store/server_schema_verify.py | 107 ++++++++++++------- tests/test_server_schema_verify_5062.py | 75 +++++++++++-- 2 files changed, 135 insertions(+), 47 deletions(-) diff --git a/messagefoundry/store/server_schema_verify.py b/messagefoundry/store/server_schema_verify.py index 7799e546b0..afcbe9ab6d 100644 --- a/messagefoundry/store/server_schema_verify.py +++ b/messagefoundry/store/server_schema_verify.py @@ -42,9 +42,9 @@ not match, an ``ALTER TABLE`` with more than one clause or an action it does not know, a table rename, an ``ALTER INDEX``, a second ``CREATE TABLE`` of a table no ``DROP`` removed, a second ``CREATE INDEX`` of a name an index it read still holds, DDL in a single-quoted string literal the reader -sees no ``EXEC`` run, at any depth of ``EXEC``, or that a ``+`` joins to more text (other than a -``DROP CONSTRAINT`` named by ``QUOTENAME``), a default followed by a token that opens no column -clause, a ``USING`` access +sees no ``EXEC`` run, that a ``+`` or ``||`` joins to more text (other than a ``DROP CONSTRAINT`` +whose name a ``+ QUOTENAME(@x)`` ending the statement or the ``EXEC`` supplies), each at any +depth of ``EXEC``, a default followed by a token that opens no column clause, a ``USING`` access method, a key column or expression carrying a collation, an operator class or a ``NULLS`` order, a key that opens with a ``::`` or ``CAST`` cast of a column, a key built ``USING INDEX``, a SQL Server inline ``INDEX``, a ``NOT NULL`` table constraint, a column type or clause it does not know, a SQL @@ -57,8 +57,10 @@ ``;`` ends, as reaching only an older store, so the latter raises where its result differs from the ``CREATE TABLE``, even if it would run on a new store too. -Not every misread raises (BACKLOG #5062). At least: DDL in a PostgreSQL dollar-quoted body is read -as run, a function's body included, which runs only when it is called; and a +Not every misread raises (BACKLOG #5062). At least: DDL in a PostgreSQL dollar-quoted body, or in +a T-SQL procedure's body, is read as run, though a function's or a procedure's body runs only when +it is called; a literal a variable holds is read as run by an ``EXEC`` of that variable whatever +the text between them does to it, other than a ``SET`` or ``SELECT`` that assigns it; and a ``DROP COLUMN`` raises where the reader finds the column's name among the words of an expression, ``INCLUDE`` or partial index on its table, other than as a key column, but that word search can miss a name, so a ``DROP COLUMN`` that should raise may instead keep an index PostgreSQL drops. @@ -1000,7 +1002,7 @@ def table(self, text: str, m: re.Match[str]) -> None: else: built.later.add(shape) - def index(self, text: str, m: re.Match[str]) -> None: + def index(self, text: str, m: re.Match[str], spans: list[tuple[int, int]]) -> None: if m["using"]: raise ValueError(f"index access method not compared: {m.group(0)!r}") body, end = _balanced(text, m.end()) @@ -1031,10 +1033,8 @@ def index(self, text: str, m: re.Match[str]) -> None: # To the statement's end: a predicate has no closing mark of its own. Inside an # EXEC string, to the string's end, its quotes undoubled, as alter() reads one. tail = text[end:] - for start, stop in _string_spans(text): - if start < m.start() < stop: - tail = text[end : stop - 1].replace("''", "'") - break + if span := _enclosing_span(spans, m.start()): + tail = text[end : span[1] - 1].replace("''", "'") tail = " " + tail # so the scan never starts at index 0 # Nested dynamic SQL's quotes can defeat the scan: keep it all, which only raises more. with contextlib.suppress(ValueError): @@ -1174,7 +1174,13 @@ def _rename(self, table: str, old: str, new: str) -> None: moved = cols.pop(old, None) built = cols.setdefault(new, _Built()) if moved is not None: - built.later |= moved.ways() + # A new store renames what its CREATE TABLE built too, so that shape stays the create + # one, and a later guarded ALTER COLUMN is still held to it (BACKLOG #5062). + if built.create is None: + built.create = moved.create + elif moved.create is not None: + built.later.add(moved.create) + built.later |= moved.later self._rewrite_keys(table, old, new) for (on, index), (used, keys) in list(self.opaque.items()): if on == table: @@ -1240,16 +1246,16 @@ def shape(self) -> ServerSchemaShape: #: What opens a string literal the server runs as SQL: an ``EXEC`` or ``EXECUTE`` argument, an -#: ``sp_executesql`` statement, or a value assigned to a variable, which counts only once an -#: ``EXEC`` outside any literal runs that variable later in the text. -_EXEC_LITERAL = re.compile( - r"\b(?:EXEC(?:UTE)?\s*\(\s*|EXECUTE\s+|sp_executesql\s+(?:@\w+\s*=\s*)?)N?$", re.I -) +#: ``sp_executesql`` statement, PL/pgSQL's ``EXECUTE`` without one, or a value a ``DECLARE`` or +#: ``SET`` gives a variable, which counts only once an ``EXEC`` outside any literal runs that +#: variable later in the text, with no ``SET`` or ``SELECT`` changing it first. +_EXEC_LITERAL = re.compile(r"\b(?:EXEC(?:UTE)?\s*\(\s*|sp_executesql\s+(?:@\w+\s*=\s*)?)N?$", re.I) +_PLPGSQL_EXECUTE = re.compile(r"\bEXECUTE\s+$", re.I) _ASSIGNED_LITERAL = re.compile( - r"@(?P\w+)(?:\s+(?:AS\s+)?\w+(?:\s*\([^()]*\))?)?\s*=\s*N?$", re.I + r"\b(?:DECLARE|SET)\s+@(?P\w+)(?:\s+(?:AS\s+)?\w+(?:\s*\([^()]*\))?)?\s*=\s*N?$", re.I ) #: A literal joined to a quoted name and nothing else, as a ``DROP CONSTRAINT`` takes its name. -_QUOTENAME_TAIL = re.compile(r"\s*\+\s*QUOTENAME\s*\(\s*@\w+\s*\)\s*(?:;|$)", re.I) +_QUOTENAME_TAIL = re.compile(r"\s*\+\s*QUOTENAME\s*\(\s*@\w+\s*\)\s*(?:;|\)|$)", re.I) def _enclosing_span(spans: list[tuple[int, int]], pos: int) -> tuple[int, int] | None: @@ -1257,37 +1263,64 @@ def _enclosing_span(spans: list[tuple[int, int]], pos: int) -> tuple[int, int] | return next(((start, end) for start, end in spans if start < pos < end), None) +def _assigned_and_run(text: str, spans: list[tuple[int, int]], var: str, end: int) -> bool: + """Whether an ``EXEC`` outside any literal runs ``@var`` after ``text[end]``, with no ``SET`` + or ``SELECT`` assigning it, nor a ``+=``, outside a literal in between.""" + runs = re.compile(rf"\b(?:EXEC(?:UTE)?\s*\(\s*@{var}\s*\)|sp_executesql\s+@{var}\b)", re.I) + changes = re.compile(rf"\b(?:SET|SELECT)\s+@{var}\s*[-+*/|&^%]?=|@{var}\s*[-+*/|&^%]=", re.I) + first = next( + (f for f in runs.finditer(text, end) if _enclosing_span(spans, f.start()) is None), None + ) + if first is None: + return False + return not any( + _enclosing_span(spans, c.start()) is None + for c in changes.finditer(text, end, first.start()) + ) + + def _check_literal( - text: str, spans: list[tuple[int, int]], kind: str, at: int, stop: int, label: str + text: str, spans: list[tuple[int, int]], kind: str, m: re.Match[str], dialect: Dialect | None +) -> None: + """Raise when DDL the reader matched sits in a string literal it cannot read as run (BACKLOG + #5062): one it sees no ``EXEC`` run, or one joined to more text by ``+`` or ``||``, whose + clause the literal cuts short. The one join read is an ``ALTER TABLE ... DROP CONSTRAINT`` + given its name by ``QUOTENAME``, a clause the reader does not apply. A literal that is run is + read again as SQL of its own, its quotes undoubled, so a literal inside it is held to the same + rule.""" + _check_literal_at(text, spans, kind, m.start(), m.end(), m.group(0), dialect) + + +def _check_literal_at( + text: str, + spans: list[tuple[int, int]], + kind: str, + at: int, + stop: int, + label: str, + dialect: Dialect | None, ) -> None: - """Raise when DDL the reader matched, ``text[at:stop]``, sits in a string literal it cannot - read as run (BACKLOG #5062): one it sees no ``EXEC`` run, or one joined to more text by ``+``, - whose clause the literal cuts short. The one join read is an ``ALTER TABLE ... DROP - CONSTRAINT`` given its name by ``QUOTENAME``, a clause the reader does not apply. A literal - that is run is read again as SQL of its own, its quotes undoubled, so a literal inside it - is held to the same rule.""" + """:func:`_check_literal` for the DDL at ``text[at:stop]``, one ``EXEC`` depth at a time.""" if (span := _enclosing_span(spans, at)) is None: return start, end = span - run = _EXEC_LITERAL.search(text, 0, start) is not None + run = _EXEC_LITERAL.search(text, 0, start) is not None or ( + dialect != "sqlserver" and _PLPGSQL_EXECUTE.search(text, 0, start) is not None + ) if not run and (assigned := _ASSIGNED_LITERAL.search(text, 0, start)): - var = assigned["var"] - runs = re.compile(rf"\b(?:EXEC(?:UTE)?\s*\(\s*@{var}\s*\)|sp_executesql\s+@{var}\b)", re.I) - run = any(_enclosing_span(spans, f.start()) is None for f in runs.finditer(text, end)) + run = _assigned_and_run(text, spans, assigned["var"], end) if not run: - raise ValueError( - f"DDL inside a string literal the reader sees no EXEC run: {label[:120]!r}" - ) - if text[end:].lstrip().startswith("+") and not ( + raise ValueError(f"DDL inside a string literal the reader sees no EXEC run: {label!r}") + if text[end:].lstrip().startswith(("+", "||")) and not ( kind == "alter" and re.fullmatch(r"\s*DROP\s+CONSTRAINT\s*", text[stop : end - 1], re.I) and _QUOTENAME_TAIL.match(text, end) ): - raise ValueError(f"DDL in a string literal that a + joins to more text: {label!r}") + raise ValueError(f"DDL in a string literal that a join adds more text to: {label!r}") body = text[start + 1 : end - 1].replace("''", "'") offset = len(text[start + 1 : at].replace("''", "'")) length = len(text[at:stop].replace("''", "'")) - _check_literal(body, _string_spans(body), kind, offset, offset + length, label) + _check_literal_at(body, _string_spans(body), kind, offset, offset + length, label, dialect) @cache @@ -1324,11 +1357,11 @@ def declared_schema( ): events.extend((m.start(), kind, m) for m in pattern.finditer(text)) for _pos, kind, m in sorted(events, key=lambda e: e[0]): - _check_literal(text, spans, kind, m.start(), m.end(), m.group(0)) + _check_literal(text, spans, kind, m, dialect) if kind == "table": reader.table(text, m) elif kind == "index": - reader.index(text, m) + reader.index(text, m, spans) elif kind == "alter": reader.alter(text, m, spans) elif kind == "rename": diff --git a/tests/test_server_schema_verify_5062.py b/tests/test_server_schema_verify_5062.py index f7d01c378a..9d904e8cf9 100644 --- a/tests/test_server_schema_verify_5062.py +++ b/tests/test_server_schema_verify_5062.py @@ -680,7 +680,7 @@ def test_ddl_in_a_plpgsql_execute_literal_is_read() -> None: def test_ddl_in_a_literal_joined_to_more_text_raises() -> None: """The literal cut the clause short: ``DROP COLUMN b`` read alone left c expected.""" - with pytest.raises(ValueError, match="joins to more text"): + with pytest.raises(ValueError, match="join adds more text"): declared_schema( ( "CREATE TABLE t (a INT NULL, b INT NULL, c INT NULL)", @@ -690,18 +690,73 @@ def test_ddl_in_a_literal_joined_to_more_text_raises() -> None: ) -def test_a_drop_constraint_named_by_quotename_is_still_read() -> None: - shape = declared_schema( - ( - "CREATE TABLE t (a INT NOT NULL)", - "DECLARE @drop nvarchar(400) = N'ALTER TABLE t DROP CONSTRAINT ' + QUOTENAME(@pk);" - " EXEC(@drop);", - ), - "sqlserver", - ) +def test_ddl_in_a_plpgsql_literal_joined_by_a_pipe_pair_raises() -> None: + with pytest.raises(ValueError, match="join adds more text"): + declared_schema( + ( + "CREATE TABLE t (a INT, b INT, c INT)", + "DO $$ BEGIN EXECUTE 'ALTER TABLE t DROP COLUMN b' || ', DROP COLUMN c'; END $$", + ), + "postgres", + ) + + +@pytest.mark.parametrize( + "statement", + [ + "DECLARE @drop nvarchar(400) = N'ALTER TABLE t DROP CONSTRAINT ' + QUOTENAME(@pk);" + " EXEC(@drop);", + "EXEC(N'ALTER TABLE t DROP CONSTRAINT ' + QUOTENAME(@pk))", + ], +) +def test_a_drop_constraint_named_by_quotename_is_still_read(statement: str) -> None: + shape = declared_schema(("CREATE TABLE t (a INT NOT NULL)", statement), "sqlserver") assert shape.columns["t"] == frozenset({"a"}) +@pytest.mark.parametrize( + "between", + ["SET @s = @s + N', COLUMN c';", "SET @s += N', COLUMN c';", "SELECT @s = N'PRINT 1';"], +) +def test_a_variable_changed_before_its_exec_is_not_read_as_run(between: str) -> None: + with pytest.raises(ValueError, match="sees no EXEC run"): + declared_schema( + ( + "CREATE TABLE t (a INT NULL, b INT NULL, c INT NULL)", + f"DECLARE @s nvarchar(max) = N'ALTER TABLE t DROP COLUMN b'; {between} EXEC(@s)", + ), + "sqlserver", + ) + + +@pytest.mark.parametrize( + "statement", + [ + # A comparison, not an assignment, so the literal is never run. + "IF @mode = N'ALTER TABLE t ADD b INT NULL' PRINT 1; EXEC(@mode)", + # T-SQL reads a bare string after EXECUTE as a module's name, not as SQL. + "EXECUTE N'ALTER TABLE t ADD b INT NULL'", + ], +) +def test_a_literal_sql_server_does_not_run_as_sql_raises(statement: str) -> None: + with pytest.raises(ValueError, match="sees no EXEC run"): + declared_schema(("CREATE TABLE t (a INT NULL)", statement), "sqlserver") + + +def test_a_guarded_alter_column_after_a_rename_is_held_to_the_create() -> None: + """A rename once moved the CREATE TABLE shape into the older-store shapes, so a guarded ALTER + COLUMN after it changed every shape and was read as reaching a new store.""" + with pytest.raises(ValueError, match="built two ways"): + declared_schema( + ( + "CREATE TABLE t (a INT NULL)", + "EXEC sp_rename 't.a', 'b', 'COLUMN'", + "IF 1 = 0 ALTER TABLE t ALTER COLUMN b BIGINT NULL", + ), + "sqlserver", + ) + + def test_a_default_of_more_than_one_token_is_named_as_the_default() -> None: with pytest.raises(ValueError, match="a default the live-schema check cannot read"): declared_schema( From 49af03532c0a88572f2a14ae7e3e4c7aea79bda8 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 02:55:20 -0600 Subject: [PATCH 4/7] Server schema check: state the literal and ALTER rules as the code reads them Text only, from the unrepaired review round (round-42da1ebf67), BACKLOG #5062. The module docstring, _Built and _assigned_and_run now say: the join check sees a + or || right after the closing quote only; DDL at a second EXEC depth raises without being read; a column only a guarded ADD builds takes a guarded ALTER on every shape; and EXEC ... AT, USE, other joins and other assignment forms are listed among the misreads that do not raise. Proposed PR title: Server schema check reads more DDL forms or raises (BACKLOG #5062, #8302 items 3, 5, 6) Proposed banners: #5062 PARTIAL: built skip_tables from taken, the unguarded ALTER COLUMN, DDL in a literal no EXEC runs, EXEC-string cut clauses, ADD PRIMARY KEY against SET NOT NULL, multi-token DEFAULT messages. Remains: cross-type default opclass, the first parse on the event loop, scratch-schema altitude, the lower-cased refusal, item 6, item 7's postgres.py rollback finding, the dead label branch, test_store_schema_hash's cannot-fail assertion, and this branch's open review findings. #8302 PARTIAL: items 3, 5 and 6 built. --- messagefoundry/store/server_schema_verify.py | 36 ++++++++++++-------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/messagefoundry/store/server_schema_verify.py b/messagefoundry/store/server_schema_verify.py index afcbe9ab6d..e25e2184cc 100644 --- a/messagefoundry/store/server_schema_verify.py +++ b/messagefoundry/store/server_schema_verify.py @@ -42,9 +42,10 @@ not match, an ``ALTER TABLE`` with more than one clause or an action it does not know, a table rename, an ``ALTER INDEX``, a second ``CREATE TABLE`` of a table no ``DROP`` removed, a second ``CREATE INDEX`` of a name an index it read still holds, DDL in a single-quoted string literal the reader -sees no ``EXEC`` run, that a ``+`` or ``||`` joins to more text (other than a ``DROP CONSTRAINT`` -whose name a ``+ QUOTENAME(@x)`` ending the statement or the ``EXEC`` supplies), each at any -depth of ``EXEC``, a default followed by a token that opens no column clause, a ``USING`` access +sees no ``EXEC`` run, or whose closing quote a ``+`` or ``||`` follows (other than a ``DROP +CONSTRAINT`` whose name a ``+ QUOTENAME(@x)`` ending the statement or the ``EXEC`` supplies), each +at any depth of ``EXEC`` (DDL at a second depth is not read, and raises), a default followed by a +token that opens no column clause, a ``USING`` access method, a key column or expression carrying a collation, an operator class or a ``NULLS`` order, a key that opens with a ``::`` or ``CAST`` cast of a column, a key built ``USING INDEX``, a SQL Server inline ``INDEX``, a ``NOT NULL`` table constraint, a column type or clause it does not know, a SQL @@ -55,12 +56,17 @@ An ``ALTER COLUMN`` or added ``PRIMARY KEY`` that opens its entry in the batch, with nothing before it, is read as reaching every store, and one with anything before it, even a statement a ``;`` ends, as reaching only an older store, so the latter raises where its result differs from -the ``CREATE TABLE``, even if it would run on a new store too. - -Not every misread raises (BACKLOG #5062). At least: DDL in a PostgreSQL dollar-quoted body, or in -a T-SQL procedure's body, is read as run, though a function's or a procedure's body runs only when -it is called; a literal a variable holds is read as run by an ``EXEC`` of that variable whatever -the text between them does to it, other than a ``SET`` or ``SELECT`` that assigns it; and a +the ``CREATE TABLE``, even if it would run on a new store too. A column no ``CREATE TABLE`` +declares, which only a guarded ``ADD`` builds, has no create shape to hold the latter to, so it is +applied to that column's every shape. + +Not every misread raises (BACKLOG #5062). At least: DDL in a PostgreSQL dollar-quoted string, a +function's body included, or in a T-SQL procedure's body, is read as run, though a function's or a +procedure's body runs only when it is called; DDL an ``EXEC ... AT`` runs on a linked server, or +after a ``USE`` in another database, is read as this store's; a literal joined to more text by +anything other than a ``+`` or ``||`` right after its closing quote is read whole; a literal a +variable holds is read as run by an ``EXEC`` of that variable whatever the text between them does +to it, other than a ``SET @v``, ``SELECT @v`` or compound assignment written that way; and a ``DROP COLUMN`` raises where the reader finds the column's name among the words of an expression, ``INCLUDE`` or partial index on its table, other than as a key column, but that word search can miss a name, so a ``DROP COLUMN`` that should raise may instead keep an index PostgreSQL drops. @@ -889,8 +895,8 @@ class _Built: """Every shape a store may hold one column in. ``create`` is what ``CREATE TABLE`` builds on a new store. ``later`` is what a guarded ``ADD`` builds on an older store that lacked the column, and what an ``ALTER COLUMN`` or an added ``PRIMARY KEY`` leaves on an older store. A guarded - one is not taken to reach a new store, because its guard may test for the old state: its result - must equal ``create``, or the column is built two ways. An ``ALTER TABLE`` that opens its + one is not taken to reach a new store, because its guard may test for the old state: where + ``create`` is set, its result must equal it, or the column is built two ways. An ``ALTER TABLE`` that opens its entry in the batch, with nothing before it, runs on every store, so it changes ``create`` too (BACKLOG #5062).""" @@ -1248,7 +1254,7 @@ def shape(self) -> ServerSchemaShape: #: What opens a string literal the server runs as SQL: an ``EXEC`` or ``EXECUTE`` argument, an #: ``sp_executesql`` statement, PL/pgSQL's ``EXECUTE`` without one, or a value a ``DECLARE`` or #: ``SET`` gives a variable, which counts only once an ``EXEC`` outside any literal runs that -#: variable later in the text, with no ``SET`` or ``SELECT`` changing it first. +#: variable later in the text, with no assignment :func:`_assigned_and_run` sees changing it first. _EXEC_LITERAL = re.compile(r"\b(?:EXEC(?:UTE)?\s*\(\s*|sp_executesql\s+(?:@\w+\s*=\s*)?)N?$", re.I) _PLPGSQL_EXECUTE = re.compile(r"\bEXECUTE\s+$", re.I) _ASSIGNED_LITERAL = re.compile( @@ -1264,8 +1270,10 @@ def _enclosing_span(spans: list[tuple[int, int]], pos: int) -> tuple[int, int] | def _assigned_and_run(text: str, spans: list[tuple[int, int]], var: str, end: int) -> bool: - """Whether an ``EXEC`` outside any literal runs ``@var`` after ``text[end]``, with no ``SET`` - or ``SELECT`` assigning it, nor a ``+=``, outside a literal in between.""" + """Whether an ``EXEC`` outside any literal runs ``@var`` after ``text[end]``, with no ``SET + @var``, ``SELECT @var`` or compound assignment such as ``@var +=``, outside a literal, in + between. An assignment written another way, such as ``SELECT @a = 1, @var = ...``, is not + seen.""" runs = re.compile(rf"\b(?:EXEC(?:UTE)?\s*\(\s*@{var}\s*\)|sp_executesql\s+@{var}\b)", re.I) changes = re.compile(rf"\b(?:SET|SELECT)\s+@{var}\s*[-+*/|&^%]?=|@{var}\s*[-+*/|&^%]=", re.I) first = next( From a11834fcfdb43d0db31afbc3da757e9a3fa7e31e Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 16:27:18 -0600 Subject: [PATCH 5/7] Record the server schema check's two variable patterns as scanner blind spots BACKLOG #5062. The Lander's hold on PR 3182 names one red, tests/test_security_static.py::test_the_scanners_blind_spots_are_the_recorded_ones: _assigned_and_run in messagefoundry/store/server_schema_verify.py compiles two patterns that splice the captured variable name, so the ReDoS scanner cannot resolve them. Pin both expressions in _UNSCANNABLE_RE_PATTERNS with why each is unresolvable and why its shape is linear. --- tests/test_security_static.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tests/test_security_static.py b/tests/test_security_static.py index 745e10e857..b613f94802 100644 --- a/tests/test_security_static.py +++ b/tests/test_security_static.py @@ -815,6 +815,20 @@ def _py_files(*roots: Path) -> list[Path]: # it, a tchar, so each character is read once; the optional tail is one ``.*`` with nothing # after it. ``is_authorization_header_name`` uses ``fullmatch``, so there is one start position. "messagefoundry/transports/http_auth.py": ("f'[^{_TCHARS}]*authorization(?:[^{_TCHARS}].*)?'",), + # BACKLOG #5062 -- the server schema check's EXEC-of-a-variable reading, in + # ``_assigned_and_run``. Unresolvable BY CONSTRUCTION: both patterns name the variable that + # ``_ASSIGNED_LITERAL`` captured from the DDL text being read, so there is no literal to write. + # The capture is ``(?P\w+)``, and a ``\w`` character is never a regex metacharacter, so the + # splice adds only literal word characters, unescaped. The shapes are linear by inspection: each + # is an alternation of literal keywords joined by single ``\s*`` or ``\s+`` runs, quantified + # nowhere and inside no quantified group. No ``\s`` run is followed by a token that can match + # whitespace (``(``, ``@``, ``)``, the optional operator class, ``=``), so there is one way to + # split any prefix. The callers use the unanchored ``finditer``, and each start is a ``\b`` or + # an ``@`` before a literal. + "messagefoundry/store/server_schema_verify.py": ( + "f'\\\\b(?:EXEC(?:UTE)?\\\\s*\\\\(\\\\s*@{var}\\\\s*\\\\)|sp_executesql\\\\s+@{var}\\\\b)'", + "f'\\\\b(?:SET|SELECT)\\\\s+@{var}\\\\s*[-+*/|&^%]?=|@{var}\\\\s*[-+*/|&^%]='", + ), # a wrapper's parameter. NOTE: register_ui_action's own re.compile(pattern) stays here BY # CONSTRUCTION — its argument is the function's parameter — but every one of its 25 call sites is # now resolved through _PATTERN_WRAPPERS, so no console route pattern is unscanned. consistency.py From ac39d07f1bf0999355230c7c60dd17f749c9aa12 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 16:40:44 -0600 Subject: [PATCH 6/7] State the server schema blind-spot pin's premises as the code holds them BACKLOG #5062. Review round-1fea7c0c text findings on the new _UNSCANNABLE_RE_PATTERNS entry: the splice is a choice, not forced by construction; the pin does not bind the \w capture it relies on; name the input (the engine's own checked-in DDL); describe the optional groups and the operator class accurately. --- tests/test_security_static.py | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/tests/test_security_static.py b/tests/test_security_static.py index b613f94802..815558562e 100644 --- a/tests/test_security_static.py +++ b/tests/test_security_static.py @@ -816,15 +816,21 @@ def _py_files(*roots: Path) -> list[Path]: # after it. ``is_authorization_header_name`` uses ``fullmatch``, so there is one start position. "messagefoundry/transports/http_auth.py": ("f'[^{_TCHARS}]*authorization(?:[^{_TCHARS}].*)?'",), # BACKLOG #5062 -- the server schema check's EXEC-of-a-variable reading, in - # ``_assigned_and_run``. Unresolvable BY CONSTRUCTION: both patterns name the variable that - # ``_ASSIGNED_LITERAL`` captured from the DDL text being read, so there is no literal to write. - # The capture is ``(?P\w+)``, and a ``\w`` character is never a regex metacharacter, so the - # splice adds only literal word characters, unescaped. The shapes are linear by inspection: each - # is an alternation of literal keywords joined by single ``\s*`` or ``\s+`` runs, quantified - # nowhere and inside no quantified group. No ``\s`` run is followed by a token that can match - # whitespace (``(``, ``@``, ``)``, the optional operator class, ``=``), so there is one way to - # split any prefix. The callers use the unanchored ``finditer``, and each start is a ``\b`` or - # an ``@`` before a literal. + # ``_assigned_and_run``. Unresolvable because the code splices the variable name that + # ``_ASSIGNED_LITERAL`` captured from the DDL text into an f-string. That is a choice, not a + # necessity: a static pattern capturing ``@(\w+)`` and comparing the name after the match would + # resolve. The name goes in UNESCAPED. It is safe only while the capture admits nothing but + # ``\w`` characters, none of which is a regex metacharacter, and this pin does not bind that + # capture: a widened capture, or a new caller passing another name, keeps this test green. The + # source of record is ``server_schema_verify.py``. + # + # The text read is the engine's own checked-in DDL: ``declared_schema`` is called from + # ``postgres.py`` and ``sqlserver.py`` over their ``_SCHEMA`` (and Postgres's migration index + # DDL), and from nowhere else at this pin's writing. The shapes have no nested quantifier and no + # quantified group. Each pattern is an alternation of literals, ``@`` and the name, joined by + # single ``\s*`` or ``\s+`` runs, plus the optional ``(?:UTE)?`` and an operator class + # ``[-+*/|&^%]``, optional in one branch and required in the other. No ``\s`` run is followed by + # a token that can match whitespace, so there is one way to split any prefix. "messagefoundry/store/server_schema_verify.py": ( "f'\\\\b(?:EXEC(?:UTE)?\\\\s*\\\\(\\\\s*@{var}\\\\s*\\\\)|sp_executesql\\\\s+@{var}\\\\b)'", "f'\\\\b(?:SET|SELECT)\\\\s+@{var}\\\\s*[-+*/|&^%]?=|@{var}\\\\s*[-+*/|&^%]='", From dcaaa632f05e4b38633f700b2a81f68fd7ac6d1c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 03:38:33 -0600 Subject: [PATCH 7/7] ReDoS scan pin for server_schema_verify: describe each pattern separately BACKLOG #5062. The comment said each pattern held the optional (?:UTE)? and the operator class. The runs pattern holds only the first; the changes pattern holds only the class. Text only. --- tests/test_security_static.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/test_security_static.py b/tests/test_security_static.py index c64fae46b1..c1854167cc 100644 --- a/tests/test_security_static.py +++ b/tests/test_security_static.py @@ -826,12 +826,12 @@ def _py_files(*roots: Path) -> list[Path]: # # The text read is the engine's own checked-in DDL: ``declared_schema`` is called from # ``postgres.py`` and ``sqlserver.py`` over their ``_SCHEMA`` (and Postgres's migration index - # DDL), and from nowhere else at this pin's writing. The shapes have no nested quantifier; the one - # quantified group, ``(?:UTE)?``, holds only literals. Each pattern is an alternation of - # literals, ``@`` and the name, joined by single ``\s*`` or ``\s+`` runs, plus that optional - # ``(?:UTE)?`` and an operator class ``[-+*/|&^%]``, optional in one branch and required in the - # other. No ``\s`` run is followed by a token that can match whitespace, so there is one way to - # split any prefix. + # DDL), and from nowhere else at this pin's writing. The shapes have no nested quantifier. Each + # pattern is an alternation of literals, ``@`` and the name, joined by single ``\s*`` or + # ``\s+`` runs. The runs pattern (the first) also holds the optional ``(?:UTE)?``, a group of + # literals only. The changes pattern (the second) also holds the operator class + # ``[-+*/|&^%]``, optional in one branch and required in the other. No ``\s`` run is followed + # by a token that can match whitespace, so there is one way to split any prefix. "messagefoundry/store/server_schema_verify.py": ( "f'\\\\b(?:EXEC(?:UTE)?\\\\s*\\\\(\\\\s*@{var}\\\\s*\\\\)|sp_executesql\\\\s+@{var}\\\\b)'", "f'\\\\b(?:SET|SELECT)\\\\s+@{var}\\\\s*[-+*/|&^%]?=|@{var}\\\\s*[-+*/|&^%]='",