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