sqlassert 0.1.2__py3-none-any.whl → 0.3.3__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 (50) hide show
  1. sqlassert/__init__.py +34 -9
  2. sqlassert/__main__.py +9 -0
  3. sqlassert/check.py +451 -0
  4. sqlassert/diagnostics.py +70 -0
  5. sqlassert/dialects.py +258 -0
  6. sqlassert/discovery/__init__.py +30 -0
  7. sqlassert/discovery/bigquery.py +71 -0
  8. sqlassert/discovery/databricks.py +18 -0
  9. sqlassert/discovery/duckdb.py +159 -0
  10. sqlassert/discovery/fetcher.py +418 -0
  11. sqlassert/discovery/information_schema.py +327 -0
  12. sqlassert/discovery/mysql.py +70 -0
  13. sqlassert/discovery/postgres.py +142 -0
  14. sqlassert/discovery/redshift.py +36 -0
  15. sqlassert/discovery/snowflake.py +63 -0
  16. sqlassert/discovery/trino.py +37 -0
  17. sqlassert/edits.py +240 -0
  18. sqlassert/hazards.py +574 -0
  19. sqlassert/ir/__init__.py +58 -0
  20. sqlassert/ir/convert.py +3509 -0
  21. sqlassert/ir/model.py +779 -0
  22. sqlassert/main.py +51 -0
  23. sqlassert/properties.py +121 -0
  24. sqlassert/provenance.py +73 -0
  25. sqlassert/python_engine.py +356 -0
  26. sqlassert/reporting.py +105 -0
  27. sqlassert/rewrites.py +1541 -0
  28. sqlassert/rules/STYLEGUIDE.md +19 -0
  29. sqlassert/rules/__init__.py +11 -0
  30. sqlassert/rules/column_set.py +34 -0
  31. sqlassert/rules/domain.py +472 -0
  32. sqlassert/rules/equality.py +442 -0
  33. sqlassert/rules/exactly_one.py +114 -0
  34. sqlassert/rules/foreign_key.py +319 -0
  35. sqlassert/rules/join_cardinality.py +116 -0
  36. sqlassert/rules/nullability.py +627 -0
  37. sqlassert/rules/uniqueness.py +904 -0
  38. sqlassert/sql_parse.py +1081 -0
  39. sqlassert/suggest.py +418 -0
  40. sqlassert-0.3.3.dist-info/METADATA +807 -0
  41. sqlassert-0.3.3.dist-info/RECORD +46 -0
  42. {sqlassert-0.1.2.dist-info → sqlassert-0.3.3.dist-info}/WHEEL +1 -1
  43. sqlassert-0.3.3.dist-info/entry_points.txt +2 -0
  44. sqlassert-0.3.3.dist-info/licenses/LICENSE +21 -0
  45. sqlassert-0.3.3.dist-info/top_level.txt +2 -0
  46. sqlassert_cli.py +130 -0
  47. sqlassert/unique.py +0 -605
  48. sqlassert-0.1.2.dist-info/METADATA +0 -173
  49. sqlassert-0.1.2.dist-info/RECORD +0 -6
  50. sqlassert-0.1.2.dist-info/top_level.txt +0 -1
