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
@@ -1,18 +1,41 @@
1
1
  """Databricks (Unity Catalog): the standard discovery, over `databricks-sql-connector`.
2
2
 
3
3
  Unity Catalog's `information_schema` has every standard view this reads, so
4
- only the session query and the parameter style (`?`) differ. Primary and
4
+ only the session query and the parameter style (`?`) differ. Databricks has
5
+ no unique indexes. Primary and
5
6
  foreign keys are informational: they hold only under
6
7
  `trust_unenforced_keys` (`dialects.py`); the `RELY` a constraint may carry is
7
8
  not read. Names qualified by another catalog are not looked up.
9
+
10
+ A Delta table checks its CHECK constraints on every write, and on the rows
11
+ already there when one is added. Unity Catalog's `CHECK_CONSTRAINTS` view
12
+ is empty (reserved), so they are read from each table's properties, where
13
+ Delta keeps each as `delta.constraints.<name>`. Unprobed: written from the
14
+ Databricks documentation, not run against a workspace.
8
15
  """
9
16
 
10
17
  from __future__ import annotations
11
18
 
12
- from sqlassert.discovery.information_schema import InformationSchemaKnowledgeFetcher
19
+ from collections.abc import Sequence
20
+
21
+ from sqlassert.discovery.fetcher import DatabaseMetadataError
22
+ from sqlassert.discovery.information_schema import InformationSchemaKnowledgeFetcher, quoted
23
+
24
+ _CHECK_PROPERTY = "delta.constraints."
13
25
 
14
26
 
15
27
  class DatabricksKnowledgeFetcher(InformationSchemaKnowledgeFetcher):
16
28
  type_dialect = "databricks"
17
29
  paramstyle = "qmark"
18
30
  session_sql = "SELECT current_catalog(), current_schema()"
31
+
32
+ def checks(self, catalog: str, schema: str, tables: Sequence[str]) -> list[tuple[str, str]]:
33
+ found: list[tuple[str, str]] = []
34
+ for table in tables:
35
+ name = ".".join(quoted(part, "`") for part in (catalog, schema, table))
36
+ try:
37
+ properties = self._rows(f"SHOW TBLPROPERTIES {name}")
38
+ except DatabaseMetadataError:
39
+ continue # A table whose properties cannot be read keeps its other facts, without CHECKs.
40
+ found.extend((table, value) for key, value in properties if key.lower().startswith(_CHECK_PROPERTY))
41
+ return found
@@ -1,9 +1,10 @@
1
1
  """DuckDB: the standard discovery, with DuckDB's `duckdb_*()` catalog functions.
2
2
 
3
- Every hook reads `duckdb_tables()`, `duckdb_views()`, `duckdb_columns()` or
4
- `duckdb_constraints()`; it never scans a table. Any DuckDB connection works
5
- (the `duckdb` module's, or one from any other client exposing `execute`), and
6
- sqlassert does not import a DuckDB driver.
3
+ Every hook reads `duckdb_tables()`, `duckdb_views()`, `duckdb_columns()`,
4
+ `duckdb_constraints()` (keys, foreign keys, CHECKs) or `duckdb_indexes()`;
5
+ it never scans a table. Any
6
+ DuckDB connection works (the `duckdb` module's, or one from any other client
7
+ exposing `execute`), and sqlassert does not import a DuckDB driver.
7
8
 
8
9
  Queries run on the connection itself, not on a cursor: a DuckDB cursor is a
9
10
  new session, without the connection's temporary tables, `USE` or
@@ -26,7 +27,7 @@ from sqlassert.discovery.fetcher import (
26
27
  DatabaseRelationKind,
27
28
  DatabaseRelationMetadata,
28
29
  )
29
- from sqlassert.discovery.information_schema import FoundRelation, InformationSchemaKnowledgeFetcher, Key
30
+ from sqlassert.discovery.information_schema import FoundRelation, InformationSchemaKnowledgeFetcher, Key, key_over_columns
30
31
 
31
32
  _SESSION = "SELECT current_database(), current_schema(), current_setting('search_path')"
32
33
 
@@ -58,6 +59,21 @@ WHERE constraint_type IN ({{kinds}}) AND {_TABLES}
58
59
  ORDER BY table_name, constraint_index
59
60
  """
60
61
 
