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
@@ -4,17 +4,26 @@ A `DatabaseKnowledgeFetcher` runs before the engine. It links the Program once
4
4
  without a connection to find the external Named Relations it reaches, asks
5
5
  its database-specific hooks for their catalog metadata and view definitions,
6
6
  and relinks the Program with that metadata turned into ordinary declarations:
7
- a fetched table becomes a column-only `CREATE TABLE`, a fetched view the
8
- `CREATE VIEW` the database stored. Each relink reveals the Relations the new
7
+ a fetched table becomes a `CREATE TABLE` of its columns and its CHECK
8
+ constraints, a fetched view the `CREATE VIEW` the
9
+ database stored. Each relink reveals the Relations the new
9
10
  view bodies read, so view expansion recurses until nothing new is reached; a
10
11
  cycle among views is left to the linker, which reports it.
11
12
 
12
- Catalog constraints never pass through those declarations. `bind` turns them
13
+ A CHECK is declared as written, so the parser reads it as one in the SQL:
14
+ the same Enumerated Domains and the
15
+ same `ignored-check-constraint` warning for one it does not read. Other
16
+ catalog constraints never pass through those declarations. `bind` turns them
13
17
  into Properties over the final IR's own Output Columns, so the engine sees
14
- Properties only, never a name, a catalog row, or a connection: Knowledge for
15
- what the dialect enforces, Property Declarations for unenforced keys the
16
- caller trusts (`trust_unenforced_keys`), as `ir/convert.py` decides for keys
17
- written in SQL.
18
+ Properties only, never a name, a catalog row, or a connection: Knowledge,
19
+ enforced by the database or not, as for keys written in SQL (ADR 0012). A catalog foreign key onto a table the SQL declares binds to
20
+ that declaration, the table the query reads by that name (ADR 0005): the
21
+ hydration asks the catalog which of the SQL's tables are its target, and
22
+ `bind` warns `unbound-foreign-key` when the declaration lacks a referenced
23
+ column or the SQL declares the target twice. The parser is still told each fetched table's primary key
24
+ (`IrParser.catalog_primary_keys`): a column-less `REFERENCES` in the SQL pairs
25
+ with it, and a GROUP BY that includes it determines the table's other columns,
26
+ as for a key declared in SQL.
18
27
  """
19
28
 
20
29
  from __future__ import annotations
@@ -24,6 +33,7 @@ from collections.abc import Mapping
24
33
  from dataclasses import dataclass, field, replace
25
34
  from enum import Enum
26
35
 
36
+ import sqlglot
27
37
  from sqlglot import Expr, exp
28
38
  from sqlglot.errors import SqlglotError
29
39
  from sqlglot.optimizer.scope import traverse_scope
@@ -34,7 +44,7 @@ from sqlassert.diagnostics import Diagnostic, quoted_all
34
44
  from sqlassert.dialects import semantics
35
45
  from sqlassert.ir.convert import IrConversionResult, IrParser
36
46
  from sqlassert.properties import NonNullColumn, Property, ReferentialCoverage, UniqueSet
37
- from sqlassert.provenance import Origin
47
+ from sqlassert.provenance import ORIGIN_META, Origin
38
48
  from sqlassert.sql_parse import ParsedProgram, SqlParser
39
49
 
40
50
  CATALOG = "catalog"
@@ -72,8 +82,10 @@ class DatabaseForeignKey:
72
82
  class DatabaseRelationMetadata:
73
83
  """One catalog Relation, identified canonically, with its complete enforced facts.
74
84
 
