sqlassert 0.3.1__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 (73) hide show
  1. sqlassert/__init__.py +1 -2
  2. sqlassert/__main__.py +2 -131
  3. sqlassert/check.py +98 -16
  4. sqlassert/diagnostics.py +31 -7
  5. sqlassert/dialects.py +504 -27
  6. sqlassert/discovery/bigquery.py +3 -1
  7. sqlassert/discovery/databricks.py +25 -2
  8. sqlassert/discovery/duckdb.py +61 -23
  9. sqlassert/discovery/fetcher.py +170 -45
  10. sqlassert/discovery/information_schema.py +34 -5
  11. sqlassert/discovery/mysql.py +22 -1
  12. sqlassert/discovery/postgres.py +28 -12
  13. sqlassert/discovery/redshift.py +3 -2
  14. sqlassert/discovery/snowflake.py +3 -0
  15. sqlassert/discovery/trino.py +2 -2
  16. sqlassert/edits.py +240 -0
  17. sqlassert/hazards.py +735 -0
  18. sqlassert/ir/__init__.py +6 -1
  19. sqlassert/ir/convert/__init__.py +13 -0
  20. sqlassert/ir/convert/aggregation.py +439 -0
  21. sqlassert/ir/convert/builtins.py +140 -0
  22. sqlassert/ir/convert/expressions.py +572 -0
  23. sqlassert/ir/convert/joins.py +264 -0
  24. sqlassert/ir/convert/markers.py +249 -0
  25. sqlassert/ir/convert/parser.py +253 -0
  26. sqlassert/ir/convert/queries.py +259 -0
  27. sqlassert/ir/convert/schema.py +606 -0
  28. sqlassert/ir/convert/scopes.py +205 -0
  29. sqlassert/ir/convert/selects.py +337 -0
  30. sqlassert/ir/convert/shared.py +429 -0
  31. sqlassert/ir/convert/sources.py +432 -0
  32. sqlassert/ir/convert/subqueries.py +364 -0
  33. sqlassert/ir/convert/value_types.py +223 -0
  34. sqlassert/ir/convert/windows.py +275 -0
  35. sqlassert/ir/model.py +247 -66
  36. sqlassert/ir/names.py +63 -0
  37. sqlassert/main.py +3 -9
  38. sqlassert/properties.py +12 -1
  39. sqlassert/provenance.py +5 -1
  40. sqlassert/python_engine.py +167 -50
  41. sqlassert/reporting.py +36 -32
  42. sqlassert/rewrites.py +1591 -0
  43. sqlassert/rules/STYLEGUIDE.md +3 -2
  44. sqlassert/rules/causes/__init__.py +41 -0
  45. sqlassert/rules/causes/coverage.py +113 -0
  46. sqlassert/rules/causes/domain.py +123 -0
  47. sqlassert/rules/causes/joins.py +73 -0
  48. sqlassert/rules/causes/nulls.py +154 -0
  49. sqlassert/rules/causes/unique.py +523 -0
  50. sqlassert/rules/domain.py +123 -26
  51. sqlassert/rules/equality.py +153 -85
  52. sqlassert/rules/exactly_one.py +42 -2
  53. sqlassert/rules/foreign_key.py +15 -13
  54. sqlassert/rules/join_cardinality.py +302 -39
  55. sqlassert/rules/nullability.py +244 -35
  56. sqlassert/rules/uniqueness.py +513 -86
  57. sqlassert/rules/value_typing.py +337 -0
  58. sqlassert/sql_parse.py +224 -90
  59. sqlassert/suggest.py +132 -57
  60. sqlassert-0.4.1.dist-info/METADATA +235 -0
  61. sqlassert-0.4.1.dist-info/RECORD +69 -0
  62. sqlassert-0.4.1.dist-info/entry_points.txt +2 -0
  63. sqlassert-0.4.1.dist-info/top_level.txt +2 -0
  64. sqlassert_cli.py +130 -0
  65. sqlassert/improvements.py +0 -528
  66. sqlassert/ir/convert.py +0 -2377
  67. sqlassert/smells.py +0 -306
  68. sqlassert-0.3.1.dist-info/METADATA +0 -725
  69. sqlassert-0.3.1.dist-info/RECORD +0 -44
  70. sqlassert-0.3.1.dist-info/entry_points.txt +0 -2
  71. sqlassert-0.3.1.dist-info/top_level.txt +0 -1
  72. {sqlassert-0.3.1.dist-info → sqlassert-0.4.1.dist-info}/WHEEL +0 -0
  73. {sqlassert-0.3.1.dist-info → sqlassert-0.4.1.dist-info}/licenses/LICENSE +0 -0