62
+ # DuckDB checks every CHECK on each write and cannot add one by ALTER TABLE
63
+ # (probed, 2.0.1), so each was declared with its table and holds on every
64
+ # row. `expression` is the condition as written, parenthesized.
65
+ _CHECKS = f"""
66
+ SELECT table_name, expression FROM duckdb_constraints()
67
+ WHERE constraint_type = 'CHECK' AND {_TABLES}
68
+ ORDER BY table_name, constraint_index
69
+ """
70
+
71
+ # Indexes created by CREATE INDEX only: the ones backing a PRIMARY KEY or
72
+ # UNIQUE constraint are not listed, so a key is never read twice. DuckDB has
73
+ # no partial indexes, and an index is checked from its creation, so every
74
+ # unique one enforces uniqueness; one with an expression key part is skipped.
75
+ _UNIQUE_INDEXES = f"SELECT table_name, sql FROM duckdb_indexes() WHERE is_unique AND {_TABLES} ORDER BY table_name, index_name"
76
+
61
77
  _VIEW = "SELECT sql FROM duckdb_views() WHERE database_name = %s AND schema_name = %s AND view_name = %s"
62
78
 
63
79
 
@@ -117,10 +133,15 @@ class DuckDBKnowledgeFetcher(InformationSchemaKnowledgeFetcher):
117
133
  ]
118
134
 
119
135
  def keys(self, catalog: str, schema: str, tables: Sequence[str]) -> list[Key]:
120
- return [
136
+ lookup = (catalog, schema, list(tables))
137
+ keys = [
121
138
  Key(table, tuple(members), kind == "PRIMARY KEY")
122
- for table, kind, members, *_ in self._rows(_CONSTRAINTS.format(kinds="'PRIMARY KEY', 'UNIQUE'"), (catalog, schema, list(tables)))
139
+ for table, kind, members, *_ in self._rows(_CONSTRAINTS.format(kinds="'PRIMARY KEY', 'UNIQUE'"), lookup)
123
140
  ]
141
+ for table, sql in self._rows(_UNIQUE_INDEXES, lookup):
142
+ if (key := key_over_columns(table, self._index_columns(sql))) is not None:
143
+ keys.append(key)
144
+ return keys
124
145
 
125
146
  def foreign_keys(self, catalog: str, schema: str, tables: Sequence[str]) -> list[tuple[str, DatabaseForeignKey]]:
126
147
  return [
@@ -129,6 +150,9 @@ class DuckDBKnowledgeFetcher(InformationSchemaKnowledgeFetcher):
129
150
  in self._rows(_CONSTRAINTS.format(kinds="'FOREIGN KEY'"), (catalog, schema, list(tables)))
130
151
  ]
131
152
 
153
+ def checks(self, catalog: str, schema: str, tables: Sequence[str]) -> list[tuple[str, str]]:
154
+ return [(table, condition) for table, condition in self._rows(_CHECKS, (catalog, schema, list(tables)))]
155
+
132
156
  def view_definition(self, relation: DatabaseRelationMetadata) -> str | None:
133
157
  rows = self._rows(_VIEW, (relation.catalog, relation.schema, relation.name))
134
158
  return rows[0][0] if rows else None
@@ -150,6 +174,24 @@ class DuckDBKnowledgeFetcher(InformationSchemaKnowledgeFetcher):
150
174
  )
151
175
  return collated
152
176
 
177
+ @staticmethod
178
+ def _index_columns(sql: str | None) -> list[str | None]:
179
+ """The key parts of a stored `CREATE INDEX`: a column's name, or None
180
+ for an expression; none when it cannot be parsed, which loses the key,
181
+ never soundness. `duckdb_indexes().expressions` is a list rendered as
182
+ text, which does not tell a quoted name from an expression."""
183
+ try:
184
+ create = sqlglot.parse_one(sql or "", read="duckdb")
185
+ except SqlglotError:
186
+ return []
187
+ index = create.this
188
+ params = index.args.get("params") if isinstance(index, exp.Index) else None
189
+ parts = params.args.get("columns") or () if isinstance(params, exp.IndexParameters) else ()
190
+ return [
191
+ part.this.name if isinstance(part, exp.Ordered) and isinstance(part.this, exp.Column) and not part.this.table else None
192
+ for part in parts
193
+ ]
194
+
153
195
  def _rows(self, sql: str, parameters: tuple[Any, ...] = ()) -> list[tuple[Any, ...]]:
154
196
  """The rows of one catalog query, run on the connection (see the module
155
197
  docstring). Any driver error is a DatabaseMetadataError."""