75
- Columns, keys, unique sets, and foreign keys describe base tables only; a
76
- view's are derived from its definition instead.
85
+ Columns, keys, unique sets, foreign keys and checks describe base tables
86
+ only; a view's are derived from its definition instead. `checks` are the
87
+ conditions of the CHECK constraints the database enforces, each as SQL
88
+ text in the fetcher's `type_dialect`.
77
89
  """
78
90
 
79
91
  catalog: str
@@ -84,6 +96,7 @@ class DatabaseRelationMetadata:
84
96
  primary_key: tuple[str, ...] = ()
85
97
  unique_sets: tuple[tuple[str, ...], ...] = ()
86
98
  foreign_keys: tuple[DatabaseForeignKey, ...] = ()
99
+ checks: tuple[str, ...] = ()
87
100
 
88
101
  @property
89
102
  def identity(self) -> str:
@@ -103,23 +116,24 @@ class DatabaseMetadataError(Exception):
103
116
 
104
117
  @dataclass(frozen=True)
105
118
  class DatabaseHydration:
106
- """The final linked Program and the catalog tables declared into it, by declared name."""
119
+ """The final linked Program and the catalog tables declared into it, by
120
+ declared name. `declared_targets` names, for each canonical identity
121
+ (lower-cased) a catalog foreign key references and no catalog table here
122
+ has, the tables the SQL declares that the catalog resolves to it."""
107
123
 
108
124
  conversion: IrConversionResult
109
125
  tables: Mapping[str, DatabaseRelationMetadata] = field(default_factory=dict)
126
+ declared_targets: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
110
127
  diagnostics: tuple[Diagnostic, ...] = ()
111
128
  dialect: str = "duckdb"
112
- trust_unenforced_keys: bool = True
113
129
 
114
130
 
115
131
  @dataclass(frozen=True)
116
132
  class CatalogFacts:
117
- """What `bind` makes of the catalog: Knowledge the database enforces,
118
- Property Declarations it does not but the caller trusts, and a warning
119
- for each key left out."""
133
+ """What `bind` makes of the catalog: Knowledge, and a warning for each
134
+ foreign key left unbound."""
120
135
 
121
136
  knowledge: tuple[Property, ...] = ()
122
- declarations: tuple[Property, ...] = ()
123
137
  warnings: tuple[Diagnostic, ...] = ()
124
138
 
125
139
 
@@ -129,23 +143,25 @@ class DatabaseKnowledgeFetcher(ABC):
129
143
  # The SQL dialect the database writes column types in.
130
144
  type_dialect: str | None = None
131
145
 
132
- def hydrate(self, ast: ParsedProgram, *, dialect: str, trust_unenforced_keys: bool = True) -> DatabaseHydration:
133
- return _Hydration(self, ast, dialect, trust_unenforced_keys).run()
146
+ def hydrate(
147
+ self, ast: ParsedProgram, *, dialect: str, required_relations: tuple[tuple[str, tuple[str, ...]], ...] = (),
148
+ ) -> DatabaseHydration:
149
+ return _Hydration(self, ast, dialect, required_relations).run()
134
150
 
135
151
  def convert(
136
- self, ast: ParsedProgram, *, dialect: str, trust_unenforced_keys: bool = True,
152
+ self, ast: ParsedProgram, *, dialect: str, required_relations: tuple[tuple[str, tuple[str, ...]], ...] = (),
137
153
  ) -> tuple[IrConversionResult, DatabaseHydration]:
138
154
  """`hydrate` and `bind` together: the conversion with the catalog's
139
155
  declarations, Knowledge and diagnostics merged in, and the hydration.
140
156
  Its warnings are the catalog facts' and the SQL's own
141
157
  (`diagnostics.SQL_WARNINGS`): a connection warning asks for what the
142
- catalog has just answered."""
143
- hydration = self.hydrate(ast, dialect=dialect, trust_unenforced_keys=trust_unenforced_keys)
158
+ catalog has just answered. `required_relations` are reached as
159
+ `IrParser`'s are."""
160
+ hydration = self.hydrate(ast, dialect=dialect, required_relations=required_relations)
144
161
  conversion = hydration.conversion
145
162
  facts = self.bind(conversion.program, hydration)
