sqlassert 0.3.3__py3-none-any.whl → 0.4.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. sqlassert/__init__.py +1 -2
  2. sqlassert/check.py +88 -13
  3. sqlassert/diagnostics.py +17 -6
  4. sqlassert/dialects.py +437 -7
  5. sqlassert/discovery/bigquery.py +3 -1
  6. sqlassert/discovery/databricks.py +25 -2
  7. sqlassert/discovery/duckdb.py +49 -7
  8. sqlassert/discovery/fetcher.py +130 -21
  9. sqlassert/discovery/information_schema.py +30 -2
  10. sqlassert/discovery/mysql.py +22 -1
  11. sqlassert/discovery/postgres.py +22 -5
  12. sqlassert/discovery/redshift.py +3 -2
  13. sqlassert/discovery/snowflake.py +3 -0
  14. sqlassert/discovery/trino.py +2 -2
  15. sqlassert/hazards.py +248 -87
  16. sqlassert/ir/__init__.py +4 -1
  17. sqlassert/ir/convert/__init__.py +13 -0
  18. sqlassert/ir/convert/aggregation.py +439 -0
  19. sqlassert/ir/convert/builtins.py +140 -0
  20. sqlassert/ir/convert/expressions.py +572 -0
  21. sqlassert/ir/convert/joins.py +264 -0
  22. sqlassert/ir/convert/markers.py +249 -0
  23. sqlassert/ir/convert/parser.py +253 -0
  24. sqlassert/ir/convert/queries.py +259 -0
  25. sqlassert/ir/convert/schema.py +606 -0
  26. sqlassert/ir/convert/scopes.py +205 -0
  27. sqlassert/ir/convert/selects.py +337 -0
  28. sqlassert/ir/convert/shared.py +429 -0
  29. sqlassert/ir/convert/sources.py +432 -0
  30. sqlassert/ir/convert/subqueries.py +364 -0
  31. sqlassert/ir/convert/value_types.py +223 -0
  32. sqlassert/ir/convert/windows.py +275 -0
  33. sqlassert/ir/model.py +125 -47
  34. sqlassert/ir/names.py +63 -0
  35. sqlassert/properties.py +12 -1
  36. sqlassert/provenance.py +5 -1
  37. sqlassert/python_engine.py +104 -44
  38. sqlassert/reporting.py +33 -32
  39. sqlassert/rewrites.py +111 -61
  40. sqlassert/rules/STYLEGUIDE.md +3 -2
  41. sqlassert/rules/causes/__init__.py +41 -0
  42. sqlassert/rules/causes/coverage.py +113 -0
  43. sqlassert/rules/causes/domain.py +123 -0
  44. sqlassert/rules/causes/joins.py +73 -0
  45. sqlassert/rules/causes/nulls.py +154 -0
  46. sqlassert/rules/causes/unique.py +523 -0
  47. sqlassert/rules/domain.py +8 -7
  48. sqlassert/rules/equality.py +6 -147
  49. sqlassert/rules/exactly_one.py +2 -1
  50. sqlassert/rules/foreign_key.py +8 -9
  51. sqlassert/rules/join_cardinality.py +282 -41
  52. sqlassert/rules/nullability.py +5 -5
  53. sqlassert/rules/uniqueness.py +171 -47
  54. sqlassert/rules/value_typing.py +337 -0
  55. sqlassert/sql_parse.py +28 -1
  56. sqlassert/suggest.py +11 -15
  57. sqlassert-0.4.1.dist-info/METADATA +235 -0
  58. sqlassert-0.4.1.dist-info/RECORD +69 -0
  59. sqlassert/ir/convert.py +0 -3509
  60. sqlassert-0.3.3.dist-info/METADATA +0 -807
  61. sqlassert-0.3.3.dist-info/RECORD +0 -46
  62. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/WHEEL +0 -0
  63. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/entry_points.txt +0 -0
  64. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/licenses/LICENSE +0 -0
  65. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,606 @@