@@ -7,8 +7,10 @@ the default dataset unqualified names resolve in. Every view is read from
7
7
 
8
8
  BigQuery has no `REFERENTIAL_CONSTRAINTS`: a foreign key's referenced table
9
9
  and columns come from `CONSTRAINT_COLUMN_USAGE`, which does not order them,
10
- so a foreign key over more than one column is skipped. Keys are not
10
+ so a foreign key over more than one column is skipped. BigQuery has no
11
+ unique indexes (its search and vector indexes enforce nothing). Keys are not
11
12
  enforced: they hold only under `trust_unenforced_keys` (`dialects.py`).
13
+ BigQuery has no CHECK constraints, so none are read.
12
14
  """
13
15
 
14
16
  from __future__ import annotations
@@ -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
 
@@ -46,7 +47,7 @@ WHERE {_TABLES}
46
47
  ORDER BY table_name, column_index
47
48
  """
48
49
 
49
- # duckdb_columns() drops collations; the stored CREATE TABLE keeps them.
50
+ # duckdb_columns() drops a column's COLLATE; the stored CREATE TABLE keeps it.
50
51
  _TABLE_SQL = f"SELECT table_name, sql FROM duckdb_tables() WHERE {_TABLES}"
51
52
 
52
53
  # A foreign key's referenced table is in the referencing table's own catalog
@@ -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
 
@@ -110,17 +126,22 @@ class DuckDBKnowledgeFetcher(InformationSchemaKnowledgeFetcher):
110
126
 
111
127
  def columns(self, catalog: str, schema: str, tables: Sequence[str]) -> list[tuple[str, DatabaseColumn]]:
112
128
  lookup = (catalog, schema, list(tables))
113
- collations = self._collations(catalog, schema, lookup)
129
+ collated = self._collated(catalog, schema, lookup)
114
130
  return [
115
- (table, DatabaseColumn(column, nullable, data_type, collations.get(table, {}).get(column.lower())))
131
+ (table, DatabaseColumn(column, nullable, None if (table, column.lower()) in collated else data_type))
116
132
  for table, column, nullable, data_type in self._rows(_COLUMNS, lookup)
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,30 +150,47 @@ 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
135
159
 
136
- def _collations(self, catalog: str, schema: str, lookup: tuple[Any, ...]) -> dict[str, dict[str, str]]:
137
- """Each table's columns declared with a COLLATE, by name. The
160
+ def _collated(self, catalog: str, schema: str, lookup: tuple[Any, ...]) -> set[tuple[str, str]]:
161
+ """Each (table, lowercase column) declared with a COLLATE: sqlassert
162
+ supports the default collation only, so such a column is untyped. The
138
163
  session's `default_collation` is not read: text without a COLLATE has
139
164
  the engine's shipped (binary) default (docs/dialects.md)."""
140
- collations: dict[str, dict[str, str]] = {}
165
+ collated: set[tuple[str, str]] = set()
141
166
  for table, sql in self._rows(_TABLE_SQL, lookup):
142
167
  try:
143
168
  create = sqlglot.parse_one(sql, read="duckdb")
144
169
  except SqlglotError as error:
145
170
  raise DatabaseMetadataError(f"definition of table {catalog}.{schema}.{table} could not be parsed: {error}") from error
146
- own: dict[str, str] = {}
147
- for definition in create.find_all(exp.ColumnDef):
148
- collate = next((
149
- constraint.args["kind"] for constraint in definition.constraints
150
- if isinstance(constraint.args.get("kind"), exp.CollateColumnConstraint)
151
- ), None)
152
- if collate is not None:
153
- own[definition.name.lower()] = collate.this.name
154
- collations[table] = own
155
- return collations
171
+ collated.update(
172
+ (table, definition.name.lower()) for definition in create.find_all(exp.ColumnDef)
173
+ if any(isinstance(constraint.args.get("kind"), exp.CollateColumnConstraint) for constraint in definition.constraints)
174
+ )
175
+ return collated
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
+ ]
156
194
 