146
163
  merged = replace(
147
164
  conversion,
148
- program=replace(conversion.program, declarations=conversion.program.declarations + facts.declarations),
149
165
  knowledge=conversion.knowledge + facts.knowledge,
150
166
  diagnostics=hydration.diagnostics + conversion.diagnostics,
151
167
  warnings=(*facts.warnings, *(warning for warning in conversion.warnings if warning.code in diag.SQL_WARNINGS)),
@@ -155,30 +171,17 @@ class DatabaseKnowledgeFetcher(ABC):
155
171
  def bind(self, program: ir.Program, hydration: DatabaseHydration) -> CatalogFacts:
156
172
  """Catalog facts as Properties over ``program``'s Output Columns.
157
173
 
158
- NOT NULL columns are Knowledge. Keys and foreign keys are Knowledge
159
- where the dialect enforces them; elsewhere, as for SQL declarations,
160
- they are Property Declarations under `trust_unenforced_keys`, and
161
- otherwise left out with a warning (`docs/dialects.md`). A foreign key
162
- binds only when the Program reaches its referenced Relation.
174
+ NOT NULL columns, keys and foreign keys are Knowledge, whether or
175
+ not the database enforces them (ADR 0012). A foreign key
176
+ binds only when the Program reaches its referenced Relation: a
177
+ catalog table, or a table the SQL declares (`declared_targets`) and
178
+ declares once, with every referenced column; otherwise it warns.
163
179
  """
164
180
  meaning = semantics(hydration.dialect)
165
181
  knowledge: list[Property] = []
166
- declarations: list[Property] = []
167
182
  warnings: list[Diagnostic] = []
168
183
 
169
- def place(facts: list[Property], enforced: bool, kind: str, columns: tuple[str, ...], metadata: DatabaseRelationMetadata) -> None:
170
- if enforced:
171
- knowledge.extend(facts)
172
- elif hydration.trust_unenforced_keys:
173
- declarations.extend(facts)
174
- else:
175
- warnings.append(Diagnostic(
176
- diag.UNENFORCED_CONSTRAINT,
177
- f"the {kind} ({quoted_all(columns)}) of {metadata.identity} is not Knowledge, since {hydration.dialect} "
178
- "does not enforce it: if the data satisfies it, analyze with trust_unenforced_keys=True",
179
- _origin(metadata),
180
- ))
181
-
184
+ declared = {relation.name.lower(): relation for relation in program.named_relations if relation.role is ir.RelationRole.TABLE}
182
185
  tables = [
183
186
  (relation, metadata) for relation in program.named_relations
184
187
  if relation.role is ir.RelationRole.TABLE and (metadata := hydration.tables.get(relation.name.lower())) is not None
@@ -186,27 +189,46 @@ class DatabaseKnowledgeFetcher(ABC):
186
189
  by_identity: dict[str, list[tuple[ir.NamedRelation, DatabaseRelationMetadata]]] = {}
187
190
  for relation, metadata in tables:
188
191
  by_identity.setdefault(metadata.identity.lower(), []).append((relation, metadata))
189
- keys_enforced = meaning.unique_keys == "enforced"
190
192
  for relation, metadata in tables:
191
193
  columns = {column.name.lower(): column for column in relation.output_columns}
192
194
  non_null = sorted({column.name.lower() for column in metadata.columns if not column.nullable})
193
195
  knowledge.extend(NonNullColumn(column=columns[name]) for name in non_null if name in columns)
194
196
  for position, unique_set in enumerate(_unique_sets(metadata)):
195
- facts: list[Property] = [UniqueSet(columns=frozenset(columns[name.lower()] for name in unique_set))]
196
- primary = position == 0 and bool(metadata.primary_key)
197
- if primary and (meaning.primary_key_not_null or not keys_enforced):
198
- facts.extend(NonNullColumn(column=columns[name.lower()]) for name in unique_set if name.lower() not in non_null)
199
- place(facts, keys_enforced, "primary key" if primary else "unique key", unique_set, metadata)
197
+ knowledge.append(UniqueSet(columns=frozenset(columns[name.lower()] for name in unique_set)))
198
+ if position == 0 and metadata.primary_key and meaning.primary_key_not_null:
199
+ knowledge.extend(NonNullColumn(column=columns[name.lower()]) for name in unique_set if name.lower() not in non_null)
200
200
  for foreign_key in metadata.foreign_keys:
201
- for target, target_metadata in by_identity.get(foreign_key.referenced.lower(), ()):
202
- if _incomplete_reference(foreign_key, target_metadata):
203
- continue # Never seen from a consistent catalog; no fact is safer than a wrong one.
201
+ identity = foreign_key.referenced.lower()
202
+ targets = [target for target, target_metadata in by_identity.get(identity, ())
203
+ # Never seen from a consistent catalog; no fact is safer than a wrong one.
204
+ if not _incomplete_reference(foreign_key, target_metadata)]
205
+ names = hydration.declared_targets.get(identity, ())
206
+ unbound = f"the foreign key ({quoted_all(foreign_key.columns)}) of {metadata.identity} references {foreign_key.referenced}"
207
+ if len(names) > 1:
208
+ warnings.append(Diagnostic(
209
+ diag.UNBOUND_FOREIGN_KEY,
210
+ f"{unbound}, which the SQL declares more than once ({', '.join(names)}): it is not bound; declare it once",
211
+ _origin(metadata),
212
+ ))
213
+ elif names and (target := declared.get(names[0].lower())) is not None:
214
+ present = {column.name.lower() for column in target.output_columns}
215
+ missing = [name for name in foreign_key.referenced_columns if name.lower() not in present]
216
+ if missing:
217
+ warnings.append(Diagnostic(
218
+ diag.UNBOUND_FOREIGN_KEY,
219
+ f"{unbound} ({quoted_all(foreign_key.referenced_columns)}), but the SQL declares {names[0]} without "
220
+ f"the column{'s' if len(missing) > 1 else ''} {quoted_all(missing)}: it is not bound",
221
+ _origin(metadata),
222
+ ))
223
+ else:
224
+ targets.append(target)
225
+ for target in targets:
204
226
  referenced = {column.name.lower(): column for column in target.output_columns}
205
- place([ReferentialCoverage(
227
+ knowledge.append(ReferentialCoverage(
206
228
  columns=tuple(columns[name.lower()] for name in foreign_key.columns),
207
229
  referenced_columns=tuple(referenced[name.lower()] for name in foreign_key.referenced_columns),
208
- )], meaning.foreign_keys == "enforced", "foreign key", foreign_key.columns, metadata)
209
- return CatalogFacts(tuple(knowledge), tuple(declarations), tuple(dict.fromkeys(warnings)))
230
+ ))
231
+ return CatalogFacts(tuple(knowledge), tuple(dict.fromkeys(warnings)))
210
232
 
211
233
  @abstractmethod
212
234
  def fetch_relation_metadata(
@@ -251,12 +273,20 @@ def _incomplete_reference(foreign_key: DatabaseForeignKey, target: DatabaseRelat
251
273
  class _Hydration:
252
274
  """The state of hydrating one SQL Program: catalog answers are memoized for it alone."""
253
275
 
254
- def __init__(self, fetcher: DatabaseKnowledgeFetcher, ast: ParsedProgram, dialect: str, trust_unenforced_keys: bool):
276
+ def __init__(
277
+ self, fetcher: DatabaseKnowledgeFetcher, ast: ParsedProgram, dialect: str,
278
+ required_relations: tuple[tuple[str, tuple[str, ...]], ...],
279
+ ):
255
280
  self.fetcher = fetcher
256
281
  self.ast = ast
257
282
  self.dialect = dialect
258
- self.trust_unenforced_keys = trust_unenforced_keys
283
+ self.required_relations = required_relations
259
284
  self.sql_declared = {_qualified_name(table).lower() for table in map(_created_table, ast.create_statements) if table is not None}
285
+ self.sql_tables = {
286
+ _qualified_name(table).lower(): table for statement in ast.create_statements
287
+ if isinstance(statement, exp.Create) and (statement.kind or "").upper() == "TABLE"
288
+ and (table := _created_table(statement)) is not None
289
+ }
260
290
  self.resolved: dict[str, DatabaseRelationMetadata | None] = {}
261
291
  self.views: dict[str, exp.Create | None] = {}
262
292
  self.declarations: dict[str, exp.Create] = {}
@@ -267,18 +297,48 @@ class _Hydration:
267
297
  def run(self) -> DatabaseHydration:
268
298
  while True:
269
299
  program = ParsedProgram((*self.declarations.values(), *self.ast.create_statements), self.ast.root_select)
270
- conversion = IrParser(self.dialect, self.trust_unenforced_keys).parse(program)
300
+ conversion = IrParser(
301
+ self.dialect, self.required_relations,
302
+ catalog_primary_keys={key: table.primary_key for key, table in self.tables.items() if table.primary_key},
303
+ ).parse(program)
271
304
  pending = tuple(dict.fromkeys(
272
305
  relation.name for relation in conversion.program.named_relations if self._is_external(relation)
273
306
  ))
274
307
  if not pending:
308
+ targets = self._declared_targets()
275
309
  return DatabaseHydration(
276
- conversion, dict(self.tables), tuple(dict.fromkeys(self.diagnostics)), self.dialect, self.trust_unenforced_keys,
310
+ conversion, dict(self.tables), targets, tuple(dict.fromkeys(self.diagnostics)), self.dialect,
277
311
  )
278
312
  self.resolved.update(self._resolve(tuple(name for name in pending if name.lower() not in self.resolved), None))
279
313
  for name in pending:
280
314
  self._declare(name, self.resolved[name.lower()])
281
315
 
316
+ def _declared_targets(self) -> dict[str, tuple[str, ...]]:
317
+ """Each identity a catalog foreign key references that no fetched
318
+ table has, with the tables the SQL declares that the catalog resolves
319
+ to it, as it resolves any name. Only a declaration with the target's
320
+ bare name is asked about."""
321
+ fetched = {table.identity.lower() for table in self.tables.values()}
322
+ wanted = {key.referenced.lower() for table in self.tables.values() for key in table.foreign_keys} - fetched
323
+ bare = {identity.split(".", 2)[-1] for identity in wanted}
324
+ names = tuple(_qualified_name(table) for table in self.sql_tables.values() if table.name.lower() in bare)
325
+ if not names:
326
+ return {}
327
+ try:
328
+ found = self.fetcher.fetch_relation_metadata(names, None)
329
+ except DatabaseMetadataError as error:
330
+ self.diagnostics.append(Diagnostic(
331
+ diag.CATALOG_METADATA_UNAVAILABLE,
332
+ f"the catalog could not resolve {', '.join(names)}, declared in the SQL, so catalog foreign keys onto them are not bound: {error}",
333
+ ))
334
+ return {}
335
+ targets: dict[str, tuple[str, ...]] = {}
336
+ for name in names:
337
+ metadata = found.get(name)
338
+ if metadata is not None and metadata.identity.lower() in wanted:
339
+ targets[metadata.identity.lower()] = (*targets.get(metadata.identity.lower(), ()), name)
340
+ return targets
341
+
282
342
  def _is_external(self, relation: ir.NamedRelation) -> bool:
283
343
  key = relation.name.lower()
284
344
  return (
@@ -323,7 +383,12 @@ class _Hydration:
323
383
  target = _table(name)
324
384
  if metadata.kind is DatabaseRelationKind.TABLE:
325
385
  columns = [self._column_definition(column) for column in metadata.columns]
326
- return exp.Create(kind="TABLE", this=exp.Schema(this=target, expressions=columns))
386
+ checks = [self._check(condition, metadata) for condition in metadata.checks]
387
+ declaration = exp.Create(kind="TABLE", this=exp.Schema(this=target, expressions=[*columns, *checks]))
388
+ # Its types and CHECKs were parsed from catalog text, whose lines are not the SQL's.
389
+ for node in declaration.walk():
390
+ node.meta.pop("line", None)
391
+ return declaration
327
392
  view = self._view(metadata)
328
393
  if view is None:
329
394
  return None
@@ -348,6 +413,20 @@ class _Hydration:
348
413
  definition.set("kind", kind)
349
414
  return definition
350
415
 
416
+ def _check(self, condition: str, metadata: DatabaseRelationMetadata) -> exp.CheckColumnConstraint:
417
+ """A catalog CHECK as a table-level constraint of the declaration, so
418
+ the parser reads it as one written in SQL: the same Enumerated
419
+ Domains, trusted as the dialect trusts CHECKs, or the same warning,
420
+ which points at the catalog table. Text that does not parse stays
421
+ opaque, which states no domain."""
422
+ try:
423
+ parsed = sqlglot.parse_one(condition, read=self.fetcher.type_dialect).unnest()
424
+ except SqlglotError:
425
+ parsed = exp.var(condition)
426
+ check = exp.CheckColumnConstraint(this=parsed)
427
+ check.meta[ORIGIN_META] = _origin(metadata)
428
+ return check
429
+
351
430
  def _view(self, metadata: DatabaseRelationMetadata) -> exp.Create | None:
352
431
  """The view's definition with every Relation it reads named by canonical identity, memoized."""
353
432
  if metadata.identity not in self.views:
@@ -15,11 +15,12 @@ What it reports, and what it leaves out:
15
15
  one would otherwise be taken as comparing by identity (DuckDB's COLLATE,
16
16
  Postgres's nondeterministic collations): such a column is reported untyped.
17
17
  - Primary keys, unique constraints, unique indexes and foreign keys are
18
- reported as declared; the catalog carries no per-constraint trust. Whether
19
- they are Knowledge is the dialect's `DialectSemantics` decision, applied
20
- by `DatabaseKnowledgeFetcher.bind`: where the dialect does not enforce them
21
- they hold only under `trust_unenforced_keys`.
18
+ reported as declared, and trusted whether or not the database enforces
19
+ them (ADR 0012).
22
20
  - A unique index with a `WHERE` or an expression key part is never a key.
21
+ One over the same columns as another key is reported once.
22
+ - CHECK constraints are reported as the text of their condition; the hydration declares them with the table,
23
+ so they mean what the same CHECK written in SQL means.
23
24
  """
24
25
 
25
26
  from __future__ import annotations
@@ -162,6 +163,13 @@ ORDER BY k.TABLE_NAME, k.CONSTRAINT_NAME, k.ORDINAL_POSITION
162
163
  """
163
164
  return foreign_keys_from_pairs(self._rows(sql, (schema, *tables)))
164
165
 
166
+ def checks(self, catalog: str, schema: str, tables: Sequence[str]) -> list[tuple[str, str]]:
167
+ """Each CHECK constraint's condition, as SQL text in the dialect, by
168
+ table. None here: of the dialects on the standard views alone,
169
+ Snowflake, BigQuery, Redshift and Trino have no CHECK constraints; a
170
+ dialect that has them overrides this."""
171
+ return []
172
+
165
173
  def view_definition(self, relation: DatabaseRelationMetadata) -> str | None:
166
174
  """The view's stored text: its body, or a whole `CREATE VIEW`."""
167
175
  sql = f"SELECT VIEW_DEFINITION FROM {self.information_schema(relation.catalog, relation.schema)}.VIEWS WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s"
@@ -198,6 +206,7 @@ ORDER BY k.TABLE_NAME, k.CONSTRAINT_NAME, k.ORDINAL_POSITION
198
206
  columns: dict[_Key, list[DatabaseColumn]] = {}
199
207
  keys: dict[_Key, list[Key]] = {}
200
208
  foreign_keys: dict[_Key, list[DatabaseForeignKey]] = {}
209
+ checks: dict[_Key, list[str]] = {}
201
210
  for (table_catalog, schema), group in tables.items():
202
211
  listed = sorted(group)
203
212
  for table, column in self.columns(table_catalog, schema, listed):
@@ -206,6 +215,8 @@ ORDER BY k.TABLE_NAME, k.CONSTRAINT_NAME, k.ORDINAL_POSITION
206
215
  keys.setdefault((table_catalog, schema, key.table), []).append(key)
207
216
  for table, foreign_key in self.foreign_keys(table_catalog, schema, listed):
208
217
  foreign_keys.setdefault((table_catalog, schema, table), []).append(foreign_key)
218
+ for table, condition in self.checks(table_catalog, schema, listed):
219
+ checks.setdefault((table_catalog, schema, table), []).append(condition)
209
220
 
210
221
  metadata: dict[str, DatabaseRelationMetadata] = {}
211
222
  for name, relation in resolved.items():
@@ -219,11 +230,13 @@ ORDER BY k.TABLE_NAME, k.CONSTRAINT_NAME, k.ORDINAL_POSITION
219
230
  metadata[name] = DatabaseRelationMetadata(*path_key, DatabaseRelationKind.TABLE, own)
220
231
  continue
221
232
  table_keys = keys.get(path_key, [])
233
+ primary_key = next((key.columns for key in table_keys if key.primary), ())
222
234
  metadata[name] = DatabaseRelationMetadata(
223
235
  *path_key, DatabaseRelationKind.TABLE, own,
224
- primary_key=next((key.columns for key in table_keys if key.primary), ()),
225
- unique_sets=tuple(key.columns for key in table_keys if not key.primary),
236
+ primary_key=primary_key,
237
+ unique_sets=_distinct_sets(primary_key, [key.columns for key in table_keys if not key.primary]),
226
238
  foreign_keys=tuple(foreign_keys.get(path_key, ())),
239
+ checks=tuple(checks.get(path_key, ())),
227
240
  )
228
241
  return metadata
229
242
 
@@ -323,5 +336,17 @@ def placeholders(values: Sequence[Any]) -> str:
323
336
  return ", ".join(["%s"] * len(values))
324
337
 
325
338
 
339
+ def _distinct_sets(primary_key: tuple[str, ...], unique_sets: Sequence[tuple[str, ...]]) -> tuple[tuple[str, ...], ...]:
340
+ """Each unique set once, and none that repeats the primary key: a unique
341
+ index may repeat a UNIQUE constraint over the same columns."""
342
+ seen = {frozenset(name.lower() for name in primary_key)} if primary_key else set()
343
+ distinct: list[tuple[str, ...]] = []
344
+ for columns in unique_sets:
345
+ if (lowered := frozenset(name.lower() for name in columns)) not in seen:
346
+ seen.add(lowered)
347
+ distinct.append(columns)
348
+ return tuple(distinct)
349
+
350
+
326
351
  def _lower(path: tuple[str, str, str]) -> _Key:
327
352
  return (path[0].lower(), path[1].lower(), path[2].lower())
@@ -8,10 +8,9 @@ Over any DB-API connection (PyMySQL, mysqlclient, mysql-connector). Overrides:
8
8
  like a key over `a`; an index with one is skipped. A prefix index is unique
9
9
  on the prefix, so on the column too;
10
10
  - foreign keys: `KEY_COLUMN_USAGE`'s `REFERENCED_*` columns, since every
11
- primary key is named `PRIMARY`, which the standard join cannot tell apart.
12
- Only engines that enforce foreign keys (InnoDB, NDB) keep them in the
13
- catalog. `foreign_key_checks = 0` lets a session load rows that violate
14
- one, which no catalog records.
11
+ primary key is named `PRIMARY`, which the standard join cannot tell apart;
12
+ - checks: `CHECK_CONSTRAINTS`, joined to `TABLE_CONSTRAINTS` for the table,
13
+ NOT ENFORCED ones too: a declared constraint is trusted (ADR 0012).
15
14
 
16
15
  MySQL has one catalog, which `information_schema` names `def`. A stored view
17
16
  definition qualifies every table it reads; an unqualified name in the Program
@@ -20,6 +19,7 @@ is in the current database.
20
19
 
21
20
  from __future__ import annotations
22
21
 
22
+ import re
23
23
  from collections.abc import Sequence
24
24
 
25
25
  from sqlassert.discovery.fetcher import DatabaseColumn, DatabaseForeignKey
@@ -68,3 +68,20 @@ class MySQLKnowledgeFetcher(InformationSchemaKnowledgeFetcher):
68
68
  "ORDER BY TABLE_NAME, CONSTRAINT_NAME, ORDINAL_POSITION"
69
69
  )
70
70
  return foreign_keys_from_pairs(self._rows(sql, (schema, *tables)))
71
+
72
+ def checks(self, catalog: str, schema: str, tables: Sequence[str]) -> list[tuple[str, str]]:
73
+ # CHECK constraint names are unique within a schema.
74
+ sql = (
75
+ "SELECT t.TABLE_NAME, c.CHECK_CLAUSE FROM information_schema.TABLE_CONSTRAINTS t "
76
+ "JOIN information_schema.CHECK_CONSTRAINTS c "
77
+ "ON c.CONSTRAINT_SCHEMA = t.CONSTRAINT_SCHEMA AND c.CONSTRAINT_NAME = t.CONSTRAINT_NAME "
78
+ f"WHERE t.CONSTRAINT_TYPE = 'CHECK' AND t.TABLE_SCHEMA = %s AND t.TABLE_NAME IN ({placeholders(tables)}) "
79
+ "ORDER BY t.TABLE_NAME, t.CONSTRAINT_NAME"
80
+ )
81
+ return [(table, _unescaped(clause)) for table, clause in self._rows(sql, (schema, *tables))]
82
+
83
+
84
+ def _unescaped(clause: str) -> str:
85
+ """`CHECK_CLAUSE` is the condition with each backslash and quote escaped
86
+ once more (`_utf8mb4\\'x\\'` for `_utf8mb4'x'`; probed, MySQL 8.4.13)."""
87
+ return re.sub(r"\\(.)", r"\1", clause, flags=re.DOTALL)
@@ -5,15 +5,14 @@ its table or holds a privilege on it other than SELECT, and a view's text only
5
5
  to its owner, so a read-only role would see no keys. Every hook here reads
6
6
  `pg_catalog` instead, over any DB-API connection (psycopg, psycopg2).
7
7
 
8
- Only constraints that hold on every row are reported: validated, enforced
9
- (PostgreSQL 18 has NOT ENFORCED), not DEFERRABLE, and, for a foreign key,
10
- onto a table without row-level security, which may hide a referenced row
11
- from the reader. Unique indexes no constraint owns count, over their key
12
- columns (not INCLUDE ones), when valid, immediate, with no `WHERE` and no
13
- expression. A table other tables inherit from returns their rows too, which
14
- its own keys and NOT NULLs do not cover, so it is columns only, as are
15
- foreign tables, whose constraints are never checked. A NOT NULL added NOT
16
- VALID does not count. A column under a nondeterministic collation is
8
+ Every declared constraint (key, foreign key, CHECK, NOT NULL) is reported,
9
+ NOT VALID, NOT ENFORCED or DEFERRABLE alike: a declared constraint is
10
+ trusted (ADR 0012). A foreign key onto a table with row-level security is
11
+ not, since the policy may hide a referenced row from the reader. Unique
12
+ indexes no constraint owns count, over their key columns (not INCLUDE ones),
13
+ when valid, immediate, with no `WHERE` and no expression. A table other
14
+ tables inherit from returns their rows too, which its own keys, NOT NULLs
15
+ and CHECKs need not cover, so it is columns only. A column under a nondeterministic collation is
17
16
  reported untyped: sqlassert supports the default collation only, and such a
18
17
  collation does not compare by identity (a deterministic one does).
19
18
  """
@@ -30,7 +29,7 @@ from sqlassert.discovery.fetcher import (
30
29
  )
31
30
  from sqlassert.discovery.information_schema import FoundRelation, InformationSchemaKnowledgeFetcher, Key
32
31
 
33
- _SESSION = "SELECT current_database(), current_schemas(true), current_setting('server_version_num')::int"
32
+ _SESSION = "SELECT current_database(), current_schemas(true)"
34
33
 
35
34
  _RELATION = "pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"
36
35
  _TABLES = "n.nspname = %s AND c.relname = ANY(%s::text[])"
@@ -44,10 +43,7 @@ WHERE c.relkind IN ('r', 'p', 'v', 'm', 'f') AND lower(n.nspname) = %s AND lower
44
43
 
45
44
  _COLUMNS = f"""
46
45
  SELECT c.relname, a.attname,
47
- NOT a.attnotnull OR EXISTS (
48
- SELECT 1 FROM pg_catalog.pg_constraint k
49
- WHERE k.conrelid = c.oid AND k.contype = 'n' AND NOT k.convalidated AND a.attnum = ANY(k.conkey)
50
- ),
46
+ NOT a.attnotnull,
51
47
  CASE WHEN a.attcollation = 0 OR co.collisdeterministic THEN pg_catalog.format_type(a.atttypid, a.atttypmod) END
52
48
  FROM pg_catalog.pg_attribute a
53
49
  JOIN {_RELATION} ON c.oid = a.attrelid
@@ -71,7 +67,7 @@ FROM pg_catalog.pg_constraint k
71
67
  JOIN {_RELATION} ON c.oid = k.conrelid
72
68
  LEFT JOIN pg_catalog.pg_class r ON r.oid = k.confrelid
73
69
  LEFT JOIN pg_catalog.pg_namespace rn ON rn.oid = r.relnamespace
74
- WHERE k.contype IN ({{kinds}}) AND k.convalidated AND NOT k.condeferrable {{enforced}}
70
+ WHERE k.contype IN ({{kinds}})
75
71
  AND NOT (k.contype = 'f' AND r.relrowsecurity) AND {_TABLES}
76
72
  ORDER BY c.relname, k.conname
77
73
  """
@@ -85,6 +81,17 @@ WHERE i.indisunique AND i.indisvalid AND i.indimmediate AND i.indpred IS NULL AN
85
81
  ORDER BY c.relname, i.indexrelid
86
82
  """
87
83
 
84
+ # Column-level and table-level CHECKs are alike here.
85
+ # `pg_get_expr` deparses the stored condition: `col IN (...)` comes back as
86
+ # `col = ANY (ARRAY[...])`, literals cast, which the CHECK reading accepts.
87
+ _CHECKS = f"""
88
+ SELECT c.relname, pg_catalog.pg_get_expr(k.conbin, k.conrelid)
89
+ FROM pg_catalog.pg_constraint k
90
+ JOIN {_RELATION} ON c.oid = k.conrelid
91
+ WHERE k.contype = 'c' AND {_TABLES}
92
+ ORDER BY c.relname, k.conname
93
+ """
94
+
88
95
  VIEW = f"""
89
96
  SELECT pg_catalog.pg_get_viewdef(c.oid, true)
90
97
  FROM {_RELATION}
@@ -95,20 +102,18 @@ WHERE n.nspname = %s AND c.relname = %s AND c.relkind = 'v'
95
102
  class PostgresKnowledgeFetcher(InformationSchemaKnowledgeFetcher):
96
103
  type_dialect = "postgres"
97
104
  case_sensitive = True
98
- _enforced = False
99
105
 
100
106
  def session(self, scope: DatabaseRelationMetadata | None) -> tuple[str, tuple[str, ...]]:
101
107
  # A stored view definition names relations as the session's search path
102
108
  # sees them (pg_get_viewdef qualifies the rest), so `scope` changes nothing.
103
- (database, search_path, version), = self._rows(_SESSION)
104
- self._enforced = version >= 180000
109
+ (database, search_path), = self._rows(_SESSION)
105
110
  return database, tuple(search_path)
106
111
 
107
112
  def relations(self, catalog: str, schema: str, names: Sequence[str]) -> list[FoundRelation]:
108
113
  return [
109
114
  FoundRelation(
110
115
  database, found_schema, name, DatabaseRelationKind.VIEW if kind == "v" else DatabaseRelationKind.TABLE,
111
- facts_hold=not inherited and kind != "f",
116
+ facts_hold=not inherited,
112
117
  )
113
118
  for database, found_schema, name, kind, inherited in self._rows(_RELATIONS, (schema.lower(), list(names)))
114
119
  ]
@@ -134,9 +139,12 @@ class PostgresKnowledgeFetcher(InformationSchemaKnowledgeFetcher):
134
139
  in self._rows(self._constraints("'f'"), (schema, list(tables)))
135
140
  ]
136
141
 
142
+ def checks(self, catalog: str, schema: str, tables: Sequence[str]) -> list[tuple[str, str]]:
143
+ return [(table, condition) for table, condition in self._rows(_CHECKS, (schema, list(tables)))]
144
+
137
145
  def view_definition(self, relation: DatabaseRelationMetadata) -> str | None:
138
146
  rows = self._rows(VIEW, (relation.schema, relation.name))
139
147
  return rows[0][0] if rows else None
140
148
 
141
149
  def _constraints(self, kinds: str) -> str:
142
- return _CONSTRAINTS.format(kinds=kinds, enforced="AND k.conenforced" if self._enforced else "")
150
+ return _CONSTRAINTS.format(kinds=kinds)
@@ -1,8 +1,9 @@
1
1
  """Amazon Redshift: the standard discovery, over any DB-API connection (redshift_connector, psycopg2).
2
2
 
3
3
  Redshift keeps PostgreSQL 8's `information_schema` and has no indexes, so
4
- there are no unique indexes to read. Its keys are not enforced: they hold
5
- only under `trust_unenforced_keys` (`dialects.py`). Overrides:
4
+ there are no unique indexes to read, nor CHECK constraints, which it does
5
+ not support. Its keys are not enforced, yet trusted like every declared
6
+ constraint (ADR 0012). Overrides:
6
7
 
7
8
  - session: `current_database()` and `current_schema()`. An unqualified name
8
9
  is looked up in the current schema only, so a table found later on the
@@ -4,10 +4,13 @@ Over `snowflake-connector-python` (`%s` parameters). Snowflake's
4
4
  `INFORMATION_SCHEMA` has `TABLE_CONSTRAINTS` and `REFERENTIAL_CONSTRAINTS`
5
5
  but no `KEY_COLUMN_USAGE`, so a constraint's columns come from `SHOW PRIMARY
6
6
  KEYS`, `SHOW UNIQUE KEYS` and `SHOW IMPORTED KEYS` instead. Keys are not
7
- enforced: they hold only under `trust_unenforced_keys` (`dialects.py`); the
8
- `rely` column those commands return is not read. `VIEWS.VIEW_DEFINITION` is
7
+ enforced, yet trusted like every declared constraint (ADR 0012).
8
+ `VIEWS.VIEW_DEFINITION` is
9
9
  the whole `CREATE VIEW`, and names inside it resolve in the view's own
10
10
  database and schema. Names qualified by another database are not looked up.
11
+ Snowflake has no unique indexes: a hybrid table's indexes are not unique, and
12
+ its UNIQUE constraints are read with the other keys. Snowflake has no CHECK
13
+ constraints, so none are read.
11
14
  """
12
15
 
13
16
  from __future__ import annotations
@@ -3,8 +3,8 @@
3
3
  Trino federates catalogs, each with its own `catalog.information_schema`;
4
4
  a name may be qualified by any catalog. Its `information_schema` has
5
5
  `TABLES`, `COLUMNS` and `VIEWS` but no constraint views: Trino has no key
6
- constraints, and does not surface those a connector's source enforces, so a
7
- Trino catalog reports NOT NULLs and no keys. That loses proofs, never
6
+ or CHECK constraints or indexes, and does not surface those a connector's source
7
+ enforces, so a Trino catalog reports NOT NULLs and no keys. That loses proofs, never
8
8
  soundness. Parameters are `?` (the client's qmark style).
9
9
  """
10
10
 
@@ -0,0 +1,10 @@
1
+ """The function table: each function's properties and result type, decided
2
+ for every dialect (`table.py`), and the Builtins a dialect's functions lower
3
+ to (`load.py`)."""
4
+
5
+ from sqlassert.functions.load import call, captured, fixed_typing, key, keyword, modelled, modelled_builtins, result_type, selection, unmodelled, volatile
6
+ from sqlassert.functions.table import DIALECTS, FUNCTIONS, Function
7
+
8
+ __all__ = [
9
+ "DIALECTS", "FUNCTIONS", "Function", "call", "captured", "fixed_typing", "key", "keyword", "modelled", "modelled_builtins", "result_type", "selection", "unmodelled", "volatile",
10
+ ]