sqlassert 0.3.3__py3-none-any.whl → 0.4.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. sqlassert/__init__.py +1 -2
  2. sqlassert/check.py +88 -13
  3. sqlassert/declared_types.py +158 -0
  4. sqlassert/diagnostics.py +15 -7
  5. sqlassert/dialects.py +259 -107
  6. sqlassert/discovery/bigquery.py +4 -2
  7. sqlassert/discovery/databricks.py +26 -5
  8. sqlassert/discovery/duckdb.py +49 -7
  9. sqlassert/discovery/fetcher.py +137 -58
  10. sqlassert/discovery/information_schema.py +31 -6
  11. sqlassert/discovery/mysql.py +21 -4
  12. sqlassert/discovery/postgres.py +28 -20
  13. sqlassert/discovery/redshift.py +3 -2
  14. sqlassert/discovery/snowflake.py +5 -2
  15. sqlassert/discovery/trino.py +2 -2
  16. sqlassert/functions/__init__.py +10 -0
  17. sqlassert/functions/load.py +375 -0
  18. sqlassert/functions/table.py +2721 -0
  19. sqlassert/hazards.py +249 -88
  20. sqlassert/ir/__init__.py +15 -4
  21. sqlassert/ir/convert/__init__.py +13 -0
  22. sqlassert/ir/convert/aggregation.py +438 -0
  23. sqlassert/ir/convert/expressions.py +581 -0
  24. sqlassert/ir/convert/joins.py +264 -0
  25. sqlassert/ir/convert/markers.py +249 -0
  26. sqlassert/ir/convert/parser.py +249 -0
  27. sqlassert/ir/convert/queries.py +259 -0
  28. sqlassert/ir/convert/schema.py +537 -0
  29. sqlassert/ir/convert/scopes.py +205 -0
  30. sqlassert/ir/convert/selects.py +352 -0
  31. sqlassert/ir/convert/shared.py +428 -0
  32. sqlassert/ir/convert/sources.py +433 -0
  33. sqlassert/ir/convert/subqueries.py +364 -0
  34. sqlassert/ir/convert/value_types.py +78 -0
  35. sqlassert/ir/convert/windows.py +275 -0
  36. sqlassert/ir/model.py +417 -146
  37. sqlassert/ir/names.py +63 -0
  38. sqlassert/main.py +7 -10
  39. sqlassert/properties.py +12 -1
  40. sqlassert/provenance.py +5 -1
  41. sqlassert/python_engine.py +104 -44
  42. sqlassert/reporting.py +33 -32
  43. sqlassert/rewrites.py +111 -61
  44. sqlassert/rules/STYLEGUIDE.md +3 -2
  45. sqlassert/rules/causes/__init__.py +41 -0
  46. sqlassert/rules/causes/coverage.py +113 -0
  47. sqlassert/rules/causes/domain.py +123 -0
  48. sqlassert/rules/causes/joins.py +73 -0
  49. sqlassert/rules/causes/nulls.py +154 -0
  50. sqlassert/rules/causes/unique.py +564 -0
  51. sqlassert/rules/domain.py +9 -8
  52. sqlassert/rules/equality.py +6 -147
  53. sqlassert/rules/exactly_one.py +2 -1
  54. sqlassert/rules/foreign_key.py +8 -9
  55. sqlassert/rules/join_cardinality.py +277 -43
  56. sqlassert/rules/nullability.py +8 -8
  57. sqlassert/rules/uniqueness.py +212 -87
  58. sqlassert/rules/value_typing.py +470 -0
  59. sqlassert/sql_parse.py +28 -1
  60. sqlassert/suggest.py +13 -17
  61. sqlassert-0.4.2.dist-info/METADATA +239 -0
  62. sqlassert-0.4.2.dist-info/RECORD +72 -0
  63. sqlassert/ir/convert.py +0 -3509
  64. sqlassert-0.3.3.dist-info/METADATA +0 -807
  65. sqlassert-0.3.3.dist-info/RECORD +0 -46
  66. {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/WHEEL +0 -0
  67. {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/entry_points.txt +0 -0
  68. {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/licenses/LICENSE +0 -0
  69. {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/top_level.txt +0 -0
sqlassert/dialects.py CHANGED
@@ -1,15 +1,19 @@
1
1
  """What each SQL dialect means by the constructs the analysis depends on.
2
2
 
3
- One `DialectSemantics` per dialect name (SQLGlot's), read by `ir/convert.py`
3
+ Before editing, read docs/dialects.md, "Every engine at once": a fact added
4
+ for one engine is added for every engine where the construct exists, in the
5
+ same change, tentative (from memory) where it is neither probed nor read.
6
+
7
+ One `DialectSemantics` per dialect name (SQLGlot's), read by `ir/convert/`
4
8
  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
+ which text compares by identity. What each function does with NULL, and its
10
+ result type, is the function table's (`functions/table.py`). A dialect not
11
+ listed gets `DialectSemantics()`, whose arithmetic and collation are the
12
+ cautious choice. Whether a database enforces its declared constraints is not
13
+ modelled: every declared constraint is trusted (ADR 0012).
9
14
 
10
15
  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
16
+ settings, strict modes on (ADR 0006): Spark is modelled with ANSI mode on. `docs/dialects.md` argues each entry and says how soundness is judged
13
17
  without DuckDB; `docs/dialect-provenance.json` records, per fact, the engine
14
18
  versions it was certified on or the vendor doc it rests on
15
19
  (`scripts/certify_dialects.py`).
@@ -18,31 +22,20 @@ versions it was certified on or the vendor doc it rests on
18
22
  from __future__ import annotations
19
23
 
20
24
  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"]
25
+ from typing import TYPE_CHECKING, Literal
26
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
27
+ if TYPE_CHECKING:
28
+ from sqlassert.ir.model import CastKind, CastTarget, TypeFamily
31
29
 
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
30
+ # A modifier of a star (`DialectSemantics.star_modifiers`).
31
+ type StarModifier = Literal["except", "replace", "rename"]
40
32
 
41
33
 
42
34
  @dataclass(frozen=True)
43
35
  class DialectSemantics:
44
- # `+`, `-`, `*`, unary `-` and CAST raise an error on overflow or a bad
45
- # value rather than wrapping, saturating, or returning NULL.
36
+ # `+`, `-`, `*`, unary `-` and CAST of non-null values are never NULL: a
37
+ # bad value raises an error. Only NULL reasoning reads it: types and
38
+ # injectivity assume values stay in range in every dialect (ADR 0007).
46
39
  checked_arithmetic: bool = False
47
40
  # `/`, integer division and `%` by zero raise an error rather than return NULL.
48
41
  checked_division: bool = False
@@ -66,25 +59,48 @@ class DialectSemantics:
66
59
  # identical. Not where it keeps the zone it was given (Trino, Snowflake's
67
60
  # TIMESTAMP_TZ, Oracle): equal instants in two zones differ as text.
68
61
  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"
62
+ # The casts between type families that keep different values different,
63
+ # each `(source, target, kind)` (`ir.CastTable`, ADR 0011): "widening",
64
+ # values unchanged, or "injective", each value changed but different ones
65
+ # kept apart (a DATE becomes its midnight). A pair not listed is lossy.
66
+ # Within a family the rules are general (an integer into a wider one),
67
+ # except `("text", "sized text", "widening")`: a cast into a text type
68
+ # shorter than the value keeps it or raises, where it does not truncate.
69
+ # An explicit CAST asks the table, and so does a comparison of two types,
70
+ # for the side it casts (a DATE beside a TIMESTAMP, ADR 0009). Certified
71
+ # as `cast(T->U)=KIND`: as many distinct values after the cast as before,
72
+ # over values chosen to break it, and a DATE equal to its midnight but not
73
+ # to a later time that day (which an engine casting the timestamp down to
74
+ # a DATE would match).
75
+ casts: tuple[tuple[TypeFamily, CastTarget, CastKind], ...] = ()
76
+ # The column order of `*` over `a JOIN b USING (k, ...)`. "standard": the
77
+ # USING columns first in the USING list's order, then the left input's
78
+ # others, then the right's. "left_position": each USING column stays at its
79
+ # left input's position (DuckDB, SQLite: probed). "left_order": the USING
80
+ # columns first, but in the left input's column order (MySQL: probed).
81
+ # docs/dialects.md, "Stars and names".
82
+ using_star_order: Literal["standard", "left_position", "left_order"] = "standard"
83
+ # The modifiers a star (`*`, `t.*`) takes, each meaning what DuckDB's
84
+ # does: "except" (`* EXCEPT (c)`, DuckDB's and Snowflake's EXCLUDE) drops
85
+ # the named columns, "replace" (`* REPLACE (e AS c)`) puts the expression
86
+ # in its column's place under its name, "rename" (`* RENAME (c AS d)`)
87
+ # renames a column in place; every other column keeps its position. Each
88
+ # names a column of the star's own input, and a star whose modifiers name
89
+ # a column twice, or a name that is no single column, stays opaque, so the
90
+ # order engines apply them in (Snowflake: EXCLUDE, REPLACE, RENAME) and an
91
+ # unmatched name (an error, or ignored by ClickHouse) never matter. A
92
+ # modifier not listed (Snowflake's ILIKE, ClickHouse's APPLY and
93
+ # COLUMNS('re'), DuckDB's COLUMNS) leaves the select opaque, as does any
94
+ # modifier in PostgreSQL, MySQL, SQLite, Trino, Redshift, Hive and Oracle,
95
+ # which have none. Certified as `star_modifier(KIND)`. docs/dialects.md,
96
+ # "Stars and names".
97
+ star_modifiers: tuple[StarModifier, ...] = ()
98
+ # Identifiers are case-sensitive (ClickHouse). Only star modifiers read
99
+ # it: a name that matches a column only up to case is ignored there, not
100
+ # an error, so the modifier must spell its column exactly.
101
+ case_sensitive_names: bool = False
82
102
  # A PRIMARY KEY column is NOT NULL.
83
103
  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
104
  # An ENUM's members lose their trailing spaces (MySQL). An ENUM holds only
89
105
  # its members: MySQL's '' for any other value, outside strict mode or
90
106
  # under INSERT IGNORE, is out of scope (docs/dialects.md).
@@ -95,11 +111,68 @@ class DialectSemantics:
95
111
  # it is no soundness claim and is not certified: a wrong True suggests SQL
96
112
  # the engine rejects, never a wrong proof.
97
113
  set_operations_all: bool = False
114
+ # The type of a number literal that is not an integer, by kind, as the
115
+ # engine names the type (`literal_type(KIND)=TYPE`): "decimal", a literal
116
+ # written with a point (`0.1`), and "exponent", one written with an exponent
117
+ # (`1e0`). An exact type compares by value; a float rounds. A literal of a
118
+ # kind not listed has no type claimed, so it types and binds nothing.
119
+ # Certified with the engine's type function (`scripts/certify_dialects.py`),
120
+ # else cited, else a best guess from memory marked tentative (ADR 0007).
121
+ # An integer literal is an INT where it fits, else a BIGINT, in every dialect.
122
+ literal_types: tuple[tuple[str, str], ...] = ()
123
+ # The type a VALUES column has when every non-NULL value in it is a
124
+ # literal of one kind (NULL does not change it), by kind, as the engine
125
+ # names the type (`values_type(KIND)=TYPE`): "string"; "integer", each
126
+ # value within INTEGER's range; "bigint", each within BIGINT's and one
127
+ # beyond INTEGER's (the column has its widest row's type); "decimal", each
128
+ # written `d.f` with a whole part that does not start with 0, a type
129
+ # DECIMAL(p, s) of the widest whole part and scale. A kind not listed, a
130
+ # column of mixed kinds, of any other literal (a boolean, an exponent, a
131
+ # whole part 0, an integer beyond BIGINT) and of any expression stay untyped.
132
+ # A string type claims only that it is text: whether it compares by
133
+ # identity is `text_is_binary`, as for a declared column.
134
+ values_types: tuple[tuple[str, str], ...] = ()
135
+ # The columns, in order, that `SELECT * FROM f(...)` returns for a table
136
+ # function (or UNNEST, as `unnest`) of one argument list, by lower-case
137
+ # name (`table_function(NAME)=COLUMNS`): whatever its arguments, and
138
+ # whether or not the alias lists column names, which rename the leading
139
+ # columns. A function not listed, an UNNEST of several arguments or WITH
140
+ # ORDINALITY has columns not known without the data or the engine. So has
141
+ # one whose columns follow its argument's type: Spark's `explode` has `col`
142
+ # for an array and `key`, `value` for a map. An UNNEST of a list of
143
+ # structs is the one exception no entry can state: it is one column here
144
+ # (named by the alias), though BigQuery and Redshift spread the struct's
145
+ # fields over columns (docs/dialects.md).
146
+ table_functions: tuple[tuple[str, tuple[str, ...]], ...] = ()
147
+ # The one-column functions of `table_functions` whose column an alias with
148
+ # no column list names, as DuckDB does (`range(3) AS r` is the column `r`).
149
+ # Not one whose column the engine names itself (Spark's `range(3) AS r` is
150
+ # still `id`).
151
+ alias_named_table_functions: tuple[str, ...] = ()
152
+
98
153
 
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)
154
+ # The casts every engine keeps apart, by type family (`DialectSemantics.casts`):
155
+ # an integer or decimal written as text in its one canonical form (a decimal
156
+ # at its declared scale or without trailing zeros, either way one text per
157
+ # value), a boolean as 1 and 0 or as text, a date, time or timestamp as ISO
158
+ # text with every fraction of a second it has, a DATE as its midnight in a
159
+ # timestamp with no zone. Each dialect states its own; tentative where unprobed.
160
+ _CASTS: tuple[tuple[TypeFamily, CastTarget, CastKind], ...] = (
161
+ ("integer", "text", "injective"),
162
+ ("decimal", "text", "injective"),
163
+ ("boolean", "integer", "injective"),
164
+ ("boolean", "text", "injective"),
165
+ ("date", "text", "injective"),
166
+ ("time", "text", "injective"),
167
+ ("timestamp", "text", "injective"),
168
+ ("date", "timestamp", "injective"),
169
+ )
170
+ # A DATE as its midnight in the session zone: two dates are two instants in every zone.
171
+ _DATE_TO_INSTANT: tuple[TypeFamily, CastTarget, CastKind] = ("date", "timestamptz", "injective")
172
+ # A UUID as its canonical lower-case hyphenated text.
173
+ _UUID_TO_TEXT: tuple[TypeFamily, CastTarget, CastKind] = ("uuid", "text", "injective")
174
+ # A cast into text shorter than the value raises (or ignores the length) rather than truncate.
175
+ _SIZED_TEXT_KEEPS: tuple[TypeFamily, CastTarget, CastKind] = ("text", "sized text", "widening")
103
176
 
104
177
 
105
178
  # Spark 4 and Databricks under ANSI mode, their default (ADR 0006): overflow
@@ -109,49 +182,90 @@ class DialectSemantics:
109
182
  _SPARK = DialectSemantics(
110
183
  checked_arithmetic=True,
111
184
  casts_raise=False,
185
+ text_is_binary=True, # UTF8_BINARY is the default collation.
112
186
  zoned_timestamp_is_instant=True,
113
- pipes="strict",
114
- concat="strict",
115
- concat_ws="skips-null",
187
+ # Tentative: a DATE beside a TIMESTAMP (an instant) is its midnight in
188
+ # the session zone, beside a TIMESTAMP_NTZ its midnight. A cast into
189
+ # VARCHAR(n) is not claimed to keep the text.
190
+ casts=(*_CASTS, _DATE_TO_INSTANT),
116
191
  # Certified on Spark 4.3, not Databricks (`databricks` below drops them).
117
192
  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
193
  set_operations_all=True,
194
+ values_types=(("string", "string"), ("integer", "int"), ("bigint", "bigint"), ("decimal", "decimal")),
195
+ literal_types=(("decimal", "DECIMAL"), ("exponent", "DOUBLE")),
196
+ # `* EXCEPT (c)`, and `* EXCEPT (s.f)` drops the field f of a struct s
197
+ # (probed by hand on Spark 4.3); no REPLACE or RENAME.
198
+ star_modifiers=("except",),
199
+ # Tentative. `range(n)` has the one column `id`, whatever its alias. Not
200
+ # `explode`, `posexplode` or `inline`: an array, a map or a struct gives
201
+ # different columns, and the SQL alone does not say which it reads.
202
+ table_functions=(("range", ("id",)),),
125
203
  )
126
204
 
205
+ # What `json_each` and `json_tree` return, in DuckDB and SQLite alike.
206
+ _JSON_TABLE_COLUMNS = ("key", "value", "type", "atom", "id", "parent", "fullkey", "path")
207
+
127
208
  _SEMANTICS: dict[str, DialectSemantics] = {
128
209
  "duckdb": DialectSemantics(
210
+ # A DATE compared with a TIMESTAMP is its midnight; with a TIMESTAMP
211
+ # WITH TIME ZONE, its midnight in the session zone. VARCHAR(n) ignores
212
+ # its length.
213
+ casts=(*_CASTS, _DATE_TO_INSTANT, _UUID_TO_TEXT, _SIZED_TEXT_KEEPS),
129
214
  checked_arithmetic=True,
130
215
  checked_sum=True,
131
216
  text_is_binary=True,
132
217
  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,
218
+ using_star_order="left_position",
138
219
  set_operations_all=True,
220
+ star_modifiers=("except", "replace", "rename"),
221
+ values_types=(("string", "VARCHAR"), ("integer", "INTEGER"), ("bigint", "BIGINT"), ("decimal", "DECIMAL")),
222
+ literal_types=(("decimal", "DECIMAL"), ("exponent", "DOUBLE")),
223
+ table_functions=(
224
+ ("json_each", _JSON_TABLE_COLUMNS), ("json_tree", _JSON_TABLE_COLUMNS),
225
+ ("range", ("range",)), ("generate_series", ("generate_series",)), ("unnest", ("unnest",)),
226
+ ),
227
+ alias_named_table_functions=("range", "generate_series", "unnest"),
139
228
  ),
140
229
  "postgres": DialectSemantics(
230
+ # Tentative: date = timestamp(tz) compares the date's midnight. A cast
231
+ # into varchar(n) truncates silently, so it is not listed.
232
+ casts=(*_CASTS, _DATE_TO_INSTANT, _UUID_TO_TEXT),
141
233
  checked_arithmetic=True,
142
234
  checked_division=True,
143
235
  checked_sum=True,
144
236
  text_is_binary=True,
145
237
  unscaled_decimal=True,
146
238
  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
239
  set_operations_all=True,
240
+ # A numeric literal with a point is an unscaled NUMERIC: no decimal is claimed.
241
+ values_types=(("string", "text"), ("integer", "integer"), ("bigint", "bigint")),
242
+ # A numeric constant with a point or an exponent is a NUMERIC (an unscaled one).
243
+ literal_types=(("decimal", "numeric"), ("exponent", "numeric")),
244
+ # Certified on Postgres 18.6 (docs/dialect-provenance.json). A function returning a base
245
+ # type has one column, named by the function or, for an alias with no
246
+ # column list, by the alias (`alias_named_table_functions`); one with a
247
+ # single named OUT parameter has that name whatever the alias
248
+ # (`jsonb_array_elements(x) AS r` is `value`), and one with several is
249
+ # a record of them. Not an array of rows (`unnest` spreads its fields),
250
+ # not several arguments (`unnest(a, b)`), not `WITH ORDINALITY`.
251
+ table_functions=(
252
+ ("generate_series", ("generate_series",)), ("unnest", ("unnest",)),
253
+ ("regexp_split_to_table", ("regexp_split_to_table",)),
254
+ *((name, ("value",)) for name in (
255
+ "jsonb_array_elements", "json_array_elements", "jsonb_array_elements_text", "json_array_elements_text",
256
+ )),
257
+ *((name, ("key", "value")) for name in ("jsonb_each", "json_each", "jsonb_each_text", "json_each_text")),
258
+ ),
259
+ alias_named_table_functions=("generate_series", "unnest", "regexp_split_to_table"),
153
260
  ),
154
261
  "mysql": DialectSemantics(
262
+ # Tentative: a DATE beside a DATETIME is its midnight. Not TIMESTAMP:
263
+ # it is compared as a local DATETIME, and the fall-back hour gives two
264
+ # instants one local time. A CAST to text is a CHAR, compared ignoring
265
+ # case, so its entries never make a key.
266
+ casts=_CASTS,
267
+ # `*` over USING: the USING columns first, in the left input's order (probed, 8.4).
268
+ using_star_order="left_order",
155
269
  # MySQL under its default strict sql_mode only (docs/dialects.md), so
156
270
  # a comparison of non-null operands is non-null. Not `checked_arithmetic`:
157
271
  # `-x` of the least BIGINT is an exact DECIMAL rather than an error, and
@@ -162,70 +276,109 @@ _SEMANTICS: dict[str, DialectSemantics] = {
162
276
  # Not `text_is_binary`: the default collations ignore case (and
163
277
  # accents, and some trailing spaces).
164
278
  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
279
  enum_strips_trailing_spaces=True,
172
280
  set_operations_all=True, # Since 8.0.31.
281
+ # Every integer literal is a BIGINT. MySQL spells a row `ROW(...)`, which is not lowered.
282
+ values_types=(("string", "varchar"), ("integer", "bigint"), ("bigint", "bigint"), ("decimal", "decimal")),
283
+ literal_types=(("decimal", "DECIMAL"), ("exponent", "DOUBLE")),
173
284
  ),
174
285
  "snowflake": DialectSemantics(
286
+ # Tentative (docs/dialect-provenance.json); ILIKE is opaque.
287
+ star_modifiers=("except", "replace", "rename"),
288
+ # Tentative: a DATE beside a TIMESTAMP_NTZ (TIMESTAMP and DATETIME by
289
+ # default) is its midnight. Not TIMESTAMP_TZ: it keeps the zone. Not a
290
+ # time or timestamp as text: the default output formats drop digits
291
+ # (`HH24:MI:SS`, `.FF3`). A cast into VARCHAR(n) raises for a longer value.
292
+ casts=(*(entry for entry in _CASTS if entry[0] not in ("time", "timestamp")), _SIZED_TEXT_KEEPS),
175
293
  # Not `checked_arithmetic`: its docs never say integer overflow raises.
176
294
  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",
295
+ text_is_binary=True, # With no COLLATE, text compares by its UTF-8 representation.
296
+ # VARCHAR or BINARY, as the argument is.
297
+ # `0.1` is a NUMBER(1,1) (tentative, from memory); the docs give `1e10` an exact NUMBER(11,0).
298
+ literal_types=(("decimal", "NUMBER"), ("exponent", "NUMBER")),
183
299
  ),
184
300
  "bigquery": DialectSemantics(
301
+ star_modifiers=("except", "replace"), # Tentative.
302
+ # Tentative: a DATE beside a DATETIME is its midnight. A cast into
303
+ # STRING(n) raises for a longer value.
304
+ casts=(*_CASTS, _SIZED_TEXT_KEEPS),
185
305
  checked_arithmetic=True,
186
306
  checked_division=True,
187
307
  # Its docs: overflow raises, and NaN or an infinity makes NaN or an infinity.
188
308
  checked_sum=True,
309
+ text_is_binary=True, # With no collation specification, binary collation.
189
310
  zoned_timestamp_is_instant=True,
190
- pipes="strict",
191
- concat="strict",
192
- unique_keys="unenforced",
193
- foreign_keys="unenforced",
194
- check_constraints="unenforced",
311
+ # A decimal is written `NUMERIC '0.1'`: `0.1` is a FLOAT64.
312
+ literal_types=(("decimal", "DOUBLE"), ("exponent", "DOUBLE")),
313
+ # Tentative. `UNNEST(xs) AS x` has the one column `x` (SQLGlot reads the alias as a column list).
314
+ table_functions=(("unnest", ("unnest",)),),
195
315
  ),
196
316
  "redshift": DialectSemantics(
317
+ # Tentative: a DATE beside a TIMESTAMP or TIMESTAMPTZ is its midnight.
318
+ # A cast into VARCHAR(n) truncates.
319
+ casts=(*_CASTS, _DATE_TO_INSTANT),
197
320
  checked_arithmetic=True,
198
321
  checked_division=True,
199
322
  # Not `checked_sum`: its docs say nothing of a sum that overflows or meets NaN.
323
+ # Not `text_is_binary`: a comparison ignores trailing spaces, in VARCHAR too.
200
324
  zoned_timestamp_is_instant=True,
201
- pipes="strict",
202
- unique_keys="unenforced",
203
- foreign_keys="unenforced",
204
- check_constraints="unenforced",
325
+ # Tentative, from memory: `0.1` is a NUMERIC as in PostgreSQL, `1e0` a DOUBLE PRECISION.
326
+ literal_types=(("decimal", "DECIMAL"), ("exponent", "DOUBLE")),
327
+ # Tentative. Unnesting a SUPER array, `FROM t, t.xs AS x`, has the one column `x` (SQLGlot reads it as an UNNEST).
328
+ table_functions=(("unnest", ("unnest",)),),
205
329
  ),
206
330
  "databricks": replace(
207
331
  _SPARK, checked_division=True, casts_raise=True,
208
332
  # 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,
333
+ checked_sum=False,
210
334
  ),
211
335
  "spark": _SPARK,
212
- "hive": DialectSemantics(casts_raise=False, pipes="strict", concat="strict", unique_keys="unenforced", foreign_keys="unenforced",
213
- check_constraints="unenforced",
336
+ "hive": DialectSemantics(casts_raise=False,
337
+ # Tentative: a DATE beside a TIMESTAMP is its midnight. A cast into
338
+ # VARCHAR(n) truncates.
339
+ casts=_CASTS,
340
+ # A decimal literal is a DOUBLE unless it has a `BD` suffix.
341
+ literal_types=(("decimal", "DOUBLE"), ("exponent", "DOUBLE")),
214
342
  ),
215
343
  "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",
344
+ # No `casts`: SQLite has no date or time type, and a column's declared
345
+ # type does not bound the storage classes of its values.
346
+ using_star_order="left_position",
220
347
  # Only an INTEGER PRIMARY KEY (the rowid) is never NULL.
221
348
  primary_key_not_null=False,
349
+ table_functions=(("json_each", _JSON_TABLE_COLUMNS), ("json_tree", _JSON_TABLE_COLUMNS)),
350
+ # A number with a point or an exponent is a REAL, a float.
351
+ literal_types=(("decimal", "real"), ("exponent", "real")),
222
352
  ),
223
353
  # 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),
354
+ "clickhouse": DialectSemantics(
355
+ # EXCEPT and REPLACE without STRICT ignore a name no column has
356
+ # (probed); APPLY and COLUMNS('re') are opaque.
357
+ star_modifiers=("except", "replace"),
358
+ case_sensitive_names=True,
359
+ # Tentative: a Date beside a DateTime or DateTime64 is its midnight. Not a
360
+ # Time as text: a Time with a fraction of a second is no Time value
361
+ # (probed on 26.10: casting '10:00:00.001' to it fails).
362
+ casts=(*(entry for entry in _CASTS if entry[:2] != ("time", "text")), _UUID_TO_TEXT),
363
+ literal_types=(("decimal", "Float64"), ("exponent", "Float64")),
364
+ ),
365
+ "oracle": DialectSemantics(
366
+ # Tentative: a DATE beside a TIMESTAMP keeps its time of day. Not
367
+ # TIMESTAMP WITH TIME ZONE: it keeps the zone. Not a date, time or
368
+ # timestamp as text: the default NLS formats drop the time of day and
369
+ # two digits of the year.
370
+ casts=tuple(entry for entry in _CASTS if entry[0] not in ("date", "time", "timestamp") or entry[1] != "text"),
371
+ empty_string_is_null=True,
372
+ # A number literal without an `f` or `d` suffix is a NUMBER, point or exponent alike.
373
+ literal_types=(("decimal", "NUMBER"), ("exponent", "NUMBER")),
374
+ ),
226
375
  # Trino has no constraint but NOT NULL: its CREATE TABLE rejects a key, so
227
376
  # one in the SQL describes a table some other engine holds.
228
377
  "trino": DialectSemantics(
378
+ # Tentative: a DATE beside a TIMESTAMP(p) is its midnight. Not
379
+ # TIMESTAMP WITH TIME ZONE: it keeps the zone. A cast into varchar(n)
380
+ # truncates.
381
+ casts=(*_CASTS, _UUID_TO_TEXT),
229
382
  checked_arithmetic=True,
230
383
  checked_division=True,
231
384
  checked_sum=True,
@@ -233,18 +386,17 @@ _SEMANTICS: dict[str, DialectSemantics] = {
233
386
  text_is_binary=True,
234
387
  # Not `zoned_timestamp_is_instant`: a TIMESTAMP WITH TIME ZONE keeps
235
388
  # 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
389
  set_operations_all=True,
390
+ # A string is `varchar(n)` for its longest value.
391
+ values_types=(("string", "varchar"), ("integer", "integer"), ("bigint", "bigint"), ("decimal", "decimal")),
392
+ literal_types=(("decimal", "DECIMAL"), ("exponent", "DOUBLE")),
393
+ # Certified on Trino 484 (docs/dialect-provenance.json). `UNNEST(xs) AS u(x)` of one
394
+ # array has the one column `x`: Trino requires a column list to name it
395
+ # (an unaliased column has no name), and rejects one of another length.
396
+ # Not an array of rows (one column per field), a map (`k`, `v`), several
397
+ # arguments, nor `WITH ORDINALITY`; an alias list longer than one name
398
+ # reads as one of those.
399
+ table_functions=(("unnest", ("unnest",)),),
248
400
  ),
249
401
  }
250
402
 
@@ -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
11
- enforced: they hold only under `trust_unenforced_keys` (`dialects.py`).
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). Its keys
12
+ are not enforced, yet trusted like every declared constraint (ADR 0012).
13
+ BigQuery has no CHECK constraints, so none are read.
12
14
  """
13
15
 
14
16
  from __future__ import annotations
@@ -1,18 +1,39 @@
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
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.
4
+ only the session query and the parameter style (`?`) differ. Databricks has
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.
8
+
9
+ Unity Catalog's `CHECK_CONSTRAINTS` view
10
+ is empty (reserved), so they are read from each table's properties, where
11
+ Delta keeps each as `delta.constraints.<name>`. Unprobed: written from the
12
+ Databricks documentation, not run against a workspace.
8
13
  """
9
14
 
10
15
  from __future__ import annotations
11
16
 
12
- from sqlassert.discovery.information_schema import InformationSchemaKnowledgeFetcher
17
+ from collections.abc import Sequence
18
+
19
+ from sqlassert.discovery.fetcher import DatabaseMetadataError
20
+ from sqlassert.discovery.information_schema import InformationSchemaKnowledgeFetcher, quoted
21
+
22
+ _CHECK_PROPERTY = "delta.constraints."
13
23
 
14
24
 
15
25
  class DatabricksKnowledgeFetcher(InformationSchemaKnowledgeFetcher):
16
26
  type_dialect = "databricks"
17
27
  paramstyle = "qmark"
18
28
  session_sql = "SELECT current_catalog(), current_schema()"
29
+
30
+ def checks(self, catalog: str, schema: str, tables: Sequence[str]) -> list[tuple[str, str]]:
31
+ found: list[tuple[str, str]] = []
32
+ for table in tables:
33
+ name = ".".join(quoted(part, "`") for part in (catalog, schema, table))
34
+ try:
35
+ properties = self._rows(f"SHOW TBLPROPERTIES {name}")
36
+ except DatabaseMetadataError:
37
+ continue # A table whose properties cannot be read keeps its other facts, without CHECKs.
38
+ found.extend((table, value) for key, value in properties if key.lower().startswith(_CHECK_PROPERTY))
39
+ 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."""