@@ -4,17 +4,28 @@ 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 the CHECK
8
+ constraints the database enforces, 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, trusted as the dialect trusts CHECKs, 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
18
  Properties only, never a name, a catalog row, or a connection: Knowledge for
15
19
  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.
20
+ caller trusts (`trust_unenforced_keys`), as `ir/convert/` decides for keys
21
+ written in SQL. A catalog foreign key onto a table the SQL declares binds to
22
+ that declaration, the table the query reads by that name (ADR 0005): the
23
+ hydration asks the catalog which of the SQL's tables are its target, and
24
+ `bind` warns `unbound-foreign-key` when the declaration lacks a referenced
25
+ column or the SQL declares the target twice. The parser is still told each fetched table's primary key
26
+ (`IrParser.catalog_primary_keys`): a column-less `REFERENCES` in the SQL pairs
27
+ with it, and a GROUP BY that includes it determines the table's other columns,
28
+ as for a key declared in SQL.
18
29
  """
19
30
 
20
31
  from __future__ import annotations
@@ -24,6 +35,7 @@ from collections.abc import Mapping
24
35
  from dataclasses import dataclass, field, replace
25
36
  from enum import Enum
26
37
 
38
+ import sqlglot
27
39
  from sqlglot import Expr, exp
28
40
  from sqlglot.errors import SqlglotError
29
41
  from sqlglot.optimizer.scope import traverse_scope
@@ -34,7 +46,7 @@ from sqlassert.diagnostics import Diagnostic, quoted_all
34
46
  from sqlassert.dialects import semantics
35
47
  from sqlassert.ir.convert import IrConversionResult, IrParser
36
48
  from sqlassert.properties import NonNullColumn, Property, ReferentialCoverage, UniqueSet
37
- from sqlassert.provenance import Origin
49
+ from sqlassert.provenance import ORIGIN_META, Origin
38
50
  from sqlassert.sql_parse import ParsedProgram, SqlParser
39
51
 
40
52
  CATALOG = "catalog"
@@ -72,8 +84,10 @@ class DatabaseForeignKey:
72
84
  class DatabaseRelationMetadata:
73
85
  """One catalog Relation, identified canonically, with its complete enforced facts.
74
86
 
75
- Columns, keys, unique sets, and foreign keys describe base tables only; a
76
- view's are derived from its definition instead.
87
+ Columns, keys, unique sets, foreign keys and checks describe base tables
88
+ only; a view's are derived from its definition instead. `checks` are the
89
+ conditions of the CHECK constraints the database enforces, each as SQL
90
+ text in the fetcher's `type_dialect`.
77
91
  """
78
92
 
79
93
  catalog: str
@@ -84,6 +98,7 @@ class DatabaseRelationMetadata:
84
98
  primary_key: tuple[str, ...] = ()
85
99
  unique_sets: tuple[tuple[str, ...], ...] = ()
86
100
  foreign_keys: tuple[DatabaseForeignKey, ...] = ()
101
+ checks: tuple[str, ...] = ()
87
102
 
88
103
  @property
89
104
  def identity(self) -> str:
@@ -103,10 +118,14 @@ class DatabaseMetadataError(Exception):
103
118
 
104
119
  @dataclass(frozen=True)
105
120
  class DatabaseHydration:
106
- """The final linked Program and the catalog tables declared into it, by declared name."""
121
+ """The final linked Program and the catalog tables declared into it, by
122
+ declared name. `declared_targets` names, for each canonical identity
123
+ (lower-cased) a catalog foreign key references and no catalog table here
124
+ has, the tables the SQL declares that the catalog resolves to it."""
107
125
 
108
126
  conversion: IrConversionResult
109
127
  tables: Mapping[str, DatabaseRelationMetadata] = field(default_factory=dict)
128
+ declared_targets: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
110
129
  diagnostics: tuple[Diagnostic, ...] = ()
111
130
  dialect: str = "duckdb"
112
131
  trust_unenforced_keys: bool = True
@@ -129,18 +148,25 @@ class DatabaseKnowledgeFetcher(ABC):
129
148
  # The SQL dialect the database writes column types in.
130
149
  type_dialect: str | None = None
131
150
 
132
- def hydrate(self, ast: ParsedProgram, *, dialect: str, trust_unenforced_keys: bool = True) -> DatabaseHydration:
133
- return _Hydration(self, ast, dialect, trust_unenforced_keys).run()
151
+ def hydrate(
152
+ self, ast: ParsedProgram, *, dialect: str, trust_unenforced_keys: bool = True,
153
+ required_relations: tuple[tuple[str, tuple[str, ...]], ...] = (),
154
+ ) -> DatabaseHydration:
155
+ return _Hydration(self, ast, dialect, trust_unenforced_keys, required_relations).run()
134
156
 
135
157
  def convert(
136
158
  self, ast: ParsedProgram, *, dialect: str, trust_unenforced_keys: bool = True,
159
+ required_relations: tuple[tuple[str, tuple[str, ...]], ...] = (),
137
160
  ) -> tuple[IrConversionResult, DatabaseHydration]:
138
161
  """`hydrate` and `bind` together: the conversion with the catalog's
