diff --git a/messagefoundry/store/server_schema_verify.py b/messagefoundry/store/server_schema_verify.py index 1d0e3e41b8..e25e2184cc 100644 --- a/messagefoundry/store/server_schema_verify.py +++ b/messagefoundry/store/server_schema_verify.py @@ -40,7 +40,12 @@ 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 an index it read still holds, DDL in a single-quoted string literal the reader +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 @@ -48,8 +53,20 @@ 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 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. 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. @@ -317,27 +334,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 +469,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 +496,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 +738,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 +894,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: 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).""" create: ColumnShape | None = None later: set[ColumnShape] = field(default_factory=set) @@ -888,8 +906,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]: @@ -986,7 +1008,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()) @@ -997,6 +1019,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)), @@ -1009,10 +1039,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): @@ -1032,10 +1060,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() :] - 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 + # 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() + 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() @@ -1049,7 +1079,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 +1113,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 +1133,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}") @@ -1153,7 +1180,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: @@ -1218,6 +1251,86 @@ 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 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( + 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) + + +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 _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 + @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( + (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, 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: + """: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 or ( + dialect != "sqlserver" and _PLPGSQL_EXECUTE.search(text, 0, start) is not None + ) + if not run and (assigned := _ASSIGNED_LITERAL.search(text, 0, start)): + 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!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 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_at(body, _string_spans(body), kind, offset, offset + length, label, dialect) + + @cache def declared_schema( statements: tuple[str, ...], dialect: Dialect | None = None @@ -1252,10 +1365,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, 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": @@ -1277,25 +1391,32 @@ def _a(noun: str) -> str: def server_schema_differences( expected: SchemaShape, live: SchemaShape, - taken: Mapping[str, str], + *, + 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 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_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): - 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 +1427,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 +1563,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 +1581,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 + 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_security_static.py b/tests/test_security_static.py index 77e8176477..c1854167cc 100644 --- a/tests/test_security_static.py +++ b/tests/test_security_static.py @@ -815,6 +815,27 @@ 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 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. 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*[-+*/|&^%]='", + ), # BACKLOG #6637 -- the ignores for pydicom's UserWarning copies of a refused value. ``message`` # iterates ``reversed(_PYDICOM_VALUE_WARNINGS)``, which is derived from the ``warning`` field of # each ``_REFUSALS`` shape that sets one, and this scanner reads neither. None has a nested diff --git a/tests/test_server_schema_verify_5062.py b/tests/test_server_schema_verify_5062.py index f3eb84228f..9d904e8cf9 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,242 @@ 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)'", + # 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="sees no EXEC run"): + 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)", + "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: + shape = declared_schema(("CREATE TABLE t (a INT NULL)", statement), "sqlserver") + 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="join adds 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_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( + ("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..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)", @@ -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, 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))", "table 'messages' was never created: the name is taken by an index", @@ -354,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))" ] @@ -1291,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: @@ -1302,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: @@ -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", ) @@ -1559,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", @@ -1589,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" @@ -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", )