1
+ """Schema statements: CREATE TABLE and VIEW, unique indexes and ALTER TABLE, and
2
+ the Knowledge a declared table's columns and constraints state (keys, NOT
3
+ NULL, CHECK domains, REFERENCES)."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import re
8
+ from collections.abc import Iterable, Mapping
9
+ from dataclasses import replace
10
+ from typing import TYPE_CHECKING, Literal
11
+
12
+ from sqlglot import Expr, exp
13
+
14
+ from sqlassert import diagnostics as diag
15
+ from sqlassert import ir
16
+ from sqlassert.dialects import DialectSemantics
17
+ from sqlassert.diagnostics import Diagnostic, quoted_all
18
+ from sqlassert.properties import EnumeratedDomain, NonNullColumn, Property, ReferentialCoverage, UniqueSet
19
+ from sqlassert.provenance import ORIGIN_META, Origin, SQL
20
+ from sqlassert.sql_parse import literal_value
21
+ from sqlassert.ir.convert.shared import _Symbol, _Binding, _ConstraintReference, _source_line, _missing, _qualified_name, _unwrap_query
22
+
23
+ if TYPE_CHECKING:
24
+ from sqlassert.ir.convert.parser import IrParser
25
+
26
+
27
+ class _Schema:
28
+ def _declare(self: IrParser, statement: exp.Create) -> None:
29
+ kind = (statement.kind or "").upper()
30
+ if kind not in _SUPPORTED_CREATE_KINDS:
31
+ self._diagnostics.append(
32
+ Diagnostic(
33
+ diag.UNSUPPORTED_CREATE_STATEMENT,
34
+ f"create statement kind {kind or '<unknown>'} is not supported; only TABLE, VIEW, INDEX, and SCHEMA are analyzed: {statement.sql(dialect=self.dialect)}",
35
+ )
36
+ )
37
+ return
38
+
39
+ table = _created_table(statement)
40
+ if table is None:
41
+ return
42
+ name = _qualified_name(table)
43
+ key = name.lower()
44
+ origin = Origin(SQL, statement.sql(dialect=self.dialect))
45
+ if key in self._global_symbols:
46
+ self._diagnostics.append(Diagnostic(diag.DUPLICATE_DECLARATION, f"relation {name} is declared more than once", origin))
47
+ return
48
+
49
+ role = ir.RelationRole.TABLE if kind == "TABLE" else ir.RelationRole.VIEW
50
+ body = statement.args.get("expression")
51
+ # The body keeps its parentheses: a LIMIT written after them is part of it.
52
+ query = body if _unwrap_query(body) is not None else None
53
+ aliases = tuple(column.name for column in statement.this.expressions) if role is ir.RelationRole.VIEW and isinstance(statement.this, exp.Schema) else ()
54
+ symbol = _Symbol(name=name, role=role, origin=origin, body=query, statement=statement, column_aliases=aliases)
55
+ self._global_symbols[key] = symbol
56
+ self._symbols.append(symbol)
57
+
58
+ def _declare_index(self: IrParser, statement: exp.Create) -> None:
59
+ """A unique index over plain columns is a Unique Set, like UNIQUE; one
60
+ with an expression key part may be (`_expression_key`); a partial one,
61
+ or any other index, states nothing about the data."""
62
+ index = statement.this
63
+ table = index.args.get("table") if isinstance(index, exp.Index) else None
64
+ if not isinstance(table, exp.Table):
65
+ self._unsupported_create(statement, "an index without a table")
66
+ return
67
+ symbol = self._created_before(table, statement)
68
+ if symbol is None or not statement.args.get("unique"):
69
+ return
70
+ params = index.args.get("params")
71
+ columns = params.args.get("columns") or () if isinstance(params, exp.IndexParameters) else ()
72
+ plain = [
73
+ column.this for column in columns
74
+ if isinstance(column, exp.Ordered) and isinstance(column.this, exp.Column) and not column.this.table
75
+ ]
76
+ if not columns or params.args.get("where") is not None:
77
+ # Uniqueness of only some rows is not a Unique Set.
78
+ self._unsupported_create(statement, "a partial unique index")
79
+ return
80
+ if len(plain) != len(columns):
81
+ parts = [column.this if isinstance(column, exp.Ordered) else column for column in columns]
82
+ symbol.expression_keys.append(([part.unnest() for part in parts], statement))
83
+ return
84
+ schema = exp.Schema(expressions=[exp.to_identifier(column.name) for column in plain])
85
+ symbol.constraints.append(exp.UniqueColumnConstraint(this=schema))
86
+
87
+ def _alter(self: IrParser, statement: exp.Alter) -> None:
88
+ """ALTER TABLE adding PRIMARY KEY, UNIQUE, FOREIGN KEY or CHECK
89
+ constraints, or setting columns NOT NULL. Any other action could invalidate what is
90
+ known of the table, so a statement with one states nothing."""
91
+ actions = statement.args.get("actions") or ()
92
+ added: list[Expr] = []
93
+ not_null: list[str] = []
94
+ for action in actions:
95
+ match action:
96
+ case exp.AddConstraint():
97
+ added.extend(_unwrap_constraints(action.expressions))
98
+ case exp.AlterColumn() if action.args.get("allow_null") is False and {
99
+ key for key, value in action.args.items() if value is not None and value is not False
100
+ } == {"this"}:
101
+ not_null.append(action.name)
102
+ case _:
103
+ added.append(action)
104
+ if not actions or not all(_is_added_constraint(constraint) for constraint in added):
105
+ self._diagnostics.append(Diagnostic(
106
+ diag.UNSUPPORTED_STATEMENT,
107
+ f"only ALTER TABLE adding PRIMARY KEY, UNIQUE, FOREIGN KEY or CHECK constraints, or setting NOT NULL, "
108
+ f"is analyzed: {statement.sql(dialect=self.dialect)}",
109
+ self._origin(statement),
110
+ ))
111
+ return
112
+ table = statement.this
113
+ symbol = self._created_before(table, statement) if isinstance(table, exp.Table) else None
114
+ if symbol is None:
115
+ return
116
+ symbol.constraints.extend(added)
117
+ symbol.not_null.update(not_null)
118
+ if statement.args.get("not_valid"):
119
+ self._unvalidated.update(id(constraint) for constraint in added)
120
+
121
+ def _created_before(self: IrParser, table: exp.Table, statement: Expr) -> _Symbol | None:
122
+ """The table `statement` amends, which a CREATE TABLE earlier in the
123
+ program must declare; otherwise the statement is diagnosed."""
124
+ name = _qualified_name(table)
125
+ symbol = self._global_symbols.get(name.lower())
126
+ if symbol is None or symbol.role is not ir.RelationRole.TABLE or symbol.statement is None:
127
+ self._diagnostics.append(Diagnostic(
128
+ diag.CONSTRAINT_WITHOUT_TABLE,
129
+ f"{name} is not a table created earlier in the program, so this statement's constraints are ignored: "
130
+ f"{statement.sql(dialect=self.dialect)}",
131
+ self._origin(statement),
132
+ ))
133
+ return None
134
+ return symbol
135
+
136
+ def _unsupported_create(self: IrParser, statement: exp.Create, what: str) -> None:
137
+ self._diagnostics.append(Diagnostic(
138
+ diag.UNSUPPORTED_CREATE_STATEMENT,
139
+ f"{what} is not analyzed: {statement.sql(dialect=self.dialect)}",
140
+ self._origin(statement),
141
+ ))
142
+
143
+ def _discover_constraint_references(self: IrParser) -> None:
144
+ """`REFERENCES` constraints onto relations the program reaches; one onto
145
+ a relation outside the program can never be used, so it is not linked."""
146
+ for symbol in tuple(self._symbols):
147
+ if symbol.role is not ir.RelationRole.TABLE or symbol.statement is None:
148
+ continue
149
+ for columns, table, target_columns, node in _references(symbol):
150
+ target = self._global_symbols.get(_qualified_name(table).lower())
151
+ if target is None or target.role is not ir.RelationRole.TABLE:
152
+ continue
153
+ self._require_undeclared(target, target_columns or ())
154
+ self._constraint_references.append(
155
+ _ConstraintReference(symbol, columns, target, target_columns, self._origin(node.find_ancestor(exp.ColumnDef) or node), node)
156
+ )
157
+
158
+ def _table_output_columns(self: IrParser, symbol: _Symbol) -> tuple[tuple[ir.OutputColumn, ...], bool]:
159
+ definitions = list(symbol.statement.this.find_all(exp.ColumnDef)) if symbol.statement is not None else []
160
+ names = [definition.name for definition in definitions]
161
+ seen = {name.lower() for name in names}
162
+ names.extend(column for column in sorted(symbol.required_columns, key=str.lower) if column.lower() not in seen)
163
+ complete = symbol.statement is not None and {column.lower() for column in symbol.required_columns} <= seen
164
+ columns = self._opaque_output_columns(names, symbol.origin)
165
+ by_name = {definition.name: definition for definition in definitions}
166
+ if symbol.statement is not None:
167
+ self._absent.update(column for column in columns if column.name not in by_name)
168
+ # A column declared with a COLLATE compares under a collation sqlassert
169
+ # does not model (`parse` warns): it is left untyped, so its values are unknown.
170
+ collated = {name for name, definition in by_name.items() if _collated(definition)}
171
+ by_name = {name: definition for name, definition in by_name.items() if name not in collated}
172
+ typed = tuple(
173
+ replace(column, typing=self._typing_of_declaration(by_name[column.name])) if column.name in by_name else column
174
+ for column in columns
175
+ )
176
+ for column in typed:
177
+ kind = by_name[column.name].args.get("kind") if column.name in by_name else None
178
+ if isinstance(kind, exp.DataType):
179
+ self._declared_types[column] = kind
180
+ return typed, complete
181
+
182
+ def _link_constraint_references(self: IrParser) -> None:
183
+ for reference in self._constraint_references:
184
+ table = self._resolve_symbol(reference.table)
185
+ target = self._resolve_symbol(reference.target)
186
+ target_names = reference.target_columns
187
+ if target_names is None:
188
+ if reference.target.statement is None:
189
+ continue # An undeclared table's primary key is unknown.
190
+ target_names = self._primary_key(reference.target)
191
+ if target_names is None:
192
+ self._diagnostics.append(Diagnostic(
193
+ diag.UNKNOWN_REFERENCED_COLUMN,
194
+ f"a foreign key of {table.name} references {target.name} without columns, "
195
+ f"and {target.name} declares no primary key",
196
+ reference.origin,
197
+ ))
198
+ continue
199
+ columns = self._columns_named(table, reference.columns)
200
+ if columns is None or len(reference.columns) != len(target_names):
201
+ self._diagnostics.append(Diagnostic(
202
+ diag.INVALID_FOREIGN_KEY_CONSTRAINT,
203
+ f"a foreign key of {table.name} must pair columns of its own with equally many columns of "
204
+ f"{target.name}: ({quoted_all(reference.columns)}) references ({quoted_all(target_names)})",
205
+ reference.origin,
206
+ ))
207
+ continue
208
+ referenced = self._columns_named(target, target_names)
209
+ if referenced is None:
210
+ self._diagnostics.append(Diagnostic(
211
+ diag.UNKNOWN_REFERENCED_COLUMN,
212
+ f"a foreign key of {table.name} references {target.name}({quoted_all(target_names)}), "
213
+ f"but {target.name} has no column {quoted_all(_missing(target, target_names))}",
214
+ reference.origin,
215
+ ))
216
+ continue
217
+ trust = self._key_trust(reference.node, reference.table, reference.columns)
218
+ if trust is not None:
219
+ (self._knowledge if trust == "enforced" else self._declarations).append(
220
+ ReferentialCoverage(columns=columns, referenced_columns=referenced)
221
+ )
222
+
223
+ def _primary_key(self: IrParser, symbol: _Symbol) -> tuple[str, ...] | None:
224
+ """A declared table's primary key, from its SQL or the catalog alike."""
225
+ if symbol.role is not ir.RelationRole.TABLE or symbol.statement is None:
226
+ return None
227
+ return _declared_primary_key(symbol) or self.catalog_primary_keys.get(symbol.name.lower())
228
+
229
+ def _table_knowledge(self: IrParser, relation: ir.NamedRelation, symbol: _Symbol) -> None:
230
+ """A declared table's ENUM types, NOT NULL columns, keys and CHECK
231
+ domains: Knowledge where the dialect enforces them, Property
232
+ Declarations where they are trusted (`_key_trust`)."""
233
+ statement = symbol.statement
234
+ if statement is None:
235
+ return
236
+ columns = {column.name.lower(): column for column in relation.output_columns}
237
+ non_null = {column.lower() for column in symbol.not_null}
238
+ # Each key's columns, its constraint, and whether it is a primary key.
239
+ keys: list[tuple[tuple[str, ...], Expr, bool]] = []
240
+ checks: list[exp.CheckColumnConstraint] = []
241
+ types: dict[str, exp.DataType] = {}
242
+ for definition in statement.this.find_all(exp.ColumnDef):
243
+ if isinstance(kind := definition.args.get("kind"), exp.DataType):
244
+ types[definition.name.lower()] = kind
245
+ domain = _enum_type_values(definition, self.semantics)
246
+ if domain is not None and definition.name.lower() in columns:
247
+ self._knowledge.append(EnumeratedDomain(column=columns[definition.name.lower()], values=domain))
248
+ for constraint in definition.constraints:
249
+ match constraint.args.get("kind"):
250
+ case exp.NotNullColumnConstraint() as not_null if not not_null.args.get("allow_null"):
251
+ non_null.add(definition.name.lower())
252
+ case exp.PrimaryKeyColumnConstraint() as key:
253
+ keys.append(((definition.name,), key, True))
254
+ case exp.UniqueColumnConstraint() as key:
255
+ keys.append(((definition.name,), key, False))
256
+ case exp.CheckColumnConstraint() as check:
257
+ checks.append(check)
258
+ case _:
259
+ pass # Other column constraints state nothing about keys or NULL.
260
+ for constraint in _table_constraints(symbol):
261
+ if isinstance(constraint, exp.CheckColumnConstraint):
262
+ checks.append(constraint)
263
+ continue
264
+ constrained = _table_level_unique_columns(constraint)
265
+ if constrained is not None:
266
+ keys.append((constrained, constraint, isinstance(constraint, exp.PrimaryKey)))
267
+ self._knowledge.extend(NonNullColumn(column=columns[name]) for name in sorted(non_null) if name in columns)
268
+ for column_names, constraint, primary in keys:
269
+ members = tuple(columns[name.lower()] for name in column_names if name.lower() in columns)
270
+ if len(members) != len(column_names):
271
+ continue
272
+ trust = self._key_trust(constraint, symbol, column_names)
273
+ if trust is None:
274
+ continue
275
+ facts: list[Property] = [UniqueSet(columns=frozenset(members))]
276
+ if primary and (trust == "declared" or self.semantics.primary_key_not_null):
277
+ facts.extend(NonNullColumn(column=member) for member in members if member.name.lower() not in non_null)
278
+ (self._knowledge if trust == "enforced" else self._declarations).extend(facts)
279
+ for parts, index in symbol.expression_keys:
280
+ members = self._expression_key(relation, parts, index)
281
+ if members is None:
282
+ continue
283
+ names = tuple(member.name for member in members)
284
+ trust = self._key_trust(exp.UniqueColumnConstraint(), symbol, names)
285
+ if trust is not None:
286
+ (self._knowledge if trust == "enforced" else self._declarations).append(UniqueSet(columns=frozenset(members)))
287
+ for check in checks:
288
+ self._check_knowledge(check, symbol, columns, types)
289
+
290
+ def _check_knowledge(
291
+ self: IrParser, check: exp.CheckColumnConstraint, symbol: _Symbol, columns: dict[str, ir.OutputColumn], types: dict[str, exp.DataType],
292
+ ) -> None:
293
+ """A CHECK constraint's Enumerated Domains (`_check_domains`), or a
294
+ warning that its shape states none sqlassert reads."""
295
+ domains = _check_domains(check.this, self.semantics, types)
296
+ if domains is None or not all(name in columns for name, _ in domains):
297
+ assert symbol.statement is not None
298
+ self._warnings.append(Diagnostic(
299
+ diag.IGNORED_CHECK_CONSTRAINT,
300
+ f"CHECK ({check.this.sql(dialect=self.dialect)}) of {symbol.name} is ignored: only col IN (...) and col = v, "
301
+ "with literal values, joined by AND, give a column's values",
302
+ self._constraint_origin(check, symbol),
303
+ ))
304
+ return
305
+ trust = self._key_trust(check, symbol, tuple(dict.fromkeys(name for name, _ in domains)))
306
+ if trust is None:
307
+ return
308
+ facts = [EnumeratedDomain(column=columns[name], values=values) for name, values in domains]
309
+ (self._knowledge if trust == "enforced" else self._declarations).extend(facts)
310
+
311
+ def _expression_key(
312
+ self: IrParser, relation: ir.NamedRelation, parts: list[Expr], index: exp.Create
313
+ ) -> tuple[ir.OutputColumn, ...] | None:
314
+ """The columns a unique index over `parts` makes a Unique Set, or None
315
+ (diagnosed) when it makes none.
316
+
317
+ Two rows equal and non-null on the columns the parts read would give
318
+ equal index keys, which the index forbids, when every part is a pure
319
+ function of its columns (equal inputs, equal keys: so only over columns
320
+ whose equal values are identical; under a case-insensitive collation
321
+ `'A' = 'a'` yet their bytes differ) and total in them (a NULL key part
322
+ exempts the row: `nullif(email, '')` lets every '' through). No
323
+ injectivity is needed: `lower(email)` unique makes `email` unique."""
324
+ bindings = tuple(_Binding(relation.name.lower(), column.name.lower(), column) for column in relation.output_columns)
325
+ found: dict[ir.OutputColumn, None] = {}
326
+ for part in parts:
327
+ lowered = self._lower_expression(part, bindings, schema_complete=relation.is_schema_complete)
328
+ inputs = ir.determinants(lowered)
329
+ text = part.sql(dialect=self.dialect)
330
+ if inputs is None:
331
+ problem = f"{text} is not a function of the table's columns"
332
+ elif not ir.total(lowered):
333
+ problem = f"{text} may be NULL where its columns are not, which exempts the row from the index"
334
+ elif not all(column in relation.output_columns and column.typing is not None and column.typing.identity_comparison for column in inputs):
335
+ problem = f"{text} reads a column whose equal values may differ (a float, or text under a collation)"
336
+ else:
337
+ found.update(dict.fromkeys(inputs))
338
+ continue
339
+ self._unsupported_create(index, f"a unique index whose key states no Unique Set ({problem})")
340
+ return None
341
+ return tuple(found)
342
+
343
+ def _key_trust(self: IrParser, constraint: Expr, symbol: _Symbol, columns: tuple[str, ...]) -> Literal["enforced", "declared"] | None:
344
+ """Whether a key or foreign key constraint holds: enforced by the
345
+ database (Knowledge), trusted by its author (a Property Declaration:
346
+ marked `RELY`, or any unenforced one under `trust_unenforced_keys`),
347
+ or neither, which a warning reports. An unenforced one is never
348
+ Knowledge, so never proves anything by itself (ADR 0005)."""
349
+ assert symbol.statement is not None
350
+ foreign = isinstance(constraint, exp.ForeignKey | exp.Reference)
351
+ check = isinstance(constraint, exp.CheckColumnConstraint)
352
+ reference = constraint.args.get("reference") if isinstance(constraint, exp.ForeignKey) else constraint
353
+ options = {str(option).upper() for option in (reference.args.get("options") or ())} if isinstance(reference, Expr) else set()
354
+ meaning = self.semantics
355
+ reason = None
356
+ if "NOT ENFORCED" in options:
357
+ reason = "it is declared NOT ENFORCED"
358
+ elif id(constraint) in self._unvalidated:
359
+ reason = "ALTER TABLE ... NOT VALID added it, so rows already in the table were never checked"
360
+ elif "DEFERRABLE" in options or "INITIALLY DEFERRED" in options:
361
+ reason = "it is DEFERRABLE, so a transaction may see it violated"
362
+ elif (meaning.check_constraints if check else meaning.foreign_keys if foreign else meaning.unique_keys) != "enforced":
363
+ reason = f"{self.dialect} does not enforce it"
364
+ elif isinstance(constraint, exp.Reference) and not meaning.inline_references:
365
+ reason = f"{self.dialect} before 9.0 ignores a column-level REFERENCES"
366
+ elif foreign and meaning.foreign_key_engines is not None and (engine := _engine(symbol)) not in meaning.foreign_key_engines:
367
+ reason = (
368
+ f"ENGINE={engine} does not enforce foreign keys" if engine is not None
369
+ else "its table names no ENGINE, and the server's default_storage_engine may not enforce foreign keys"
370
+ )
371
+ if reason is None:
372
+ return "enforced"
373
+ if ("RELY" in options and meaning.rely) or self.trust_unenforced_keys:
374
+ return "declared"
375
+ kind = "check constraint" if check else "foreign key" if foreign else "primary key" if isinstance(constraint, exp.PrimaryKey | exp.PrimaryKeyColumnConstraint) else "unique constraint"
376
+ fixes = ["mark it RELY"] if meaning.rely and not check else []
377
+ if foreign and meaning.foreign_key_engines is not None and _engine(symbol) is None:
378
+ fixes.append("write ENGINE=InnoDB")
379
+ fixes.append("analyze with trust_unenforced_keys=True")
380
+ self._warnings.append(Diagnostic(
381
+ diag.UNENFORCED_CONSTRAINT,
382
+ f"the {kind} ({quoted_all(columns)}) of {symbol.name} is not Knowledge, since {reason}: "
383
+ f"if the data satisfies it, {' or '.join(fixes)}",
384
+ self._constraint_origin(constraint, symbol),
385
+ ))
386
+ return None
387
+
388
+ def _constraint_origin(self: IrParser, constraint: Expr, symbol: _Symbol) -> Origin:
389
+ """Where a table's constraint is stated: the catalog for one a catalog
390
+ declares (`ORIGIN_META`), else the SQL, at its line or its table's."""
391
+ origin = constraint.meta.get(ORIGIN_META)
392
+ if isinstance(origin, Origin):
393
+ return origin
394
+ assert symbol.statement is not None
395
+ return self._origin(constraint, _source_line(constraint) or _source_line(symbol.statement))
396
+
397
+
398
+ def _table_level_unique_columns(constraint: Expr) -> tuple[str, ...] | None:
399
+ if isinstance(constraint, exp.PrimaryKey):
400
+ return tuple(identifier.name for identifier in constraint.expressions)
401
+ if isinstance(constraint, exp.UniqueColumnConstraint) and isinstance(constraint.this, exp.Schema):
402
+ return tuple(identifier.name for identifier in constraint.this.expressions)
403
+ return None
404
+
405
+
406
+ def _table_constraints(symbol: _Symbol) -> list[Expr]:
407
+ """A declared table's table-level constraints, named or not: its CREATE
408
+ TABLE's, then those added later."""
409
+ assert symbol.statement is not None
410
+ schema = symbol.statement.this
411
+ own = _unwrap_constraints(schema.expressions) if isinstance(schema, exp.Schema) else []
412
+ return own + symbol.constraints
413
+
414
+
415
+ def _unwrap_constraints(constraints: Iterable[Expr]) -> list[Expr]:
416
+ """`CONSTRAINT name ...` is the constraints it names."""
417
+ return [
418
+ inner for constraint in constraints
419
+ for inner in (constraint.expressions if isinstance(constraint, exp.Constraint) else (constraint,))
420
+ ]
421
+
422
+
423
+ def _is_added_constraint(constraint: Expr) -> bool:
424
+ return (
425
+ isinstance(constraint, exp.PrimaryKey | exp.ForeignKey | exp.CheckColumnConstraint)
426
+ or _table_level_unique_columns(constraint) is not None
427
+ )
428
+
429
+
430
+ def _references(symbol: _Symbol) -> list[tuple[tuple[str, ...], exp.Table, tuple[str, ...] | None, Expr]]:
431
+ """Every `REFERENCES` constraint of a table, column-level and table-level,
432
+ as `(columns, referenced table, referenced columns, node)`. Referenced
433
+ columns are None when omitted, meaning the referenced primary key."""
434
+ found = []
435
+ assert symbol.statement is not None
436
+ for definition in symbol.statement.this.find_all(exp.ColumnDef):
437
+ for constraint in definition.constraints:
438
+ reference = constraint.args.get("kind")
439
+ if isinstance(reference, exp.Reference):
440
+ found.append(((definition.name,), *_reference_target(reference), reference))
441
+ for foreign_key in _table_constraints(symbol):
442
+ if not isinstance(foreign_key, exp.ForeignKey):
443
+ continue
444
+ reference = foreign_key.args.get("reference")
445
+ if isinstance(reference, exp.Reference):
446
+ columns = tuple(identifier.name for identifier in foreign_key.expressions)
447
+ found.append((columns, *_reference_target(reference), foreign_key))
448
+ return found
449
+
450
+
451
+ def _reference_target(reference: exp.Reference) -> tuple[exp.Table, tuple[str, ...] | None]:
452
+ target = reference.this
453
+ if isinstance(target, exp.Schema):
454
+ return target.this, tuple(identifier.name for identifier in target.expressions)
455
+ return target, None
456
+
457
+
458
+ def _declared_primary_key(symbol: _Symbol) -> tuple[str, ...] | None:
459
+ assert symbol.statement is not None
460
+ for definition in symbol.statement.this.find_all(exp.ColumnDef):
461
+ if any(isinstance(constraint.args.get("kind"), exp.PrimaryKeyColumnConstraint) for constraint in definition.constraints):
462
+ return (definition.name,)
463
+ for constraint in _table_constraints(symbol):
464
+ if isinstance(constraint, exp.PrimaryKey):
465
+ return tuple(identifier.name for identifier in constraint.expressions)
466
+ return None
467
+
468
+
469
+ _SUPPORTED_CREATE_KINDS = {"TABLE", "VIEW"}
470
+
471
+
472
+ def _collated(definition: exp.ColumnDef) -> bool:
473
+ """Whether a column is declared with a `COLLATE`."""
474
+ return any(isinstance(constraint.args.get("kind"), exp.CollateColumnConstraint) for constraint in definition.constraints)
475
+
476
+
477
+ def _created_table(statement: exp.Create) -> exp.Table | None:
478
+ target = statement.this
479
+ if isinstance(target, exp.Schema):
480
+ target = target.this
481
+ return target if isinstance(target, exp.Table) else None
482
+
483
+
484
+ def _enum_type_values(definition: exp.ColumnDef, meaning: DialectSemantics) -> frozenset[ir.LiteralValue] | None:
485
+ """The values of a column declared `ENUM('a', ...)`: its members, with
486
+ their trailing spaces removed where the dialect does (MySQL)."""
487
+ kind = definition.args.get("kind")
488
+ if not (isinstance(kind, exp.DataType) and kind.this == exp.DataType.Type.ENUM and kind.expressions):
489
+ return None
490
+ values = [literal_value(member) for member in kind.expressions]
491
+ if any(value is None or value.type != "string" for value in values):
492
+ return None
493
+ members = {value for value in values if value is not None}
494
+ if meaning.enum_strips_trailing_spaces:
495
+ members = {replace(value, text=value.text.rstrip(" ")) for value in members}
496
+ return frozenset(members)
497
+
498
+
499
+ def _check_domains(
500
+ condition: Expr, meaning: DialectSemantics, types: Mapping[str, exp.DataType],
501
+ ) -> list[tuple[str, frozenset[ir.LiteralValue]]] | None:
502
+ """The Enumerated Domains a CHECK condition states, by lower-cased
503
+ column name, or None for a shape that states none sqlassert reads.
504
+ `types` are the table's declared column types, by lower-cased name.
505
+
506
+ A CHECK passes a row unless its condition is FALSE, so NULL passes. Each
507
+ AND-ed `col IN (v, ...)` or `col = v` over non-null literals is FALSE for
508
+ a non-null value equal to no v, which makes the whole condition FALSE: so
509
+ every non-null value of col equals one of them, exactly what ENUM states.
510
+ A NULL among the values would make the IN NULL instead, and pass any row.
511
+
512
+ The same CHECK is read in the forms engines store it in, which a catalog
513
+ returns: `col = ANY (ARRAY[v, ...])` is PostgreSQL's IN (TRUE, FALSE and NULL
514
+ alike), a literal may carry a charset (`_check_literal`) or a cast that
515
+ keeps its value, and a column a cast that keeps its value
516
+ (`_check_column`).
517
+ """
518
+ condition = condition.unnest()
519
+ parts = list(condition.flatten()) if isinstance(condition, exp.And) else [condition]
520
+ found = []
521
+ for part in parts:
522
+ match part.unnest():
523
+ case exp.EQ(this=operand, expression=exp.Any(this=array)):
524
+ values = _array_values(array) or []
525
+ case exp.EQ(this=operand, expression=value) if _check_column(operand, types) is not None:
526
+ values = [value]
527
+ case exp.EQ(this=value, expression=operand):
528
+ values = [value]
529
+ case exp.In(this=operand, expressions=list(values)):
530
+ pass
531
+ case _:
532
+ return None
533
+ column = _check_column(operand, types)
534
+ literals = [_check_literal(value) for value in values]
535
+ if column is None or not literals or any(
536
+ literal is None or (meaning.empty_string_is_null and literal.type == "string" and literal.text == "")
537
+ for literal in literals
538
+ ):
539
+ return None
540
+ found.append((column, frozenset(literal for literal in literals if literal is not None)))
541
+ return found
542
+
543
+
544
+ _TEXT_TYPES = frozenset({exp.DataType.Type.TEXT, exp.DataType.Type.VARCHAR, exp.DataType.Type.NVARCHAR, exp.DataType.Type.BPCHAR})
545
+ _INTEGER_TYPES = frozenset({exp.DataType.Type.TINYINT, exp.DataType.Type.SMALLINT, exp.DataType.Type.INT, exp.DataType.Type.BIGINT})
546
+ _SIGNED_INTEGER = re.compile(r"-?\d+")
547
+ _SIGNED_DECIMAL = re.compile(r"-?(\d+\.?\d*|\.\d+)")
548
+
549
+
550
+ def _check_column(operand: Expr, types: Mapping[str, exp.DataType]) -> str | None:
551
+ """The lower-cased name of the column a CHECK compares, or None: an
552
+ unqualified column, or a VARCHAR or TEXT one cast to TEXT, which keeps
553
+ its value (PostgreSQL stores a comparison of VARCHAR so)."""
554
+ operand = operand.unnest()
555
+ if isinstance(operand, exp.Cast) and operand.to.this == exp.DataType.Type.TEXT and not operand.to.expressions:
556
+ inner = operand.this.unnest()
557
+ declared = types.get(inner.name.lower()) if isinstance(inner, exp.Column) else None
558
+ if declared is None or declared.this not in (exp.DataType.Type.TEXT, exp.DataType.Type.VARCHAR):
559
+ return None
560
+ operand = inner
561
+ return operand.name.lower() if isinstance(operand, exp.Column) and not operand.table else None
562
+
563
+
564
+ def _check_literal(value: Expr) -> ir.LiteralValue | None:
565
+ """The literal a CHECK compares with, or None: one written plainly, a
566
+ string given a charset (MySQL stores `_utf8mb4'x'`: the same
567
+ characters), or one cast to a type that keeps its value, as PostgreSQL
568
+ stores them: a string to unsized text (`'x'::text`, `'x'::bpchar`), or a
569
+ number, or a string spelling one, to an integer type or unsized NUMERIC
570
+ (`(2)::numeric`, `'-1'::integer`)."""
571
+ value = value.unnest()
572
+ if isinstance(value, exp.Introducer):
573
+ literal = literal_value(value.expression)
574
+ return literal if literal is not None and literal.type == "string" else None
575
+ if not isinstance(value, exp.Cast):
576
+ return literal_value(value)
577
+ literal = _check_literal(value.this)
578
+ to = value.to
579
+ if literal is None or literal.type == "boolean" or to.expressions:
580
+ return None
581
+ if to.this in _TEXT_TYPES:
582
+ return literal if literal.type == "string" else None
583
+ text = literal.text
584
+ if (to.this in _INTEGER_TYPES and _SIGNED_INTEGER.fullmatch(text)) or (to.this == exp.DataType.Type.DECIMAL and _SIGNED_DECIMAL.fullmatch(text)):
585
+ number = exp.Literal.number(text.removeprefix("-"))
586
+ return literal_value(exp.Neg(this=number) if text.startswith("-") else number)
587
+ return None
588
+
589
+
590
+ def _array_values(array: Expr) -> list[Expr] | None:
591
+ """The elements of `ARRAY[v, ...]`, each under the cast of the array to
592
+ an array type (`(ARRAY['a'::varchar])::text[]`) as a cast of its own, or
593
+ None for any other operand of ANY."""
594
+ array = array.unnest()
595
+ if isinstance(array, exp.Cast):
596
+ to = array.to
597
+ values = _array_values(array.this) if to.this == exp.DataType.Type.ARRAY and len(to.expressions) == 1 else None
598
+ return None if values is None else [exp.Cast(this=value, to=to.expressions[0].copy()) for value in values]
599
+ return [value.copy() for value in array.expressions] if isinstance(array, exp.Array) else None
600
+
601
+
602
+ def _engine(symbol: _Symbol) -> str | None:
603
+ """The storage ENGINE a CREATE TABLE names (lower-cased), if any."""
604
+ assert symbol.statement is not None
605
+ engine = symbol.statement.find(exp.EngineProperty)
606
+ return engine.name.lower() if engine is not None else None