139
162
  declarations, Knowledge and diagnostics merged in, and the hydration.
140
163
  Its warnings are the catalog facts' and the SQL's own
141
164
  (`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)
165
+ catalog has just answered. `required_relations` are reached as
166
+ `IrParser`'s are."""
167
+ hydration = self.hydrate(
168
+ ast, dialect=dialect, trust_unenforced_keys=trust_unenforced_keys, required_relations=required_relations,
169
+ )
144
170
  conversion = hydration.conversion
145
171
  facts = self.bind(conversion.program, hydration)
146
172
  merged = replace(
@@ -159,7 +185,9 @@ class DatabaseKnowledgeFetcher(ABC):
159
185
  where the dialect enforces them; elsewhere, as for SQL declarations,
160
186
  they are Property Declarations under `trust_unenforced_keys`, and
161
187
  otherwise left out with a warning (`docs/dialects.md`). A foreign key
162
- binds only when the Program reaches its referenced Relation.
188
+ binds only when the Program reaches its referenced Relation: a
189
+ catalog table, or a table the SQL declares (`declared_targets`) and
190
+ declares once, with every referenced column; otherwise it warns.
163
191
  """
164
192
  meaning = semantics(hydration.dialect)
165
193
  knowledge: list[Property] = []
@@ -179,6 +207,7 @@ class DatabaseKnowledgeFetcher(ABC):
179
207
  _origin(metadata),
180
208
  ))
181
209
 
210
+ declared = {relation.name.lower(): relation for relation in program.named_relations if relation.role is ir.RelationRole.TABLE}
182
211
  tables = [
183
212
  (relation, metadata) for relation in program.named_relations
184
213
  if relation.role is ir.RelationRole.TABLE and (metadata := hydration.tables.get(relation.name.lower())) is not None
@@ -198,9 +227,31 @@ class DatabaseKnowledgeFetcher(ABC):
198
227
  facts.extend(NonNullColumn(column=columns[name.lower()]) for name in unique_set if name.lower() not in non_null)
199
228
  place(facts, keys_enforced, "primary key" if primary else "unique key", unique_set, metadata)
200
229
  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.
230
+ identity = foreign_key.referenced.lower()
231
+ targets = [target for target, target_metadata in by_identity.get(identity, ())
232
+ # Never seen from a consistent catalog; no fact is safer than a wrong one.
233
+ if not _incomplete_reference(foreign_key, target_metadata)]
234
+ names = hydration.declared_targets.get(identity, ())
235
+ unbound = f"the foreign key ({quoted_all(foreign_key.columns)}) of {metadata.identity} references {foreign_key.referenced}"
236
+ if len(names) > 1:
237
+ warnings.append(Diagnostic(
238
+ diag.UNBOUND_FOREIGN_KEY,
239
+ f"{unbound}, which the SQL declares more than once ({', '.join(names)}): it is not bound; declare it once",
240
+ _origin(metadata),
241
+ ))
242
+ elif names and (target := declared.get(names[0].lower())) is not None:
243
+ present = {column.name.lower() for column in target.output_columns}
244
+ missing = [name for name in foreign_key.referenced_columns if name.lower() not in present]
245
+ if missing:
246
+ warnings.append(Diagnostic(
247
+ diag.UNBOUND_FOREIGN_KEY,
248
+ f"{unbound} ({quoted_all(foreign_key.referenced_columns)}), but the SQL declares {names[0]} without "
249
+ f"the column{'s' if len(missing) > 1 else ''} {quoted_all(missing)}: it is not bound",
250
+ _origin(metadata),
251
+ ))
252
+ else:
253
+ targets.append(target)
254
+ for target in targets:
204
255
  referenced = {column.name.lower(): column for column in target.output_columns}
205
256
  place([ReferentialCoverage(
206
257
  columns=tuple(columns[name.lower()] for name in foreign_key.columns),
@@ -251,12 +302,21 @@ def _incomplete_reference(foreign_key: DatabaseForeignKey, target: DatabaseRelat
251
302
  class _Hydration:
252
303
  """The state of hydrating one SQL Program: catalog answers are memoized for it alone."""
253
304
 
254
- def __init__(self, fetcher: DatabaseKnowledgeFetcher, ast: ParsedProgram, dialect: str, trust_unenforced_keys: bool):
305
+ def __init__(
306
+ self, fetcher: DatabaseKnowledgeFetcher, ast: ParsedProgram, dialect: str, trust_unenforced_keys: bool,
307
+ required_relations: tuple[tuple[str, tuple[str, ...]], ...],
308
+ ):
255
309
  self.fetcher = fetcher
256
310
  self.ast = ast
257
311
  self.dialect = dialect
258
312
  self.trust_unenforced_keys = trust_unenforced_keys
313
+ self.required_relations = required_relations
259
314
  self.sql_declared = {_qualified_name(table).lower() for table in map(_created_table, ast.create_statements) if table is not None}
315
+ self.sql_tables = {
316
+ _qualified_name(table).lower(): table for statement in ast.create_statements
317
+ if isinstance(statement, exp.Create) and (statement.kind or "").upper() == "TABLE"
318
+ and (table := _created_table(statement)) is not None
319
+ }
260
320
  self.resolved: dict[str, DatabaseRelationMetadata | None] = {}
261
321
  self.views: dict[str, exp.Create | None] = {}
262
322
  self.declarations: dict[str, exp.Create] = {}
@@ -267,18 +327,48 @@ class _Hydration:
267
327
  def run(self) -> DatabaseHydration:
268
328
  while True:
269
329
  program = ParsedProgram((*self.declarations.values(), *self.ast.create_statements), self.ast.root_select)
270
- conversion = IrParser(self.dialect, self.trust_unenforced_keys).parse(program)
330
+ conversion = IrParser(
331
+ self.dialect, self.trust_unenforced_keys, self.required_relations,
332
+ catalog_primary_keys={key: table.primary_key for key, table in self.tables.items() if table.primary_key},
333
+ ).parse(program)
271
334
  pending = tuple(dict.fromkeys(
272
335
  relation.name for relation in conversion.program.named_relations if self._is_external(relation)
273
336
  ))
274
337
  if not pending:
338
+ targets = self._declared_targets()
275
339
  return DatabaseHydration(
276
- conversion, dict(self.tables), tuple(dict.fromkeys(self.diagnostics)), self.dialect, self.trust_unenforced_keys,
340
+ conversion, dict(self.tables), targets, tuple(dict.fromkeys(self.diagnostics)), self.dialect, self.trust_unenforced_keys,
277
341
  )
278
342
  self.resolved.update(self._resolve(tuple(name for name in pending if name.lower() not in self.resolved), None))
279
343
  for name in pending:
280
344
  self._declare(name, self.resolved[name.lower()])
281
345
 
346
+ def _declared_targets(self) -> dict[str, tuple[str, ...]]:
347
+ """Each identity a catalog foreign key references that no fetched
348
+ table has, with the tables the SQL declares that the catalog resolves
349
+ to it, as it resolves any name. Only a declaration with the target's
350
+ bare name is asked about."""
351
+ fetched = {table.identity.lower() for table in self.tables.values()}
352
+ wanted = {key.referenced.lower() for table in self.tables.values() for key in table.foreign_keys} - fetched
353
+ bare = {identity.split(".", 2)[-1] for identity in wanted}
354
+ names = tuple(_qualified_name(table) for table in self.sql_tables.values() if table.name.lower() in bare)
355
+ if not names:
356
+ return {}
357
+ try:
358
+ found = self.fetcher.fetch_relation_metadata(names, None)
359
+ except DatabaseMetadataError as error:
360
+ self.diagnostics.append(Diagnostic(
361
+ diag.CATALOG_METADATA_UNAVAILABLE,
362
+ f"the catalog could not resolve {', '.join(names)}, declared in the SQL, so catalog foreign keys onto them are not bound: {error}",
363
+ ))
364
+ return {}
365
+ targets: dict[str, tuple[str, ...]] = {}
366
+ for name in names:
367
+ metadata = found.get(name)
368
+ if metadata is not None and metadata.identity.lower() in wanted:
369
+ targets[metadata.identity.lower()] = (*targets.get(metadata.identity.lower(), ()), name)
370
+ return targets
371
+
282
372
  def _is_external(self, relation: ir.NamedRelation) -> bool:
283
373
  key = relation.name.lower()
284
374
  return (
@@ -323,7 +413,12 @@ class _Hydration:
323
413
  target = _table(name)
324
414
  if metadata.kind is DatabaseRelationKind.TABLE:
325
415
  columns = [self._column_definition(column) for column in metadata.columns]
326
- return exp.Create(kind="TABLE", this=exp.Schema(this=target, expressions=columns))
416
+ checks = [self._check(condition, metadata) for condition in metadata.checks]
417
+ declaration = exp.Create(kind="TABLE", this=exp.Schema(this=target, expressions=[*columns, *checks]))
418
+ # Its types and CHECKs were parsed from catalog text, whose lines are not the SQL's.
419
+ for node in declaration.walk():
420
+ node.meta.pop("line", None)
421
+ return declaration
327
422
  view = self._view(metadata)
328
423
  if view is None:
329
424
  return None
@@ -348,6 +443,20 @@ class _Hydration:
348
443
  definition.set("kind", kind)
349
444
  return definition
350
445
 
446
+ def _check(self, condition: str, metadata: DatabaseRelationMetadata) -> exp.CheckColumnConstraint:
447
+ """A catalog CHECK as a table-level constraint of the declaration, so
448
+ the parser reads it as one written in SQL: the same Enumerated
449
+ Domains, trusted as the dialect trusts CHECKs, or the same warning,
450
+ which points at the catalog table. Text that does not parse stays
451
+ opaque, which states no domain."""
452
+ try:
453
+ parsed = sqlglot.parse_one(condition, read=self.fetcher.type_dialect).unnest()
454
+ except SqlglotError:
455
+ parsed = exp.var(condition)
456
+ check = exp.CheckColumnConstraint(this=parsed)
457
+ check.meta[ORIGIN_META] = _origin(metadata)
458
+ return check
459
+
351
460
  def _view(self, metadata: DatabaseRelationMetadata) -> exp.Create | None:
352
461
  """The view's definition with every Relation it reads named by canonical identity, memoized."""
353
462
  if metadata.identity not in self.views:
@@ -20,6 +20,10 @@ What it reports, and what it leaves out:
20
20
  by `DatabaseKnowledgeFetcher.bind`: where the dialect does not enforce them
21
21
  they hold only under `trust_unenforced_keys`.
22
22
  - A unique index with a `WHERE` or an expression key part is never a key.
23
+ One over the same columns as another key is reported once.
24
+ - CHECK constraints are reported only where the database enforces them, as
25
+ the text of their condition; the hydration declares them with the table,
26
+ so they mean what the same CHECK written in SQL means.
23
27
  """
24
28
 
25
29
  from __future__ import annotations
@@ -162,6 +166,13 @@ ORDER BY k.TABLE_NAME, k.CONSTRAINT_NAME, k.ORDINAL_POSITION
162
166
  """
163
167
  return foreign_keys_from_pairs(self._rows(sql, (schema, *tables)))
164
168
 
169
+ def checks(self, catalog: str, schema: str, tables: Sequence[str]) -> list[tuple[str, str]]:
170
+ """Each enforced CHECK constraint's condition, as SQL text in the
171
+ dialect, by table. None here: of the dialects on the standard views
172
+ alone, Snowflake, BigQuery, Redshift and Trino have no CHECK
173
+ constraints; a dialect that enforces them overrides this."""
174
+ return []
175
+
165
176
  def view_definition(self, relation: DatabaseRelationMetadata) -> str | None:
166
177
  """The view's stored text: its body, or a whole `CREATE VIEW`."""
167
178
  sql = f"SELECT VIEW_DEFINITION FROM {self.information_schema(relation.catalog, relation.schema)}.VIEWS WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s"
@@ -198,6 +209,7 @@ ORDER BY k.TABLE_NAME, k.CONSTRAINT_NAME, k.ORDINAL_POSITION
198
209
  columns: dict[_Key, list[DatabaseColumn]] = {}
199
210
  keys: dict[_Key, list[Key]] = {}
200
211
  foreign_keys: dict[_Key, list[DatabaseForeignKey]] = {}
212
+ checks: dict[_Key, list[str]] = {}
201
213
  for (table_catalog, schema), group in tables.items():
202
214
  listed = sorted(group)
203
215
  for table, column in self.columns(table_catalog, schema, listed):
@@ -206,6 +218,8 @@ ORDER BY k.TABLE_NAME, k.CONSTRAINT_NAME, k.ORDINAL_POSITION
206
218
  keys.setdefault((table_catalog, schema, key.table), []).append(key)
207
219
  for table, foreign_key in self.foreign_keys(table_catalog, schema, listed):
208
220
  foreign_keys.setdefault((table_catalog, schema, table), []).append(foreign_key)
221
+ for table, condition in self.checks(table_catalog, schema, listed):
222
+ checks.setdefault((table_catalog, schema, table), []).append(condition)
209
223
 
210
224
  metadata: dict[str, DatabaseRelationMetadata] = {}
211
225
  for name, relation in resolved.items():
@@ -219,11 +233,13 @@ ORDER BY k.TABLE_NAME, k.CONSTRAINT_NAME, k.ORDINAL_POSITION
219
233
  metadata[name] = DatabaseRelationMetadata(*path_key, DatabaseRelationKind.TABLE, own)
220
234
  continue
221
235
  table_keys = keys.get(path_key, [])
236
+ primary_key = next((key.columns for key in table_keys if key.primary), ())
222
237
  metadata[name] = DatabaseRelationMetadata(
223
238
  *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),
239
+ primary_key=primary_key,
240
+ unique_sets=_distinct_sets(primary_key, [key.columns for key in table_keys if not key.primary]),
226
241
  foreign_keys=tuple(foreign_keys.get(path_key, ())),
242
+ checks=tuple(checks.get(path_key, ())),
227
243
  )
228
244
  return metadata
229
245
 
@@ -323,5 +339,17 @@ def placeholders(values: Sequence[Any]) -> str:
323
339
  return ", ".join(["%s"] * len(values))
324
340
 
325
341
 
342
+ def _distinct_sets(primary_key: tuple[str, ...], unique_sets: Sequence[tuple[str, ...]]) -> tuple[tuple[str, ...], ...]:
343
+ """Each unique set once, and none that repeats the primary key: a unique
344
+ index may repeat a UNIQUE constraint over the same columns."""
345
+ seen = {frozenset(name.lower() for name in primary_key)} if primary_key else set()
346
+ distinct: list[tuple[str, ...]] = []
347
+ for columns in unique_sets:
348
+ if (lowered := frozenset(name.lower() for name in columns)) not in seen:
349
+ seen.add(lowered)
350
+ distinct.append(columns)
351
+ return tuple(distinct)
352
+
353
+
326
354
  def _lower(path: tuple[str, str, str]) -> _Key:
327
355
  return (path[0].lower(), path[1].lower(), path[2].lower())
@@ -11,7 +11,10 @@ Over any DB-API connection (PyMySQL, mysqlclient, mysql-connector). Overrides:
11
11
  primary key is named `PRIMARY`, which the standard join cannot tell apart.
12
12
  Only engines that enforce foreign keys (InnoDB, NDB) keep them in the
13
13
  catalog. `foreign_key_checks = 0` lets a session load rows that violate
14
- one, which no catalog records.
14
+ one, which no catalog records;
15
+ - checks: `CHECK_CONSTRAINTS`, joined to `TABLE_CONSTRAINTS` for the table
16
+ and `ENFORCED = 'YES'` (a NOT ENFORCED CHECK is never checked; an enforced
17
+ one added by ALTER TABLE checks the rows already there).
15
18
 
16
19
  MySQL has one catalog, which `information_schema` names `def`. A stored view
17
20
  definition qualifies every table it reads; an unqualified name in the Program
@@ -20,6 +23,7 @@ is in the current database.
20
23
 
21
24
  from __future__ import annotations
22
25
 
26
+ import re
23
27
  from collections.abc import Sequence
24
28
 
25
29
  from sqlassert.discovery.fetcher import DatabaseColumn, DatabaseForeignKey
@@ -68,3 +72,20 @@ class MySQLKnowledgeFetcher(InformationSchemaKnowledgeFetcher):
68
72
  "ORDER BY TABLE_NAME, CONSTRAINT_NAME, ORDINAL_POSITION"
69
73
  )
70
74
  return foreign_keys_from_pairs(self._rows(sql, (schema, *tables)))
75
+
76
+ def checks(self, catalog: str, schema: str, tables: Sequence[str]) -> list[tuple[str, str]]:
77
+ # CHECK constraint names are unique within a schema.
78
+ sql = (
79
+ "SELECT t.TABLE_NAME, c.CHECK_CLAUSE FROM information_schema.TABLE_CONSTRAINTS t "
80
+ "JOIN information_schema.CHECK_CONSTRAINTS c "
81
+ "ON c.CONSTRAINT_SCHEMA = t.CONSTRAINT_SCHEMA AND c.CONSTRAINT_NAME = t.CONSTRAINT_NAME "
82
+ f"WHERE t.CONSTRAINT_TYPE = 'CHECK' AND t.ENFORCED = 'YES' AND t.TABLE_SCHEMA = %s AND t.TABLE_NAME IN ({placeholders(tables)}) "
83
+ "ORDER BY t.TABLE_NAME, t.CONSTRAINT_NAME"
84
+ )
85
+ return [(table, _unescaped(clause)) for table, clause in self._rows(sql, (schema, *tables))]
86
+
87
+
88
+ def _unescaped(clause: str) -> str:
89
+ """`CHECK_CLAUSE` is the condition with each backslash and quote escaped
90
+ once more (`_utf8mb4\\'x\\'` for `_utf8mb4'x'`; probed, MySQL 8.4.13)."""
91
+ return re.sub(r"\\(.)", r"\1", clause, flags=re.DOTALL)
@@ -5,13 +5,13 @@ 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
8
+ Only constraints (keys, foreign keys, CHECKs) that hold on every row are
9
+ reported: validated, enforced (PostgreSQL 18 has NOT ENFORCED), not
10
+ DEFERRABLE, and, for a foreign key, onto a table without row-level
11
+ security, which may hide a referenced row from the reader. Unique indexes no constraint owns count, over their key
12
12
  columns (not INCLUDE ones), when valid, immediate, with no `WHERE` and no
13
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
14
+ its own keys, NOT NULLs and CHECKs need not cover, so it is columns only, as are
15
15
  foreign tables, whose constraints are never checked. A NOT NULL added NOT
16
16
  VALID does not count. A column under a nondeterministic collation is
17
17
  reported untyped: sqlassert supports the default collation only, and such a
@@ -85,6 +85,19 @@ WHERE i.indisunique AND i.indisvalid AND i.indimmediate AND i.indpred IS NULL AN
85
85
  ORDER BY c.relname, i.indexrelid
86
86
  """
87
87
 
88
+ # A CHECK holds on every row once validated (one added NOT VALID has not
89
+ # checked the rows already there) and, in PostgreSQL 18, enforced; it is
90
+ # never deferrable. Column-level and table-level ones are alike here.
91
+ # `pg_get_expr` deparses the stored condition: `col IN (...)` comes back as
92
+ # `col = ANY (ARRAY[...])`, literals cast, which the CHECK reading accepts.
93
+ _CHECKS = f"""
94
+ SELECT c.relname, pg_catalog.pg_get_expr(k.conbin, k.conrelid)
95
+ FROM pg_catalog.pg_constraint k
96
+ JOIN {_RELATION} ON c.oid = k.conrelid
97
+ WHERE k.contype = 'c' AND k.convalidated {{enforced}} AND {_TABLES}
98
+ ORDER BY c.relname, k.conname
99
+ """
100
+
88
101
  VIEW = f"""
89
102
  SELECT pg_catalog.pg_get_viewdef(c.oid, true)
90
103
  FROM {_RELATION}
@@ -134,6 +147,10 @@ class PostgresKnowledgeFetcher(InformationSchemaKnowledgeFetcher):
134
147
  in self._rows(self._constraints("'f'"), (schema, list(tables)))
135
148
  ]
136
149
 
150
+ def checks(self, catalog: str, schema: str, tables: Sequence[str]) -> list[tuple[str, str]]:
151
+ sql = _CHECKS.format(enforced="AND k.conenforced" if self._enforced else "")
152
+ return [(table, condition) for table, condition in self._rows(sql, (schema, list(tables)))]
153
+
137
154
  def view_definition(self, relation: DatabaseRelationMetadata) -> str | None:
138
155
  rows = self._rows(VIEW, (relation.schema, relation.name))
139
156
  return rows[0][0] if rows else None
@@ -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: they hold only under
6
+ `trust_unenforced_keys` (`dialects.py`). 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
@@ -8,6 +8,9 @@ enforced: they hold only under `trust_unenforced_keys` (`dialects.py`); the
8
8
  `rely` column those commands return is not read. `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