sqlassert/dialects.py ADDED
@@ -0,0 +1,258 @@
1
+ """What each SQL dialect means by the constructs the analysis depends on.
2
+
3
+ One `DialectSemantics` per dialect name (SQLGlot's), read by `ir/convert.py`
4
+ while it lowers SQL: which Builtins raise an error rather than return NULL,
5
+ which text compares by identity, what `||`, `concat()`, `greatest()` and
6
+ subscripts do with NULL, and which constraints the database enforces. A dialect not listed gets
7
+ `DialectSemantics()`, whose arithmetic, collation and `||` are the cautious
8
+ choice; only its keys are taken as enforced, as before dialects were listed.
9
+
10
+ Every flag is a claim about the dialect's latest release under its default
11
+ settings, strict modes on (ADR 0006): MySQL's `||` is OR, since the default
12
+ `sql_mode` has no PIPES_AS_CONCAT; Spark is modelled with ANSI mode on. `docs/dialects.md` argues each entry and says how soundness is judged
13
+ without DuckDB; `docs/dialect-provenance.json` records, per fact, the engine
14
+ versions it was certified on or the vendor doc it rests on
15
+ (`scripts/certify_dialects.py`).
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from dataclasses import dataclass, replace
21
+ from typing import Literal
22
+
23
+ # How a dialect treats a declared key (PRIMARY KEY, UNIQUE) or foreign key:
24
+ # enforced; informational, trusted when marked `RELY`; or informational only.
25
+ type KeyTrust = Literal["enforced", "rely", "unenforced"]
26
+
27
+ # What `a || b` is: concatenation whose NULL operand makes it NULL ("strict"),
28
+ # or concatenation that may skip a NULL operand ("lenient", Postgres arrays);
29
+ # None when it is not modelled (MySQL, where it is OR).
30
+ type PipesMeaning = Literal["strict", "lenient"] | None
31
+
32
+ # What `concat(a, ...)` does with NULL: makes the result NULL ("strict"), or
33
+ # skips it, so the result is never NULL ("skips-null"); None when not modelled.
34
+ type ConcatMeaning = Literal["strict", "skips-null"] | None
35
+
36
+ # What `greatest(a, ...)` and `least(a, ...)` do with NULL: make the result
37
+ # NULL ("strict"), or skip it, so the result is NULL only when every argument
38
+ # is ("skips-null"); None when not modelled.
39
+ type GreatestMeaning = Literal["strict", "skips-null"] | None
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class DialectSemantics:
44
+ # `+`, `-`, `*`, unary `-` and CAST raise an error on overflow or a bad
45
+ # value rather than wrapping, saturating, or returning NULL.
46
+ checked_arithmetic: bool = False
47
+ # `/`, integer division and `%` by zero raise an error rather than return NULL.
48
+ checked_division: bool = False
49
+ # `sum` and `avg` of non-null values are never NULL: an overflow raises
50
+ # (or widens the type) rather than returning NULL, and NaN or infinity is
51
+ # a value, not NULL (SQLite turns NaN into NULL).
52
+ checked_sum: bool = False
53
+ # An implicit cast that fails raises an error, so a comparison, LIKE,
54
+ # BETWEEN, NOT or bitwise operator of non-null operands is never NULL.
55
+ casts_raise: bool = True
56
+ # VARCHAR and TEXT compare by identity under the engine's shipped default
57
+ # collation. A setting that changes that default (DuckDB's
58
+ # `default_collation`) is out of scope, and a COLLATE is unsupported: it
59
+ # is opaque, and a column declared with one is untyped (docs/dialects.md).
60
+ text_is_binary: bool = False
61
+ # A DECIMAL declared without a scale keeps each value's own scale, so
62
+ # equal values (1.0, 1.00) may differ: neither identity nor exact.
63
+ unscaled_decimal: bool = False
64
+ # A TIMESTAMP WITH TIME ZONE (SQLGlot's TIMESTAMPTZ: MySQL's, BigQuery's
65
+ # and Spark's TIMESTAMP too) holds an instant only, so equal values are
66
+ # identical. Not where it keeps the zone it was given (Trino, Snowflake's
67
+ # TIMESTAMP_TZ, Oracle): equal instants in two zones differ as text.
68
+ zoned_timestamp_is_instant: bool = False
69
+ pipes: PipesMeaning = None
70
+ concat: ConcatMeaning = None
71
+ # What `concat_ws(sep, a, ...)` does with a NULL value (a NULL separator
72
+ # makes it NULL either way); None where it does not exist or is not modelled.
73
+ concat_ws: ConcatMeaning = None
74
+ greatest: GreatestMeaning = None
75
+ # `xs[i]` (an element of a list, array, map or struct) is NULL when `xs` is.
76
+ subscript_strict: bool = False
77
+ unique_keys: KeyTrust = "enforced"
78
+ foreign_keys: KeyTrust = "enforced"
79
+ # CHECK constraints. Where the dialect has none (Snowflake, BigQuery,
80
+ # Redshift, Trino), one in the SQL describes a table another engine holds.
81
+ check_constraints: KeyTrust = "enforced"
82
+ # A PRIMARY KEY column is NOT NULL.
83
+ primary_key_not_null: bool = True
84
+ # A column-level `REFERENCES` is enforced (MySQL before 9.0 parses and ignores it).
85
+ inline_references: bool = True
86
+ # The table ENGINEs that enforce foreign keys (lower-cased), None for every table.
87
+ foreign_key_engines: frozenset[str] | None = None
88
+ # An ENUM's members lose their trailing spaces (MySQL). An ENUM holds only
89
+ # its members: MySQL's '' for any other value, outside strict mode or
90
+ # under INSERT IGNORE, is out of scope (docs/dialects.md).
91
+ enum_strips_trailing_spaces: bool = False
92
+ # A zero-length string is NULL (Oracle): the literal '' is NULL.
93
+ empty_string_is_null: bool = False
94
+ # `EXCEPT ALL` and `INTERSECT ALL` exist. Only gates suggesting them, so
95
+ # it is no soundness claim and is not certified: a wrong True suggests SQL
96
+ # the engine rejects, never a wrong proof.
97
+ set_operations_all: bool = False
98
+
99
+ @property
100
+ def rely(self) -> bool:
101
+ """Whether the dialect marks an informational constraint trusted with `RELY`."""
102
+ return "rely" in (self.unique_keys, self.foreign_keys)
103
+
104
+
105
+ # Spark 4 and Databricks under ANSI mode, their default (ADR 0006): overflow
106
+ # and a bad CAST raise. Apache Spark's docs say `div` by zero is NULL and do
107
+ # not say a failed implicit cast in a comparison raises; Databricks's say
108
+ # both raise (docs/dialect-provenance.json).
109
+ _SPARK = DialectSemantics(
110
+ checked_arithmetic=True,
111
+ casts_raise=False,
112
+ zoned_timestamp_is_instant=True,
113
+ pipes="strict",
114
+ concat="strict",
115
+ concat_ws="skips-null",
116
+ # Certified on Spark 4.3, not Databricks (`databricks` below drops them).
117
+ checked_sum=True,
118
+ greatest="skips-null",
119
+ subscript_strict=True,
120
+ unique_keys="rely",
121
+ foreign_keys="rely",
122
+ # Delta tables check them, other tables cannot declare them.
123
+ check_constraints="unenforced",
124
+ set_operations_all=True,
125
+ )
126
+
127
+ _SEMANTICS: dict[str, DialectSemantics] = {
128
+ "duckdb": DialectSemantics(
129
+ checked_arithmetic=True,
130
+ checked_sum=True,
131
+ text_is_binary=True,
132
+ zoned_timestamp_is_instant=True,
133
+ pipes="strict",
134
+ concat="skips-null",
135
+ concat_ws="skips-null",
136
+ greatest="skips-null",
137
+ subscript_strict=True,
138
+ set_operations_all=True,
139
+ ),
140
+ "postgres": DialectSemantics(
141
+ checked_arithmetic=True,
142
+ checked_division=True,
143
+ checked_sum=True,
144
+ text_is_binary=True,
145
+ unscaled_decimal=True,
146
+ zoned_timestamp_is_instant=True,
147
+ pipes="lenient", # `ARRAY[1] || NULL` is `{1}`.
148
+ concat="skips-null",
149
+ concat_ws="skips-null",
150
+ greatest="skips-null",
151
+ subscript_strict=True,
152
+ set_operations_all=True,
153
+ ),
154
+ "mysql": DialectSemantics(
155
+ # MySQL under its default strict sql_mode only (docs/dialects.md), so
156
+ # a comparison of non-null operands is non-null. Not `checked_arithmetic`:
157
+ # `-x` of the least BIGINT is an exact DECIMAL rather than an error, and
158
+ # division by zero is NULL in any mode.
159
+ # `sum` of integers is an exact DECIMAL, and a DOUBLE holds no
160
+ # infinity or NaN (a DOUBLE sum that overflows is 0).
161
+ checked_sum=True,
162
+ # Not `text_is_binary`: the default collations ignore case (and
163
+ # accents, and some trailing spaces).
164
+ zoned_timestamp_is_instant=True, # TIMESTAMP is converted to UTC.
165
+ concat="strict",
166
+ concat_ws="skips-null",
167
+ greatest="strict",
168
+ # Not `subscript_strict`: MySQL has no `xs[i]`.
169
+ inline_references=False,
170
+ foreign_key_engines=frozenset({"innodb", "ndb", "ndbcluster"}),
171
+ enum_strips_trailing_spaces=True,
172
+ set_operations_all=True, # Since 8.0.31.
173
+ ),
174
+ "snowflake": DialectSemantics(
175
+ # Not `checked_arithmetic`: its docs never say integer overflow raises.
176
+ checked_division=True,
177
+ pipes="strict",
178
+ concat="strict",
179
+ concat_ws="strict", # `concat_ws(',', 'a', NULL)` is NULL.
180
+ unique_keys="rely",
181
+ foreign_keys="rely",
182
+ check_constraints="unenforced",
183
+ ),
184
+ "bigquery": DialectSemantics(
185
+ checked_arithmetic=True,
186
+ checked_division=True,
187
+ # Its docs: overflow raises, and NaN or an infinity makes NaN or an infinity.
188
+ checked_sum=True,
189
+ zoned_timestamp_is_instant=True,
190
+ pipes="strict",
191
+ concat="strict",
192
+ unique_keys="unenforced",
193
+ foreign_keys="unenforced",
194
+ check_constraints="unenforced",
195
+ ),
196
+ "redshift": DialectSemantics(
197
+ checked_arithmetic=True,
198
+ checked_division=True,
199
+ # Not `checked_sum`: its docs say nothing of a sum that overflows or meets NaN.
200
+ zoned_timestamp_is_instant=True,
201
+ pipes="strict",
202
+ unique_keys="unenforced",
203
+ foreign_keys="unenforced",
204
+ check_constraints="unenforced",
205
+ ),
206
+ "databricks": replace(
207
+ _SPARK, checked_division=True, casts_raise=True,
208
+ # Certified on Apache Spark only; Databricks's docs do not say a sum meets NaN as a value.
209
+ checked_sum=False, greatest=None, subscript_strict=False,
210
+ ),
211
+ "spark": _SPARK,
212
+ "hive": DialectSemantics(casts_raise=False, pipes="strict", concat="strict", unique_keys="unenforced", foreign_keys="unenforced",
213
+ check_constraints="unenforced",
214
+ ),
215
+ "sqlite": DialectSemantics(
216
+ pipes="strict",
217
+ concat_ws="skips-null",
218
+ # Foreign keys are checked only under `PRAGMA foreign_keys = ON`, off by default.
219
+ foreign_keys="unenforced",
220
+ # Only an INTEGER PRIMARY KEY (the rowid) is never NULL.
221
+ primary_key_not_null=False,
222
+ ),
223
+ # A ClickHouse primary key orders and indexes a table; it never rejects a duplicate.
224
+ "clickhouse": DialectSemantics(concat_ws="strict", unique_keys="unenforced", foreign_keys="unenforced"),
225
+ "oracle": DialectSemantics(empty_string_is_null=True),
226
+ # Trino has no constraint but NOT NULL: its CREATE TABLE rejects a key, so
227
+ # one in the SQL describes a table some other engine holds.
228
+ "trino": DialectSemantics(
229
+ checked_arithmetic=True,
230
+ checked_division=True,
231
+ checked_sum=True,
232
+ # VARCHAR compares by code point and Trino has no collations.
233
+ text_is_binary=True,
234
+ # Not `zoned_timestamp_is_instant`: a TIMESTAMP WITH TIME ZONE keeps
235
+ # its zone, and `CAST(ts AS VARCHAR)` writes it.
236
+ # Unlike Postgres, a NULL array or element operand makes `||` NULL too.
237
+ pipes="strict",
238
+ concat="strict",
239
+ greatest="strict",
240
+ # NULL for a NULL array or map; an index out of range raises.
241
+ subscript_strict=True,
242
+ # Not modelled: it skips a NULL VARCHAR, but its ARRAY(VARCHAR)
243
+ # overload is NULL for a NULL array, and SQLGlot parses both alike.
244
+ unique_keys="unenforced",
245
+ foreign_keys="unenforced",
246
+ check_constraints="unenforced",
247
+ set_operations_all=True,
248
+ ),
249
+ }
250
+
251
+
252
+ # The dialects whose semantics are argued here (docs/dialects.md).
253
+ MODELLED_DIALECTS = frozenset(_SEMANTICS)
254
+
255
+
256
+ def semantics(dialect: str) -> DialectSemantics:
257
+ """The semantics of a SQLGlot dialect name; cautious defaults for one not listed."""
258
+ return _SEMANTICS.get(dialect.lower(), DialectSemantics())
@@ -0,0 +1,30 @@
1
+ """Database Knowledge discovery: catalog metadata bound to IR nodes before the engine runs.
2
+
3
+ Database adapters live in submodules, such as `sqlassert.discovery.duckdb`
4
+ and `sqlassert.discovery.postgres`, so importing this package never imports
5
+ a database driver. `information_schema.py` is the base of every DB-API one.
6
+ """
7
+
8
+ from sqlassert.discovery.fetcher import (
9
+ CatalogFacts,
10
+ DatabaseColumn,
11
+ DatabaseForeignKey,
12
+ DatabaseHydration,
13
+ DatabaseKnowledgeFetcher,
14
+ DatabaseMetadataError,
15
+ DatabaseRelationKind,
16
+ DatabaseRelationMetadata,
17
+ DatabaseViewDefinition,
18
+ )
19
+
20
+ __all__ = [
21
+ "CatalogFacts",
22
+ "DatabaseColumn",
23
+ "DatabaseForeignKey",
24
+ "DatabaseHydration",
25
+ "DatabaseKnowledgeFetcher",
26
+ "DatabaseMetadataError",
27
+ "DatabaseRelationKind",
28
+ "DatabaseRelationMetadata",
29
+ "DatabaseViewDefinition",
30
+ ]
@@ -0,0 +1,71 @@
1
+ """BigQuery: the standard discovery, one dataset's `INFORMATION_SCHEMA` at a time.
2
+
3
+ Over `google.cloud.bigquery.dbapi` (`%s` parameters). BigQuery has no
4
+ current dataset a query can ask for, so the fetcher is given the project and
5
+ the default dataset unqualified names resolve in. Every view is read from
6
+ `project.dataset.INFORMATION_SCHEMA`; a name may be qualified by any project.
7
+
8
+ BigQuery has no `REFERENTIAL_CONSTRAINTS`: a foreign key's referenced table
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
11
+ enforced: they hold only under `trust_unenforced_keys` (`dialects.py`).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from collections.abc import Sequence
17
+ from typing import Any
18
+
19
+ from sqlassert.discovery.fetcher import DatabaseForeignKey, DatabaseRelationMetadata
20
+ from sqlassert.discovery.information_schema import (
21
+ Connection,
22
+ InformationSchemaKnowledgeFetcher,
23
+ foreign_keys_from_pairs,
24
+ placeholders,
25
+ quoted,
26
+ )
27
+
28
+
29
+ class BigQueryKnowledgeFetcher(InformationSchemaKnowledgeFetcher):
30
+ type_dialect = "bigquery"
31
+ cross_catalog = True
32
+
33
+ def __init__(self, connection: Connection, project: str, dataset: str | None = None):
34
+ super().__init__(connection)
35
+ self.project = project
36
+ self.dataset = dataset
37
+
38
+ def session(self, scope: DatabaseRelationMetadata | None) -> tuple[str, tuple[str, ...]]:
39
+ if scope is not None:
40
+ return scope.catalog, (scope.schema,)
41
+ return self.project, (self.dataset,) if self.dataset else ()
42
+
43
+ def information_schema(self, catalog: str, schema: str) -> str:
44
+ return f"{quoted(catalog, '`')}.{quoted(schema, '`')}.INFORMATION_SCHEMA"
45
+
46
+ def foreign_keys(self, catalog: str, schema: str, tables: Sequence[str]) -> list[tuple[str, DatabaseForeignKey]]:
47
+ where = self.information_schema(catalog, schema)
48
+ own_sql = (
49
+ "SELECT k.TABLE_NAME, k.CONSTRAINT_NAME, k.COLUMN_NAME "
50
+ f"FROM {where}.TABLE_CONSTRAINTS c JOIN {where}.KEY_COLUMN_USAGE k "
51
+ "ON k.CONSTRAINT_NAME = c.CONSTRAINT_NAME AND k.TABLE_NAME = c.TABLE_NAME "
52
+ f"WHERE c.CONSTRAINT_TYPE = 'FOREIGN KEY' AND c.TABLE_NAME IN ({placeholders(tables)}) "
53
+ "ORDER BY k.TABLE_NAME, k.CONSTRAINT_NAME, k.ORDINAL_POSITION"
54
+ )
55
+ own: dict[str, tuple[str, list[str]]] = {}
56
+ for table, constraint, column in self._rows(own_sql, tuple(tables)):
57
+ own.setdefault(constraint, (table, []))[1].append(column)
58
+ single = sorted(constraint for constraint, (_, members) in own.items() if len(members) == 1)
59
+ if not single:
60
+ return []
61
+ referenced_sql = (
62
+ "SELECT CONSTRAINT_NAME, TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME "
63
+ f"FROM {where}.CONSTRAINT_COLUMN_USAGE WHERE CONSTRAINT_NAME IN ({placeholders(single)})"
64
+ )
65
+ referenced: dict[str, list[tuple[Any, ...]]] = {}
66
+ for constraint, *target in self._rows(referenced_sql, tuple(single)):
67
+ referenced.setdefault(constraint, []).append(tuple(target))
68
+ return foreign_keys_from_pairs([
69
+ (own[constraint][0], constraint, own[constraint][1][0], *referenced[constraint][0])
70
+ for constraint in single if len(referenced.get(constraint, ())) == 1
71
+ ])
@@ -0,0 +1,18 @@
1
+ """Databricks (Unity Catalog): the standard discovery, over `databricks-sql-connector`.
2
+
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
5
+ foreign keys are informational: they hold only under
6
+ `trust_unenforced_keys` (`dialects.py`); the `RELY` a constraint may carry is
7
+ not read. Names qualified by another catalog are not looked up.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from sqlassert.discovery.information_schema import InformationSchemaKnowledgeFetcher
13
+
14
+
15
+ class DatabricksKnowledgeFetcher(InformationSchemaKnowledgeFetcher):
16
+ type_dialect = "databricks"
17
+ paramstyle = "qmark"
18
+ session_sql = "SELECT current_catalog(), current_schema()"
@@ -0,0 +1,159 @@
1
+ """DuckDB: the standard discovery, with DuckDB's `duckdb_*()` catalog functions.
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.
7
+
8
+ Queries run on the connection itself, not on a cursor: a DuckDB cursor is a
9
+ new session, without the connection's temporary tables, `USE` or
10
+ `search_path`, which decide what an unqualified name denotes.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from collections.abc import Sequence
16
+ from typing import Any, Protocol
17
+
18
+ import sqlglot
19
+ from sqlglot import exp
20
+ from sqlglot.errors import SqlglotError
21
+
22
+ from sqlassert.discovery.fetcher import (
23
+ DatabaseColumn,
24
+ DatabaseForeignKey,
25
+ DatabaseMetadataError,
26
+ DatabaseRelationKind,
27
+ DatabaseRelationMetadata,
28
+ )
29
+ from sqlassert.discovery.information_schema import FoundRelation, InformationSchemaKnowledgeFetcher, Key
30
+
31
+ _SESSION = "SELECT current_database(), current_schema(), current_setting('search_path')"
32
+
33
+ _RELATIONS = """
34
+ SELECT database_name, schema_name, table_name, 'table' FROM duckdb_tables()
35
+ WHERE lower(database_name) = %s AND lower(schema_name) = %s AND list_contains(%s, lower(table_name))
36
+ UNION ALL
37
+ SELECT database_name, schema_name, view_name, 'view' FROM duckdb_views()
38
+ WHERE NOT internal AND lower(database_name) = %s AND lower(schema_name) = %s AND list_contains(%s, lower(view_name))
39
+ """
40
+
41
+ _TABLES = "database_name = %s AND schema_name = %s AND list_contains(%s, table_name)"
42
+
43
+ _COLUMNS = f"""
44
+ SELECT table_name, column_name, is_nullable, data_type FROM duckdb_columns()
45
+ WHERE {_TABLES}
46
+ ORDER BY table_name, column_index
47
+ """
48
+
49
+ # duckdb_columns() drops a column's COLLATE; the stored CREATE TABLE keeps it.
50
+ _TABLE_SQL = f"SELECT table_name, sql FROM duckdb_tables() WHERE {_TABLES}"
51
+
52
+ # A foreign key's referenced table is in the referencing table's own catalog
53
+ # and schema: DuckDB rejects foreign keys across them.
54
+ _CONSTRAINTS = f"""
55
+ SELECT table_name, constraint_type, constraint_column_names, referenced_table, referenced_column_names
56
+ FROM duckdb_constraints()
57
+ WHERE constraint_type IN ({{kinds}}) AND {_TABLES}
58
+ ORDER BY table_name, constraint_index
59
+ """
60
+
61
+ _VIEW = "SELECT sql FROM duckdb_views() WHERE database_name = %s AND schema_name = %s AND view_name = %s"
62
+
63
+
64
+ class DuckDBConnection(Protocol):
65
+ def execute(self, query: str, parameters: Any = ..., /) -> Any: ...
66
+
67
+
68
+ class DuckDBKnowledgeFetcher(InformationSchemaKnowledgeFetcher):
69
+ type_dialect = "duckdb"
70
+ cross_catalog = True
71
+ _search_path: tuple[tuple[str, str], ...] = ()
72
+
73
+ def __init__(self, connection: DuckDBConnection):
74
+ self.database = connection
75
+
76
+ def session(self, scope: DatabaseRelationMetadata | None) -> tuple[str, tuple[str, ...]]:
77
+ """Where an unqualified name is looked up: a view's own schema first,
78
+ then temporary objects, then the session's path. DuckDB's path spans
79
+ catalogs, so `candidates` reads it from `_search_path`."""
80
+ (database, schema, configured), = self._rows(_SESSION)
81
+ path: list[tuple[str, str]] = [(scope.catalog, scope.schema)] if scope is not None else []
82
+ path.append(("temp", "main"))
83
+ for entry in filter(None, (entry.strip() for entry in configured.split(","))):
84
+ qualifier, _, name = entry.rpartition(".")
85
+ path.append((qualifier or database, name))
86
+ path.append((database, schema))
87
+ self._search_path = tuple((catalog.lower(), schema.lower()) for catalog, schema in path)
88
+ return database, tuple(schema for _, schema in self._search_path)
89
+
90
+ def candidates(self, name: str, catalog: str, path: tuple[str, ...]) -> list[tuple[str, str, str]]:
91
+ """Every catalog path ``name`` may denote, in DuckDB's binding order."""
92
+ match name.lower().split("."):
93
+ case [table]:
94
+ return [(searched, schema, table) for searched, schema in self._search_path]
95
+ case [qualifier, table]:
96
+ # A schema in a searched catalog first, then a catalog's default schema.
97
+ catalogs = dict.fromkeys(searched for searched, _ in self._search_path)
98
+ return [(searched, qualifier, table) for searched in catalogs] + [(qualifier, "main", table)]
99
+ case [named, schema, table]:
100
+ return [(named, schema, table)]
101
+ case _:
102
+ return []
103
+
104
+ def relations(self, catalog: str, schema: str, names: Sequence[str]) -> list[FoundRelation]:
105
+ lookup = (catalog.lower(), schema.lower(), list(names))
106
+ return [
107
+ FoundRelation(database, found_schema, name, DatabaseRelationKind(kind))
108
+ for database, found_schema, name, kind in self._rows(_RELATIONS, lookup * 2)
109
+ ]
110
+
111
+ def columns(self, catalog: str, schema: str, tables: Sequence[str]) -> list[tuple[str, DatabaseColumn]]:
112
+ lookup = (catalog, schema, list(tables))
113
+ collated = self._collated(catalog, schema, lookup)
114
+ return [
115
+ (table, DatabaseColumn(column, nullable, None if (table, column.lower()) in collated else data_type))
116
+ for table, column, nullable, data_type in self._rows(_COLUMNS, lookup)
117
+ ]
118
+
119
+ def keys(self, catalog: str, schema: str, tables: Sequence[str]) -> list[Key]:
120
+ return [
121
+ 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)))
123
+ ]
124
+
125
+ def foreign_keys(self, catalog: str, schema: str, tables: Sequence[str]) -> list[tuple[str, DatabaseForeignKey]]:
126
+ return [
127
+ (table, DatabaseForeignKey(tuple(members), f"{catalog}.{schema}.{referenced}", tuple(referenced_members)))
128
+ for table, _, members, referenced, referenced_members
129
+ in self._rows(_CONSTRAINTS.format(kinds="'FOREIGN KEY'"), (catalog, schema, list(tables)))
130
+ ]
131
+
132
+ def view_definition(self, relation: DatabaseRelationMetadata) -> str | None:
133
+ rows = self._rows(_VIEW, (relation.catalog, relation.schema, relation.name))
134
+ return rows[0][0] if rows else None
135
+
136
+ def _collated(self, catalog: str, schema: str, lookup: tuple[Any, ...]) -> set[tuple[str, str]]:
137
+ """Each (table, lowercase column) declared with a COLLATE: sqlassert
138
+ supports the default collation only, so such a column is untyped. The
139
+ session's `default_collation` is not read: text without a COLLATE has
140
+ the engine's shipped (binary) default (docs/dialects.md)."""
141
+ collated: set[tuple[str, str]] = set()
142
+ for table, sql in self._rows(_TABLE_SQL, lookup):
143
+ try:
144
+ create = sqlglot.parse_one(sql, read="duckdb")
145
+ except SqlglotError as error:
146
+ raise DatabaseMetadataError(f"definition of table {catalog}.{schema}.{table} could not be parsed: {error}") from error
147
+ collated.update(
148
+ (table, definition.name.lower()) for definition in create.find_all(exp.ColumnDef)
149
+ if any(isinstance(constraint.args.get("kind"), exp.CollateColumnConstraint) for constraint in definition.constraints)
150
+ )
151
+ return collated
152
+
153
+ def _rows(self, sql: str, parameters: tuple[Any, ...] = ()) -> list[tuple[Any, ...]]:
154
+ """The rows of one catalog query, run on the connection (see the module
155
+ docstring). Any driver error is a DatabaseMetadataError."""
156
+ try:
157
+ return [tuple(row) for row in self.database.execute(sql.replace("%s", "?"), list(parameters)).fetchall()]
158
+ except Exception as error:
159
+ raise DatabaseMetadataError(str(error)) from error