sqlassert 0.4.1__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 (42) hide show
  1. sqlassert/declared_types.py +158 -0
  2. sqlassert/diagnostics.py +1 -4
  3. sqlassert/dialects.py +118 -396
  4. sqlassert/discovery/bigquery.py +2 -2
  5. sqlassert/discovery/databricks.py +4 -6
  6. sqlassert/discovery/fetcher.py +22 -52
  7. sqlassert/discovery/information_schema.py +7 -10
  8. sqlassert/discovery/mysql.py +4 -8
  9. sqlassert/discovery/postgres.py +17 -26
  10. sqlassert/discovery/redshift.py +2 -2
  11. sqlassert/discovery/snowflake.py +2 -2
  12. sqlassert/functions/__init__.py +10 -0
  13. sqlassert/functions/load.py +375 -0
  14. sqlassert/functions/table.py +2721 -0
  15. sqlassert/hazards.py +1 -1
  16. sqlassert/ir/__init__.py +13 -5
  17. sqlassert/ir/convert/aggregation.py +2 -3
  18. sqlassert/ir/convert/expressions.py +76 -67
  19. sqlassert/ir/convert/parser.py +0 -4
  20. sqlassert/ir/convert/schema.py +11 -80
  21. sqlassert/ir/convert/selects.py +30 -15
  22. sqlassert/ir/convert/shared.py +2 -3
  23. sqlassert/ir/convert/sources.py +2 -1
  24. sqlassert/ir/convert/value_types.py +12 -157
  25. sqlassert/ir/model.py +331 -138
  26. sqlassert/main.py +7 -10
  27. sqlassert/rules/causes/domain.py +1 -1
  28. sqlassert/rules/causes/unique.py +46 -5
  29. sqlassert/rules/domain.py +1 -1
  30. sqlassert/rules/join_cardinality.py +14 -21
  31. sqlassert/rules/nullability.py +3 -3
  32. sqlassert/rules/uniqueness.py +42 -41
  33. sqlassert/rules/value_typing.py +266 -133
  34. sqlassert/suggest.py +2 -2
  35. {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/METADATA +18 -14
  36. sqlassert-0.4.2.dist-info/RECORD +72 -0
  37. sqlassert/ir/convert/builtins.py +0 -140
  38. sqlassert-0.4.1.dist-info/RECORD +0 -69
  39. {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/WHEEL +0 -0
  40. {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/entry_points.txt +0 -0
  41. {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/licenses/LICENSE +0 -0
  42. {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/top_level.txt +0 -0
@@ -8,8 +8,8 @@ the default dataset unqualified names resolve in. Every view is read from
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
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
12
- enforced: they hold only under `trust_unenforced_keys` (`dialects.py`).
11
+ unique indexes (its search and vector indexes enforce nothing). Its keys
12
+ are not enforced, yet trusted like every declared constraint (ADR 0012).
13
13
  BigQuery has no CHECK constraints, so none are read.
14
14
  """
15
15
 
@@ -2,13 +2,11 @@
2
2
 
3
3
  Unity Catalog's `information_schema` has every standard view this reads, so
4
4
  only the session query and the parameter style (`?`) differ. Databricks has
5
- no unique indexes. Primary and
6
- foreign keys are informational: they hold only under
7
- `trust_unenforced_keys` (`dialects.py`); the `RELY` a constraint may carry is
8
- not read. Names qualified by another catalog are not looked up.
5
+ no unique indexes. Its primary and foreign keys are informational, yet
6
+ trusted like every declared constraint (ADR 0012). Names qualified by
7
+ another catalog are not looked up.
9
8
 
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
9
+ Unity Catalog's `CHECK_CONSTRAINTS` view
12
10
  is empty (reserved), so they are read from each table's properties, where
13
11
  Delta keeps each as `delta.constraints.<name>`. Unprobed: written from the
14
12
  Databricks documentation, not run against a workspace.
@@ -4,21 +4,19 @@ 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 `CREATE TABLE` of its columns and the CHECK
8
- constraints the database enforces, a fetched view the `CREATE VIEW` the
7
+ a fetched table becomes a `CREATE TABLE` of its columns and its CHECK
8
+ constraints, a fetched view the `CREATE VIEW` the
9
9
  database stored. Each relink reveals the Relations the new
10
10
  view bodies read, so view expansion recurses until nothing new is reached; a
11
11
  cycle among views is left to the linker, which reports it.
12
12
 
13
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
14
+ the same Enumerated Domains and the
15
15
  same `ignored-check-constraint` warning for one it does not read. Other
16
16
  catalog constraints never pass through those declarations. `bind` turns them
17
17
  into Properties over the final IR's own Output Columns, so the engine sees
18
- Properties only, never a name, a catalog row, or a connection: Knowledge for
19
- what the dialect enforces, Property Declarations for unenforced keys the
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
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
22
20
  that declaration, the table the query reads by that name (ADR 0005): the
23
21
  hydration asks the catalog which of the SQL's tables are its target, and
24
22
  `bind` warns `unbound-foreign-key` when the declaration lacks a referenced
@@ -128,17 +126,14 @@ class DatabaseHydration:
128
126
  declared_targets: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
129
127
  diagnostics: tuple[Diagnostic, ...] = ()
130
128
  dialect: str = "duckdb"
131
- trust_unenforced_keys: bool = True
132
129
 
133
130
 
134
131
  @dataclass(frozen=True)
135
132
  class CatalogFacts:
136
- """What `bind` makes of the catalog: Knowledge the database enforces,
137
- Property Declarations it does not but the caller trusts, and a warning
138
- for each key left out."""
133
+ """What `bind` makes of the catalog: Knowledge, and a warning for each
134
+ foreign key left unbound."""
139
135
 
140
136
  knowledge: tuple[Property, ...] = ()
141
- declarations: tuple[Property, ...] = ()
142
137
  warnings: tuple[Diagnostic, ...] = ()
143
138
 
144
139
 
@@ -149,14 +144,12 @@ class DatabaseKnowledgeFetcher(ABC):
149
144
  type_dialect: str | None = None
150
145
 
151
146
  def hydrate(
152
- self, ast: ParsedProgram, *, dialect: str, trust_unenforced_keys: bool = True,
153
- required_relations: tuple[tuple[str, tuple[str, ...]], ...] = (),
147
+ self, ast: ParsedProgram, *, dialect: str, required_relations: tuple[tuple[str, tuple[str, ...]], ...] = (),
154
148
  ) -> DatabaseHydration:
155
- return _Hydration(self, ast, dialect, trust_unenforced_keys, required_relations).run()
149
+ return _Hydration(self, ast, dialect, required_relations).run()
156
150
 
157
151
  def convert(
158
- self, ast: ParsedProgram, *, dialect: str, trust_unenforced_keys: bool = True,
159
- required_relations: tuple[tuple[str, tuple[str, ...]], ...] = (),
152
+ self, ast: ParsedProgram, *, dialect: str, required_relations: tuple[tuple[str, tuple[str, ...]], ...] = (),
160
153
  ) -> tuple[IrConversionResult, DatabaseHydration]:
161
154
  """`hydrate` and `bind` together: the conversion with the catalog's
162
155
  declarations, Knowledge and diagnostics merged in, and the hydration.
@@ -164,14 +157,11 @@ class DatabaseKnowledgeFetcher(ABC):
164
157
  (`diagnostics.SQL_WARNINGS`): a connection warning asks for what the
165
158
  catalog has just answered. `required_relations` are reached as
166
159
  `IrParser`'s are."""
167
- hydration = self.hydrate(
168
- ast, dialect=dialect, trust_unenforced_keys=trust_unenforced_keys, required_relations=required_relations,
169
- )
160
+ hydration = self.hydrate(ast, dialect=dialect, required_relations=required_relations)
170
161
  conversion = hydration.conversion
171
162
  facts = self.bind(conversion.program, hydration)
172
163
  merged = replace(
173
164
  conversion,
174
- program=replace(conversion.program, declarations=conversion.program.declarations + facts.declarations),
175
165
  knowledge=conversion.knowledge + facts.knowledge,
176
166
  diagnostics=hydration.diagnostics + conversion.diagnostics,
177
167
  warnings=(*facts.warnings, *(warning for warning in conversion.warnings if warning.code in diag.SQL_WARNINGS)),
@@ -181,32 +171,16 @@ class DatabaseKnowledgeFetcher(ABC):
181
171
  def bind(self, program: ir.Program, hydration: DatabaseHydration) -> CatalogFacts:
182
172
  """Catalog facts as Properties over ``program``'s Output Columns.
183
173
 
184
- NOT NULL columns are Knowledge. Keys and foreign keys are Knowledge
185
- where the dialect enforces them; elsewhere, as for SQL declarations,
186
- they are Property Declarations under `trust_unenforced_keys`, and
187
- otherwise left out with a warning (`docs/dialects.md`). A foreign key
174
+ NOT NULL columns, keys and foreign keys are Knowledge, whether or
175
+ not the database enforces them (ADR 0012). A foreign key
188
176
  binds only when the Program reaches its referenced Relation: a
189
177
  catalog table, or a table the SQL declares (`declared_targets`) and
190
178
  declares once, with every referenced column; otherwise it warns.
191
179
  """
192
180
  meaning = semantics(hydration.dialect)
193
181
  knowledge: list[Property] = []
194
- declarations: list[Property] = []
195
182
  warnings: list[Diagnostic] = []
196
183
 
197
- def place(facts: list[Property], enforced: bool, kind: str, columns: tuple[str, ...], metadata: DatabaseRelationMetadata) -> None:
198
- if enforced:
199
- knowledge.extend(facts)
200
- elif hydration.trust_unenforced_keys:
201
- declarations.extend(facts)
202
- else:
203
- warnings.append(Diagnostic(
204
- diag.UNENFORCED_CONSTRAINT,
205
- f"the {kind} ({quoted_all(columns)}) of {metadata.identity} is not Knowledge, since {hydration.dialect} "
206
- "does not enforce it: if the data satisfies it, analyze with trust_unenforced_keys=True",
207
- _origin(metadata),
208
- ))
209
-
210
184
  declared = {relation.name.lower(): relation for relation in program.named_relations if relation.role is ir.RelationRole.TABLE}
211
185
  tables = [
212
186
  (relation, metadata) for relation in program.named_relations
@@ -215,17 +189,14 @@ class DatabaseKnowledgeFetcher(ABC):
215
189
  by_identity: dict[str, list[tuple[ir.NamedRelation, DatabaseRelationMetadata]]] = {}
216
190
  for relation, metadata in tables:
217
191
  by_identity.setdefault(metadata.identity.lower(), []).append((relation, metadata))
218
- keys_enforced = meaning.unique_keys == "enforced"
219
192
  for relation, metadata in tables:
220
193
  columns = {column.name.lower(): column for column in relation.output_columns}
221
194
  non_null = sorted({column.name.lower() for column in metadata.columns if not column.nullable})
222
195
  knowledge.extend(NonNullColumn(column=columns[name]) for name in non_null if name in columns)
223
196
  for position, unique_set in enumerate(_unique_sets(metadata)):
224
- facts: list[Property] = [UniqueSet(columns=frozenset(columns[name.lower()] for name in unique_set))]
225
- primary = position == 0 and bool(metadata.primary_key)
226
- if primary and (meaning.primary_key_not_null or not keys_enforced):
227
- facts.extend(NonNullColumn(column=columns[name.lower()]) for name in unique_set if name.lower() not in non_null)
228
- 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)
229
200
  for foreign_key in metadata.foreign_keys:
230
201
  identity = foreign_key.referenced.lower()
231
202
  targets = [target for target, target_metadata in by_identity.get(identity, ())
@@ -253,11 +224,11 @@ class DatabaseKnowledgeFetcher(ABC):
253
224
  targets.append(target)
254
225
  for target in targets:
255
226
  referenced = {column.name.lower(): column for column in target.output_columns}
256
- place([ReferentialCoverage(
227
+ knowledge.append(ReferentialCoverage(
257
228
  columns=tuple(columns[name.lower()] for name in foreign_key.columns),
258
229
  referenced_columns=tuple(referenced[name.lower()] for name in foreign_key.referenced_columns),
259
- )], meaning.foreign_keys == "enforced", "foreign key", foreign_key.columns, metadata)
260
- return CatalogFacts(tuple(knowledge), tuple(declarations), tuple(dict.fromkeys(warnings)))
230
+ ))
231
+ return CatalogFacts(tuple(knowledge), tuple(dict.fromkeys(warnings)))
261
232
 
262
233
  @abstractmethod
263
234
  def fetch_relation_metadata(
@@ -303,13 +274,12 @@ class _Hydration:
303
274
  """The state of hydrating one SQL Program: catalog answers are memoized for it alone."""
304
275
 
305
276
  def __init__(
306
- self, fetcher: DatabaseKnowledgeFetcher, ast: ParsedProgram, dialect: str, trust_unenforced_keys: bool,
277
+ self, fetcher: DatabaseKnowledgeFetcher, ast: ParsedProgram, dialect: str,
307
278
  required_relations: tuple[tuple[str, tuple[str, ...]], ...],
308
279
  ):
309
280
  self.fetcher = fetcher
310
281
  self.ast = ast
311
282
  self.dialect = dialect
312
- self.trust_unenforced_keys = trust_unenforced_keys
313
283
  self.required_relations = required_relations
314
284
  self.sql_declared = {_qualified_name(table).lower() for table in map(_created_table, ast.create_statements) if table is not None}
315
285
  self.sql_tables = {
@@ -328,7 +298,7 @@ class _Hydration:
328
298
  while True:
329
299
  program = ParsedProgram((*self.declarations.values(), *self.ast.create_statements), self.ast.root_select)
330
300
  conversion = IrParser(
331
- self.dialect, self.trust_unenforced_keys, self.required_relations,
301
+ self.dialect, self.required_relations,
332
302
  catalog_primary_keys={key: table.primary_key for key, table in self.tables.items() if table.primary_key},
333
303
  ).parse(program)
334
304
  pending = tuple(dict.fromkeys(
@@ -337,7 +307,7 @@ class _Hydration:
337
307
  if not pending:
338
308
  targets = self._declared_targets()
339
309
  return DatabaseHydration(
340
- conversion, dict(self.tables), targets, tuple(dict.fromkeys(self.diagnostics)), self.dialect, self.trust_unenforced_keys,
310
+ conversion, dict(self.tables), targets, tuple(dict.fromkeys(self.diagnostics)), self.dialect,
341
311
  )
342
312
  self.resolved.update(self._resolve(tuple(name for name in pending if name.lower() not in self.resolved), None))
343
313
  for name in pending:
@@ -15,14 +15,11 @@ 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.
23
21
  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,
22
+ - CHECK constraints are reported as the text of their condition; the hydration declares them with the table,
26
23
  so they mean what the same CHECK written in SQL means.
27
24
  """
28
25
 
@@ -167,10 +164,10 @@ ORDER BY k.TABLE_NAME, k.CONSTRAINT_NAME, k.ORDINAL_POSITION
167
164
  return foreign_keys_from_pairs(self._rows(sql, (schema, *tables)))
168
165
 
169
166
  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."""
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."""
174
171
  return []
175
172
 
176
173
  def view_definition(self, relation: DatabaseRelationMetadata) -> str | None:
@@ -8,13 +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;
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).
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).
18
14
 
19
15
  MySQL has one catalog, which `information_schema` names `def`. A stored view
20
16
  definition qualifies every table it reads; an unqualified name in the Program
@@ -79,7 +75,7 @@ class MySQLKnowledgeFetcher(InformationSchemaKnowledgeFetcher):
79
75
  "SELECT t.TABLE_NAME, c.CHECK_CLAUSE FROM information_schema.TABLE_CONSTRAINTS t "
80
76
  "JOIN information_schema.CHECK_CONSTRAINTS c "
81
77
  "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)}) "
78
+ f"WHERE t.CONSTRAINT_TYPE = 'CHECK' AND t.TABLE_SCHEMA = %s AND t.TABLE_NAME IN ({placeholders(tables)}) "
83
79
  "ORDER BY t.TABLE_NAME, t.CONSTRAINT_NAME"
84
80
  )
85
81
  return [(table, _unescaped(clause)) for table, clause in self._rows(sql, (schema, *tables))]
@@ -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 (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
- 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, NOT NULLs and CHECKs need 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,16 +81,14 @@ 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
 
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.
84
+ # Column-level and table-level CHECKs are alike here.
91
85
  # `pg_get_expr` deparses the stored condition: `col IN (...)` comes back as
92
86
  # `col = ANY (ARRAY[...])`, literals cast, which the CHECK reading accepts.
93
87
  _CHECKS = f"""
94
88
  SELECT c.relname, pg_catalog.pg_get_expr(k.conbin, k.conrelid)
95
89
  FROM pg_catalog.pg_constraint k
96
90
  JOIN {_RELATION} ON c.oid = k.conrelid
97
- WHERE k.contype = 'c' AND k.convalidated {{enforced}} AND {_TABLES}
91
+ WHERE k.contype = 'c' AND {_TABLES}
98
92
  ORDER BY c.relname, k.conname
99
93
  """
100
94
 
@@ -108,20 +102,18 @@ WHERE n.nspname = %s AND c.relname = %s AND c.relkind = 'v'
108
102
  class PostgresKnowledgeFetcher(InformationSchemaKnowledgeFetcher):
109
103
  type_dialect = "postgres"
110
104
  case_sensitive = True
111
- _enforced = False
112
105
 
113
106
  def session(self, scope: DatabaseRelationMetadata | None) -> tuple[str, tuple[str, ...]]:
114
107
  # A stored view definition names relations as the session's search path
115
108
  # sees them (pg_get_viewdef qualifies the rest), so `scope` changes nothing.
116
- (database, search_path, version), = self._rows(_SESSION)
117
- self._enforced = version >= 180000
109
+ (database, search_path), = self._rows(_SESSION)
118
110
  return database, tuple(search_path)
119
111
 
120
112
  def relations(self, catalog: str, schema: str, names: Sequence[str]) -> list[FoundRelation]:
121
113
  return [
122
114
  FoundRelation(
123
115
  database, found_schema, name, DatabaseRelationKind.VIEW if kind == "v" else DatabaseRelationKind.TABLE,
124
- facts_hold=not inherited and kind != "f",
116
+ facts_hold=not inherited,
125
117
  )
126
118
  for database, found_schema, name, kind, inherited in self._rows(_RELATIONS, (schema.lower(), list(names)))
127
119
  ]
@@ -148,12 +140,11 @@ class PostgresKnowledgeFetcher(InformationSchemaKnowledgeFetcher):
148
140
  ]
149
141
 
150
142
  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)))]
143
+ return [(table, condition) for table, condition in self._rows(_CHECKS, (schema, list(tables)))]
153
144
 
154
145
  def view_definition(self, relation: DatabaseRelationMetadata) -> str | None:
155
146
  rows = self._rows(VIEW, (relation.schema, relation.name))
156
147
  return rows[0][0] if rows else None
157
148
 
158
149
  def _constraints(self, kinds: str) -> str:
159
- return _CONSTRAINTS.format(kinds=kinds, enforced="AND k.conenforced" if self._enforced else "")
150
+ return _CONSTRAINTS.format(kinds=kinds)
@@ -2,8 +2,8 @@
2
2
 
3
3
  Redshift keeps PostgreSQL 8's `information_schema` and has no indexes, so
4
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:
5
+ not support. Its keys are not enforced, yet trusted like every declared
6
+ constraint (ADR 0012). Overrides:
7
7
 
8
8
  - session: `current_database()` and `current_schema()`. An unqualified name
9
9
  is looked up in the current schema only, so a table found later on the
@@ -4,8 +4,8 @@ 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
11
  Snowflake has no unique indexes: a hybrid table's indexes are not unique, and
@@ -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
+ ]