157
195
  def _rows(self, sql: str, parameters: tuple[Any, ...] = ()) -> list[tuple[Any, ...]]:
158
196
  """The rows of one catalog query, run on the connection (see the module
@@ -4,37 +4,49 @@ 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
21
32
 
22
33
  from abc import ABC, abstractmethod
23
34
  from collections.abc import Mapping
24
- from dataclasses import dataclass, field
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
30
42
 
31
43
  from sqlassert import diagnostics as diag
32
44
  from sqlassert import ir
33
- from sqlassert.diagnostics import Diagnostic
45
+ 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"
@@ -48,15 +60,14 @@ class DatabaseRelationKind(Enum):
48
60
  @dataclass(frozen=True)
49
61
  class DatabaseColumn:
50
62
  """One catalog column. `data_type` is its SQL type as the database writes
51
- it (in the fetcher's `type_dialect`), or None when unknown; `collation` is
52
- the collation its comparisons use, None for the database's binary default.
53
- A fetcher that cannot tell a column's collation leaves `data_type` None,
54
- so no comparison is assumed to be by identity."""
63
+ it (in the fetcher's `type_dialect`), or None when unknown. sqlassert
64
+ supports the dialect's default collation only: a fetcher reports a column
65
+ under any other collation that may not compare by identity with
66
+ `data_type` None, so no comparison of it is assumed to be by identity."""
55
67
 
56
68
  name: str
57
69
  nullable: bool
58
70
  data_type: str | None = None
59
- collation: str | None = None
60
71
 
61
72
 
62
73
  @dataclass(frozen=True)
@@ -73,8 +84,10 @@ class DatabaseForeignKey:
73
84
  class DatabaseRelationMetadata:
74
85
  """One catalog Relation, identified canonically, with its complete enforced facts.
75
86
 
76
- Columns, keys, unique sets, and foreign keys describe base tables only; a
77
- 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`.
78
91
  """
79
92
 
80
93
  catalog: str
@@ -85,6 +98,7 @@ class DatabaseRelationMetadata:
85
98
  primary_key: tuple[str, ...] = ()
86
99
  unique_sets: tuple[tuple[str, ...], ...] = ()
87
100
  foreign_keys: tuple[DatabaseForeignKey, ...] = ()
101
+ checks: tuple[str, ...] = ()
88
102
 
89
103
  @property
90
104
  def identity(self) -> str:
@@ -104,10 +118,14 @@ class DatabaseMetadataError(Exception):
104
118
 
105
119
  @dataclass(frozen=True)
106
120
  class DatabaseHydration:
107
- """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."""
108
125
 
109
126
  conversion: IrConversionResult
110
127
  tables: Mapping[str, DatabaseRelationMetadata] = field(default_factory=dict)
128
+ declared_targets: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
111
129
  diagnostics: tuple[Diagnostic, ...] = ()
112
130
  dialect: str = "duckdb"
113
131
  trust_unenforced_keys: bool = True
@@ -130,8 +148,35 @@ class DatabaseKnowledgeFetcher(ABC):
130
148
  # The SQL dialect the database writes column types in.
131
149
  type_dialect: str | None = None
132
150
 
133
- def hydrate(self, ast: ParsedProgram, *, dialect: str, trust_unenforced_keys: bool = True) -> DatabaseHydration:
134
- 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()
156
+
157
+ def convert(
158
+ self, ast: ParsedProgram, *, dialect: str, trust_unenforced_keys: bool = True,
159
+ required_relations: tuple[tuple[str, tuple[str, ...]], ...] = (),
160
+ ) -> tuple[IrConversionResult, DatabaseHydration]:
161
+ """`hydrate` and `bind` together: the conversion with the catalog's
162
+ declarations, Knowledge and diagnostics merged in, and the hydration.
163
+ Its warnings are the catalog facts' and the SQL's own
164
+ (`diagnostics.SQL_WARNINGS`): a connection warning asks for what the
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
+ )
170
+ conversion = hydration.conversion
171
+ facts = self.bind(conversion.program, hydration)
172
+ merged = replace(
173
+ conversion,
174
+ program=replace(conversion.program, declarations=conversion.program.declarations + facts.declarations),
175
+ knowledge=conversion.knowledge + facts.knowledge,
176
+ diagnostics=hydration.diagnostics + conversion.diagnostics,
177
+ warnings=(*facts.warnings, *(warning for warning in conversion.warnings if warning.code in diag.SQL_WARNINGS)),
178
+ )
179
+ return merged, hydration
135
180
 
136
181
  def bind(self, program: ir.Program, hydration: DatabaseHydration) -> CatalogFacts:
137
182
  """Catalog facts as Properties over ``program``'s Output Columns.
@@ -140,7 +185,9 @@ class DatabaseKnowledgeFetcher(ABC):
140
185
  where the dialect enforces them; elsewhere, as for SQL declarations,
141
186
  they are Property Declarations under `trust_unenforced_keys`, and
142
187
  otherwise left out with a warning (`docs/dialects.md`). A foreign key
143
- 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.
144
191
  """
145
192
  meaning = semantics(hydration.dialect)
146
193
  knowledge: list[Property] = []
@@ -155,18 +202,21 @@ class DatabaseKnowledgeFetcher(ABC):
155
202
  else:
156
203
  warnings.append(Diagnostic(
157
204
  diag.UNENFORCED_CONSTRAINT,
158
- f"the {kind} ({', '.join(columns)}) of {metadata.identity} is not Knowledge, since {hydration.dialect} "
205
+ f"the {kind} ({quoted_all(columns)}) of {metadata.identity} is not Knowledge, since {hydration.dialect} "
159
206
  "does not enforce it: if the data satisfies it, analyze with trust_unenforced_keys=True",
160
207
  _origin(metadata),
161
208
  ))
162
209
 
163
- tables = {
164
- metadata.identity.lower(): (relation, metadata)
165
- for relation in program.named_relations
210
+ declared = {relation.name.lower(): relation for relation in program.named_relations if relation.role is ir.RelationRole.TABLE}
211
+ tables = [
212
+ (relation, metadata) for relation in program.named_relations
166
213
  if relation.role is ir.RelationRole.TABLE and (metadata := hydration.tables.get(relation.name.lower())) is not None
167
- }
214
+ ]
215
+ by_identity: dict[str, list[tuple[ir.NamedRelation, DatabaseRelationMetadata]]] = {}
216
+ for relation, metadata in tables:
217
+ by_identity.setdefault(metadata.identity.lower(), []).append((relation, metadata))
168
218
  keys_enforced = meaning.unique_keys == "enforced"
169
- for relation, metadata in tables.values():
219
+ for relation, metadata in tables:
170
220
  columns = {column.name.lower(): column for column in relation.output_columns}
171
221
  non_null = sorted({column.name.lower() for column in metadata.columns if not column.nullable})
172
222
  knowledge.extend(NonNullColumn(column=columns[name]) for name in non_null if name in columns)
@@ -177,16 +227,36 @@ class DatabaseKnowledgeFetcher(ABC):
177
227
  facts.extend(NonNullColumn(column=columns[name.lower()]) for name in unique_set if name.lower() not in non_null)
178
228
  place(facts, keys_enforced, "primary key" if primary else "unique key", unique_set, metadata)
179
229
  for foreign_key in metadata.foreign_keys:
180
- if foreign_key.referenced.lower() not in tables:
181
- continue
182
- target, target_metadata = tables[foreign_key.referenced.lower()]
183
- if _incomplete_reference(foreign_key, target_metadata):
184
- continue # Never seen from a consistent catalog; no fact is safer than a wrong one.
185
- referenced = {column.name.lower(): column for column in target.output_columns}
186
- place([ReferentialCoverage(
187
- columns=tuple(columns[name.lower()] for name in foreign_key.columns),
188
- referenced_columns=tuple(referenced[name.lower()] for name in foreign_key.referenced_columns),
189
- )], meaning.foreign_keys == "enforced", "foreign key", foreign_key.columns, metadata)
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:
255
+ referenced = {column.name.lower(): column for column in target.output_columns}
256
+ place([ReferentialCoverage(
257
+ columns=tuple(columns[name.lower()] for name in foreign_key.columns),
258
+ referenced_columns=tuple(referenced[name.lower()] for name in foreign_key.referenced_columns),
259
+ )], meaning.foreign_keys == "enforced", "foreign key", foreign_key.columns, metadata)
190
260
  return CatalogFacts(tuple(knowledge), tuple(declarations), tuple(dict.fromkeys(warnings)))
191
261
 
192
262
  @abstractmethod
@@ -217,10 +287,10 @@ def _incompleteness(metadata: DatabaseRelationMetadata) -> str | None:
217
287
  names = {column.name.lower() for column in metadata.columns}
218
288
  for unique_set in _unique_sets(metadata):
219
289
  if not unique_set or not {name.lower() for name in unique_set} <= names:
220
- return f"has a key ({', '.join(unique_set)}) over columns it does not list"
290
+ return f"has a key ({quoted_all(unique_set)}) over columns it does not list"
221
291
  for foreign_key in metadata.foreign_keys:
222
292
  if not {name.lower() for name in foreign_key.columns} <= names or len(foreign_key.columns) != len(foreign_key.referenced_columns):
223
- return f"has a foreign key ({', '.join(foreign_key.columns)}) that does not pair columns it lists"
293
+ return f"has a foreign key ({quoted_all(foreign_key.columns)}) that does not pair columns it lists"
224
294
  return None
225
295
 
226
296
 
@@ -232,12 +302,21 @@ def _incomplete_reference(foreign_key: DatabaseForeignKey, target: DatabaseRelat
232
302
  class _Hydration:
233
303
  """The state of hydrating one SQL Program: catalog answers are memoized for it alone."""
234
304
 
235
- 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
+ ):
236
309
  self.fetcher = fetcher
237
310
  self.ast = ast
238
311
  self.dialect = dialect
239
312
  self.trust_unenforced_keys = trust_unenforced_keys
313
+ self.required_relations = required_relations
240
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
+ }
241
320
  self.resolved: dict[str, DatabaseRelationMetadata | None] = {}
242
321
  self.views: dict[str, exp.Create | None] = {}
243
322
  self.declarations: dict[str, exp.Create] = {}
@@ -248,18 +327,48 @@ class _Hydration:
248
327
  def run(self) -> DatabaseHydration:
249
328
  while True:
250
329
  program = ParsedProgram((*self.declarations.values(), *self.ast.create_statements), self.ast.root_select)
251
- 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)
252
334
  pending = tuple(dict.fromkeys(
253
335
  relation.name for relation in conversion.program.named_relations if self._is_external(relation)
254
336
  ))
255
337
  if not pending:
338
+ targets = self._declared_targets()
256
339
  return DatabaseHydration(
257
- 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,
258
341
  )
259
342
  self.resolved.update(self._resolve(tuple(name for name in pending if name.lower() not in self.resolved), None))
260
343
  for name in pending:
261
344
  self._declare(name, self.resolved[name.lower()])
262
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
+
263
372
  def _is_external(self, relation: ir.NamedRelation) -> bool:
264
373
  key = relation.name.lower()
265
374
  return (
@@ -304,7 +413,12 @@ class _Hydration:
304
413
  target = _table(name)
305
414
  if metadata.kind is DatabaseRelationKind.TABLE:
306
415
  columns = [self._column_definition(column) for column in metadata.columns]
307
- 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
308
422
  view = self._view(metadata)
309
423
  if view is None:
310
424
  return None
@@ -316,7 +430,7 @@ class _Hydration:
316
430
  return declaration
317
431
 
318
432
  def _column_definition(self, column: DatabaseColumn) -> exp.ColumnDef:
319
- """The column with its catalog type and collation, so the Program
433
+ """The column with its catalog type, so the Program
320
434
  compares and enumerates it as the database does; untyped if the type
321
435
  does not parse."""
322
436
  definition = exp.ColumnDef(this=exp.to_identifier(column.name))
@@ -327,11 +441,22 @@ class _Hydration:
327
441
  except SqlglotError:
328
442
  return definition
329
443
  definition.set("kind", kind)
330
- if column.collation is not None:
331
- collate = exp.CollateColumnConstraint(this=exp.to_identifier(column.collation))
332
- definition.append("constraints", exp.ColumnConstraint(kind=collate))
333
444
  return definition
334
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
+
335
460
  def _view(self, metadata: DatabaseRelationMetadata) -> exp.Create | None:
336
461
  """The view's definition with every Relation it reads named by canonical identity, memoized."""
337
462
  if metadata.identity not in self.views: