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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. sqlassert/__init__.py +1 -2
  2. sqlassert/check.py +88 -13
  3. sqlassert/diagnostics.py +17 -6
  4. sqlassert/dialects.py +437 -7
  5. sqlassert/discovery/bigquery.py +3 -1
  6. sqlassert/discovery/databricks.py +25 -2
  7. sqlassert/discovery/duckdb.py +49 -7
  8. sqlassert/discovery/fetcher.py +130 -21
  9. sqlassert/discovery/information_schema.py +30 -2
  10. sqlassert/discovery/mysql.py +22 -1
  11. sqlassert/discovery/postgres.py +22 -5
  12. sqlassert/discovery/redshift.py +3 -2
  13. sqlassert/discovery/snowflake.py +3 -0
  14. sqlassert/discovery/trino.py +2 -2
  15. sqlassert/hazards.py +248 -87
  16. sqlassert/ir/__init__.py +4 -1
  17. sqlassert/ir/convert/__init__.py +13 -0
  18. sqlassert/ir/convert/aggregation.py +439 -0
  19. sqlassert/ir/convert/builtins.py +140 -0
  20. sqlassert/ir/convert/expressions.py +572 -0
  21. sqlassert/ir/convert/joins.py +264 -0
  22. sqlassert/ir/convert/markers.py +249 -0
  23. sqlassert/ir/convert/parser.py +253 -0
  24. sqlassert/ir/convert/queries.py +259 -0
  25. sqlassert/ir/convert/schema.py +606 -0
  26. sqlassert/ir/convert/scopes.py +205 -0
  27. sqlassert/ir/convert/selects.py +337 -0
  28. sqlassert/ir/convert/shared.py +429 -0
  29. sqlassert/ir/convert/sources.py +432 -0
  30. sqlassert/ir/convert/subqueries.py +364 -0
  31. sqlassert/ir/convert/value_types.py +223 -0
  32. sqlassert/ir/convert/windows.py +275 -0
  33. sqlassert/ir/model.py +125 -47
  34. sqlassert/ir/names.py +63 -0
  35. sqlassert/properties.py +12 -1
  36. sqlassert/provenance.py +5 -1
  37. sqlassert/python_engine.py +104 -44
  38. sqlassert/reporting.py +33 -32
  39. sqlassert/rewrites.py +111 -61
  40. sqlassert/rules/STYLEGUIDE.md +3 -2
  41. sqlassert/rules/causes/__init__.py +41 -0
  42. sqlassert/rules/causes/coverage.py +113 -0
  43. sqlassert/rules/causes/domain.py +123 -0
  44. sqlassert/rules/causes/joins.py +73 -0
  45. sqlassert/rules/causes/nulls.py +154 -0
  46. sqlassert/rules/causes/unique.py +523 -0
  47. sqlassert/rules/domain.py +8 -7
  48. sqlassert/rules/equality.py +6 -147
  49. sqlassert/rules/exactly_one.py +2 -1
  50. sqlassert/rules/foreign_key.py +8 -9
  51. sqlassert/rules/join_cardinality.py +282 -41
  52. sqlassert/rules/nullability.py +5 -5
  53. sqlassert/rules/uniqueness.py +171 -47
  54. sqlassert/rules/value_typing.py +337 -0
  55. sqlassert/sql_parse.py +28 -1
  56. sqlassert/suggest.py +11 -15
  57. sqlassert-0.4.1.dist-info/METADATA +235 -0
  58. sqlassert-0.4.1.dist-info/RECORD +69 -0
  59. sqlassert/ir/convert.py +0 -3509
  60. sqlassert-0.3.3.dist-info/METADATA +0 -807
  61. sqlassert-0.3.3.dist-info/RECORD +0 -46
  62. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/WHEEL +0 -0
  63. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/entry_points.txt +0 -0
  64. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/licenses/LICENSE +0 -0
  65. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/top_level.txt +0 -0
sqlassert/dialects.py CHANGED
@@ -1,6 +1,10 @@
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
9
  which text compares by identity, what `||`, `concat()`, `greatest()` and
6
10
  subscripts do with NULL, and which constraints the database enforces. A dialect not listed gets
@@ -41,8 +45,9 @@ type GreatestMeaning = Literal["strict", "skips-null"] | None
41
45
 
42
46
  @dataclass(frozen=True)
43
47
  class DialectSemantics:
44
- # `+`, `-`, `*`, unary `-` and CAST raise an error on overflow or a bad
45
- # value rather than wrapping, saturating, or returning NULL.
48
+ # `+`, `-`, `*`, unary `-` and CAST of non-null values are never NULL: a
49
+ # bad value raises an error. Only NULL reasoning reads it: types and
50
+ # injectivity assume values stay in range in every dialect (ADR 0007).
46
51
  checked_arithmetic: bool = False
47
52
  # `/`, integer division and `%` by zero raise an error rather than return NULL.
48
53
  checked_division: bool = False
@@ -66,6 +71,15 @@ class DialectSemantics:
66
71
  # identical. Not where it keeps the zone it was given (Trino, Snowflake's
67
72
  # TIMESTAMP_TZ, Oracle): equal instants in two zones differ as text.
68
73
  zoned_timestamp_is_instant: bool = False
74
+ # Pairs `(T, U)`, as the engine names the types: comparing a T with a U,
75
+ # the engine casts the T to U, and that cast keeps different values
76
+ # different but changes each (a DATE becomes its midnight). Each side then
77
+ # fixes the other, though they are not equal (ADR 0009). A cast that keeps
78
+ # each value as it is (INT to BIGINT, TIMESTAMP(3) to TIMESTAMP(6)) is not
79
+ # listed: those sides are equal. Certified as `injective_cast(T->U)`: the
80
+ # date's midnight is equal to the U, and a later time that day is not
81
+ # (which an engine casting the U down to a DATE would match).
82
+ injective_casts: tuple[tuple[str, str], ...] = ()
69
83
  pipes: PipesMeaning = None
70
84
  concat: ConcatMeaning = None
71
85
  # What `concat_ws(sep, a, ...)` does with a NULL value (a NULL separator
@@ -74,6 +88,13 @@ class DialectSemantics:
74
88
  greatest: GreatestMeaning = None
75
89
  # `xs[i]` (an element of a list, array, map or struct) is NULL when `xs` is.
76
90
  subscript_strict: bool = False
91
+ # The column order of `*` over `a JOIN b USING (k, ...)`. "standard": the
92
+ # USING columns first in the USING list's order, then the left input's
93
+ # others, then the right's. "left_position": each USING column stays at its
94
+ # left input's position (DuckDB, SQLite: probed). "left_order": the USING
95
+ # columns first, but in the left input's column order (MySQL: probed).
96
+ # docs/dialects.md, "Stars and names".
97
+ using_star_order: Literal["standard", "left_position", "left_order"] = "standard"
77
98
  unique_keys: KeyTrust = "enforced"
78
99
  foreign_keys: KeyTrust = "enforced"
79
100
  # CHECK constraints. Where the dialect has none (Snowflake, BigQuery,
@@ -95,6 +116,67 @@ class DialectSemantics:
95
116
  # it is no soundness claim and is not certified: a wrong True suggests SQL
96
117
  # the engine rejects, never a wrong proof.
97
118
  set_operations_all: bool = False
119
+ # The type each function returns whatever its arguments' types, by the
120
+ # SQLGlot node it parses to: a select item that is such a call has that
121
+ # type, as a column declared with it would. Only where every argument type
122
+ # the engine accepts gives the same result type (`date_trunc` keeps its
123
+ # input's type, so it is not here). Certified with the engine's own type
124
+ # function (`scripts/certify_dialects.py`); a dialect without one claims none.
125
+ # A function SQLGlot parses as `Anonymous` is keyed `Anonymous:<lowercase name>`.
126
+ result_types: tuple[tuple[str, str], ...] = ()
127
+ # The type of a function whose result type follows one argument's, by the
128
+ # SQLGlot node, the argument's key in the node, and the result type for
129
+ # each argument type (`result_type(Node,ARGTYPE)=TYPE`), as the engine
130
+ # names them; `("*", "=")` makes any other argument type the result's
131
+ # (`result_type(Node,*)==`). An argument of a type not listed, or of
132
+ # unknown type, leaves the call untyped. Certified like `result_types`.
133
+ argument_result_types: tuple[tuple[str, str, tuple[tuple[str, str], ...]], ...] = ()
134
+ # Hash functions modelled as strict and total, by SQLGlot node: NULL
135
+ # exactly when the argument is. SQLGlot parses a hex-text hash as `MD5`,
136
+ # `SHA` (sha1) or `SHA2` and a raw-bytes one as `MD5Digest`, `SHA1Digest`
137
+ # or `SHA2Digest`, though ClickHouse's `SHA1`/`SHA256` (bytes) parse as
138
+ # `SHA`/`SHA2`. None is standard SQL, so each dialect claims its own.
139
+ # `sha2(x, n)` where `n` is free is NULL for an unsupported `n` in MySQL,
140
+ # Spark and Hive, so `SHA2` is claimed only where the length is fixed.
141
+ hash_functions: tuple[str, ...] = ()
142
+ # The type of a number literal that is not an integer, by kind, as the
143
+ # engine names the type (`literal_type(KIND)=TYPE`): "decimal", a literal
144
+ # written with a point (`0.1`), and "exponent", one written with an exponent
145
+ # (`1e0`). An exact type compares by value; a float rounds. A literal of a
146
+ # kind not listed has no type claimed, so it types and binds nothing.
147
+ # Certified with the engine's type function (`scripts/certify_dialects.py`),
148
+ # else cited, else a best guess from memory marked tentative (ADR 0007).
149
+ # An integer literal is an INT where it fits, else a BIGINT, in every dialect.
150
+ literal_types: tuple[tuple[str, str], ...] = ()
151
+ # The type a VALUES column has when every non-NULL value in it is a
152
+ # literal of one kind (NULL does not change it), by kind, as the engine
153
+ # names the type (`values_type(KIND)=TYPE`): "string"; "integer", each
154
+ # value within INTEGER's range; "bigint", each within BIGINT's and one
155
+ # beyond INTEGER's (the column has its widest row's type); "decimal", each
156
+ # written `d.f` with a whole part that does not start with 0, a type
157
+ # DECIMAL(p, s) of the widest whole part and scale. A kind not listed, a
158
+ # column of mixed kinds, of any other literal (a boolean, an exponent, a
159
+ # whole part 0, an integer beyond BIGINT) and of any expression stay untyped.
160
+ # A string type claims only that it is text: whether it compares by
161
+ # identity is `text_is_binary`, as for a declared column.
162
+ values_types: tuple[tuple[str, str], ...] = ()
163
+ # The columns, in order, that `SELECT * FROM f(...)` returns for a table
164
+ # function (or UNNEST, as `unnest`) of one argument list, by lower-case
165
+ # name (`table_function(NAME)=COLUMNS`): whatever its arguments, and
166
+ # whether or not the alias lists column names, which rename the leading
167
+ # columns. A function not listed, an UNNEST of several arguments or WITH
168
+ # ORDINALITY has columns not known without the data or the engine. So has
169
+ # one whose columns follow its argument's type: Spark's `explode` has `col`
170
+ # for an array and `key`, `value` for a map. An UNNEST of a list of
171
+ # structs is the one exception no entry can state: it is one column here
172
+ # (named by the alias), though BigQuery and Redshift spread the struct's
173
+ # fields over columns (docs/dialects.md).
174
+ table_functions: tuple[tuple[str, tuple[str, ...]], ...] = ()
175
+ # The one-column functions of `table_functions` whose column an alias with
176
+ # no column list names, as DuckDB does (`range(3) AS r` is the column `r`).
177
+ # Not one whose column the engine names itself (Spark's `range(3) AS r` is
178
+ # still `id`).
179
+ alias_named_table_functions: tuple[str, ...] = ()
98
180
 
99
181
  @property
100
182
  def rely(self) -> bool:
@@ -109,7 +191,11 @@ class DialectSemantics:
109
191
  _SPARK = DialectSemantics(
110
192
  checked_arithmetic=True,
111
193
  casts_raise=False,
194
+ text_is_binary=True, # UTF8_BINARY is the default collation.
112
195
  zoned_timestamp_is_instant=True,
196
+ # Tentative: a DATE beside a TIMESTAMP (an instant) is its midnight in
197
+ # the session zone, beside a TIMESTAMP_NTZ its midnight.
198
+ injective_casts=(("DATE", "TIMESTAMP"), ("DATE", "TIMESTAMP_NTZ")),
113
199
  pipes="strict",
114
200
  concat="strict",
115
201
  concat_ws="skips-null",
@@ -119,13 +205,44 @@ _SPARK = DialectSemantics(
119
205
  subscript_strict=True,
120
206
  unique_keys="rely",
121
207
  foreign_keys="rely",
122
- # Delta tables check them, other tables cannot declare them.
123
- check_constraints="unenforced",
208
+ # CHECKs are enforced (the default): only Delta tables declare one, and
209
+ # Delta rejects a write that violates it and checks existing rows before
210
+ # `ALTER TABLE ... ADD CONSTRAINT` adds one (docs/dialect-provenance.json).
124
211
  set_operations_all=True,
212
+ # Tentative. Not SHA2: `sha2(x, n)` is NULL for an unsupported `n`.
213
+ # Not `concat`, `||` or `reverse` of arrays (arrays), nor `datediff`
214
+ # (INT for two arguments, BIGINT for three).
215
+ result_types=(
216
+ ("MD5", "STRING"), ("SHA", "STRING"),
217
+ *((node, "STRING") for node in ("Lower", "Upper", "Trim", "Replace", "Left", "Right", "Substring", "Pad", "Repeat", "Initcap", "SplitPart", "Translate", "Overlay", "Chr", "ConcatWs", "RegexpReplace", "RegexpExtract", "RegexpSubstr", "Dayname", "Monthname", "TimeToStr", "ToChar",)),
218
+ *((node, "INT") for node in ("Length", "StrPosition", "Ascii", "BitLength", "Anonymous:octet_length", "Year", "Month", "Day", "Hour", "Minute", "Second", "Quarter", "DayOfWeek", "DayOfYear", "Week",)),
219
+ *((node, "BOOLEAN") for node in ("RegexpLike", "StartsWith", "EndsWith", "Contains",)),
220
+ *((node, "DOUBLE") for node in ("Ln", "Exp", "Sqrt", "Pow", "Log", "Sin", "Cos", "Tan", "Asin", "Acos", "Atan", "Atan2", "Sign",)),
221
+ *((node, "DATE") for node in ("LastDay", "DateTrunc",)),
222
+ *((node, "TIMESTAMP") for node in ("TimestampTrunc",)),
223
+ ),
224
+ argument_result_types=(
225
+ ("DPipe", "this", (("STRING", "STRING"),)),
226
+ ("Reverse", "this", (("STRING", "STRING"),)),
227
+ ("Abs", "this", (("*", "="),)),
228
+ ),
229
+ hash_functions=("MD5", "SHA"),
230
+ values_types=(("string", "string"), ("integer", "int"), ("bigint", "bigint"), ("decimal", "decimal")),
231
+ literal_types=(("decimal", "DECIMAL"), ("exponent", "DOUBLE")),
232
+ # Tentative. `range(n)` has the one column `id`, whatever its alias. Not
233
+ # `explode`, `posexplode` or `inline`: an array, a map or a struct gives
234
+ # different columns, and the SQL alone does not say which it reads.
235
+ table_functions=(("range", ("id",)),),
125
236
  )
126
237
 
238
+ # What `json_each` and `json_tree` return, in DuckDB and SQLite alike.
239
+ _JSON_TABLE_COLUMNS = ("key", "value", "type", "atom", "id", "parent", "fullkey", "path")
240
+
127
241
  _SEMANTICS: dict[str, DialectSemantics] = {
128
242
  "duckdb": DialectSemantics(
243
+ # A DATE compared with a TIMESTAMP is its midnight (probed); with a
244
+ # TIMESTAMP WITH TIME ZONE, its midnight in the session zone.
245
+ injective_casts=(("DATE", "TIMESTAMP"), ("DATE", "TIMESTAMP WITH TIME ZONE")),
129
246
  checked_arithmetic=True,
130
247
  checked_sum=True,
131
248
  text_is_binary=True,
@@ -135,9 +252,46 @@ _SEMANTICS: dict[str, DialectSemantics] = {
135
252
  concat_ws="skips-null",
136
253
  greatest="skips-null",
137
254
  subscript_strict=True,
255
+ using_star_order="left_position",
138
256
  set_operations_all=True,
257
+ result_types=(
258
+ *((node, "VARCHAR") for node in (
259
+ "MD5", "SHA", "SHA2", "Lower", "Upper", "Trim", "Replace", "Left", "Right", "Substring", "ConcatWs", "Dayname", "Monthname",
260
+ "Pad", "RegexpReplace", "Reverse", "SplitPart", "Translate", "Overlay", "Chr", "TimeToStr", "ArrayToString", "Format",
261
+ "Anonymous:nfc_normalize",
262
+ )),
263
+ *((node, "BIGINT") for node in (
264
+ "Length", "StrPosition", "Year", "Month", "Day", "Hour", "Minute", "Second", "Quarter", "Week", "DayOfWeek",
265
+ "DayOfYear", "DayOfWeekIso", "DateDiff", "BitLength", "Anonymous:octet_length", "Anonymous:strlen",
266
+ )),
267
+ *((node, "DOUBLE") for node in ("Ln", "Exp", "Sqrt", "Pow", "Log", "Sin", "Cos", "Tan", "Asin", "Acos", "Atan", "Atan2")),
268
+ *((node, "BOOLEAN") for node in (
269
+ "RegexpLike", "RegexpFullMatch", "StartsWith", "EndsWith", "Contains", "Anonymous:prefix", "Anonymous:suffix",
270
+ )),
271
+ ("Ascii", "INTEGER"), ("Sign", "TINYINT"), ("LastDay", "DATE"), ("DateFromParts", "DATE"),
272
+ ),
273
+ # Not `regexp_extract` (a STRUCT for a list of group names), `concat` or `repeat` of a list.
274
+ argument_result_types=(
275
+ ("TimestampTrunc", "this", (
276
+ *((source, "TIMESTAMP") for source in ("DATE", "TIMESTAMP", "TIMESTAMP_S", "TIMESTAMP_MS", "TIMESTAMP_NS")),
277
+ ("TIMESTAMP WITH TIME ZONE", "TIMESTAMP WITH TIME ZONE"), ("INTERVAL", "INTERVAL"),
278
+ )),
279
+ ("DPipe", "this", (("VARCHAR", "VARCHAR"),)),
280
+ ("Repeat", "this", (("VARCHAR", "VARCHAR"), ("BLOB", "BLOB"))),
281
+ ("Abs", "this", (("*", "="),)),
282
+ ),
283
+ hash_functions=("MD5", "SHA", "SHA2"),
284
+ values_types=(("string", "VARCHAR"), ("integer", "INTEGER"), ("bigint", "BIGINT"), ("decimal", "DECIMAL")),
285
+ literal_types=(("decimal", "DECIMAL"), ("exponent", "DOUBLE")),
286
+ table_functions=(
287
+ ("json_each", _JSON_TABLE_COLUMNS), ("json_tree", _JSON_TABLE_COLUMNS),
288
+ ("range", ("range",)), ("generate_series", ("generate_series",)), ("unnest", ("unnest",)),
289
+ ),
290
+ alias_named_table_functions=("range", "generate_series", "unnest"),
139
291
  ),
140
292
  "postgres": DialectSemantics(
293
+ # Tentative: date = timestamp(tz) compares the date's midnight.
294
+ injective_casts=(("date", "timestamp"), ("date", "timestamptz")),
141
295
  checked_arithmetic=True,
142
296
  checked_division=True,
143
297
  checked_sum=True,
@@ -150,8 +304,56 @@ _SEMANTICS: dict[str, DialectSemantics] = {
150
304
  greatest="skips-null",
151
305
  subscript_strict=True,
152
306
  set_operations_all=True,
307
+ # `sha256(x)` returns bytea: SHA2Digest. No Postgres SQL parses to SHA or SHA2.
308
+ # Tentative beyond the hashes (probed by hand on 18.6, not certified).
309
+ # No `year`, `last_day`, `datediff` or `dayname`: Postgres has none.
310
+ result_types=(
311
+ ("MD5", "TEXT"), ("SHA2Digest", "BYTEA"),
312
+ *((node, "TEXT") for node in ("Lower", "Upper", "Trim", "Replace", "Left", "Right", "Substring", "Pad", "Repeat", "Reverse", "Initcap", "SplitPart", "Translate", "Overlay", "Normalize", "Chr", "Concat", "ConcatWs", "Format", "ArrayToString", "RegexpReplace", "RegexpSubstr", "TimeToStr",)),
313
+ *((node, "INTEGER") for node in ("Length", "StrPosition", "BitLength", "Ascii", "Anonymous:octet_length",)),
314
+ *((node, "DOUBLE PRECISION") for node in ("Sin", "Cos", "Tan", "Asin", "Acos", "Atan", "Atan2",)),
315
+ *((node, "BOOLEAN") for node in ("RegexpLike", "StartsWith",)),
316
+ *((node, "DATE") for node in ("Anonymous:make_date",)),
317
+ ),
318
+ # `date_trunc` of a DATE is a TIMESTAMPTZ; `ln` and the like keep a NUMERIC.
319
+ argument_result_types=(
320
+ ("TimestampTrunc", "this", (("DATE", "TIMESTAMP WITH TIME ZONE"), ("TIMESTAMP", "TIMESTAMP"), ("TIMESTAMP WITH TIME ZONE", "TIMESTAMP WITH TIME ZONE"), ("INTERVAL", "INTERVAL"),)),
321
+ ("DPipe", "this", (("TEXT", "TEXT"), ("VARCHAR", "TEXT"),)),
322
+ ("Abs", "this", (("*", "="),)),
323
+ ("Ln", "this", (("SMALLINT", "DOUBLE PRECISION"), ("INTEGER", "DOUBLE PRECISION"), ("BIGINT", "DOUBLE PRECISION"), ("REAL", "DOUBLE PRECISION"), ("DOUBLE PRECISION", "DOUBLE PRECISION"), ("NUMERIC", "NUMERIC"),)),
324
+ ("Exp", "this", (("SMALLINT", "DOUBLE PRECISION"), ("INTEGER", "DOUBLE PRECISION"), ("BIGINT", "DOUBLE PRECISION"), ("REAL", "DOUBLE PRECISION"), ("DOUBLE PRECISION", "DOUBLE PRECISION"), ("NUMERIC", "NUMERIC"),)),
325
+ ("Sqrt", "this", (("SMALLINT", "DOUBLE PRECISION"), ("INTEGER", "DOUBLE PRECISION"), ("BIGINT", "DOUBLE PRECISION"), ("REAL", "DOUBLE PRECISION"), ("DOUBLE PRECISION", "DOUBLE PRECISION"), ("NUMERIC", "NUMERIC"),)),
326
+ ("Sign", "this", (("SMALLINT", "DOUBLE PRECISION"), ("INTEGER", "DOUBLE PRECISION"), ("BIGINT", "DOUBLE PRECISION"), ("REAL", "DOUBLE PRECISION"), ("DOUBLE PRECISION", "DOUBLE PRECISION"), ("NUMERIC", "NUMERIC"),)),
327
+ ),
328
+ hash_functions=("MD5", "SHA2Digest"),
329
+ # A numeric literal with a point is an unscaled NUMERIC: no decimal is claimed.
330
+ values_types=(("string", "text"), ("integer", "integer"), ("bigint", "bigint")),
331
+ # A numeric constant with a point or an exponent is a NUMERIC (an unscaled one).
332
+ literal_types=(("decimal", "numeric"), ("exponent", "numeric")),
333
+ # Certified on Postgres 18.6 (docs/dialect-provenance.json). A function returning a base
334
+ # type has one column, named by the function or, for an alias with no
335
+ # column list, by the alias (`alias_named_table_functions`); one with a
336
+ # single named OUT parameter has that name whatever the alias
337
+ # (`jsonb_array_elements(x) AS r` is `value`), and one with several is
338
+ # a record of them. Not an array of rows (`unnest` spreads its fields),
339
+ # not several arguments (`unnest(a, b)`), not `WITH ORDINALITY`.
340
+ table_functions=(
341
+ ("generate_series", ("generate_series",)), ("unnest", ("unnest",)),
342
+ ("regexp_split_to_table", ("regexp_split_to_table",)),
343
+ *((name, ("value",)) for name in (
344
+ "jsonb_array_elements", "json_array_elements", "jsonb_array_elements_text", "json_array_elements_text",
345
+ )),
346
+ *((name, ("key", "value")) for name in ("jsonb_each", "json_each", "jsonb_each_text", "json_each_text")),
347
+ ),
348
+ alias_named_table_functions=("generate_series", "unnest", "regexp_split_to_table"),
153
349
  ),
154
350
  "mysql": DialectSemantics(
351
+ # Tentative: a DATE beside a DATETIME is its midnight. Not TIMESTAMP:
352
+ # it is compared as a local DATETIME, and the fall-back hour gives two
353
+ # instants one local time.
354
+ injective_casts=(("DATE", "DATETIME"),),
355
+ # `*` over USING: the USING columns first, in the left input's order (probed, 8.4).
356
+ using_star_order="left_order",
155
357
  # MySQL under its default strict sql_mode only (docs/dialects.md), so
156
358
  # a comparison of non-null operands is non-null. Not `checked_arithmetic`:
157
359
  # `-x` of the least BIGINT is an exact DECIMAL rather than an error, and
@@ -170,38 +372,149 @@ _SEMANTICS: dict[str, DialectSemantics] = {
170
372
  foreign_key_engines=frozenset({"innodb", "ndb", "ndbcluster"}),
171
373
  enum_strips_trailing_spaces=True,
172
374
  set_operations_all=True, # Since 8.0.31.
375
+ # No type function to certify result types with. Not SHA2: its length is free.
376
+ hash_functions=("MD5", "SHA"),
377
+ # Tentative (probed by hand on 8.4, not certified). A text result
378
+ # carries its argument's length and collation, so only `regexp_replace`
379
+ # (always LONGTEXT) is claimed among them. `year()` is a YEAR.
380
+ result_types=(
381
+ *((node, "INT") for node in ("Length", "BitLength", "StrPosition", "Ascii", "Anonymous:octet_length", "Month", "Day", "Hour", "Minute", "Second", "Quarter", "Week", "DayOfWeek", "DayOfYear", "DateDiff", "RegexpLike",)),
382
+ *((node, "DOUBLE") for node in ("Ln", "Exp", "Sqrt", "Pow", "Log", "Sin", "Cos", "Tan", "Asin", "Acos", "Atan", "Atan2",)),
383
+ *((node, "BIGINT") for node in ("Sign",)),
384
+ *((node, "YEAR") for node in ("Year",)),
385
+ *((node, "DATE") for node in ("LastDay",)),
386
+ *((node, "LONGTEXT") for node in ("RegexpReplace",)),
387
+ ),
388
+ argument_result_types=(
389
+ ("Abs", "this", (("*", "="),)),
390
+ ),
391
+ # Every integer literal is a BIGINT. MySQL spells a row `ROW(...)`, which is not lowered.
392
+ values_types=(("string", "varchar"), ("integer", "bigint"), ("bigint", "bigint"), ("decimal", "decimal")),
393
+ literal_types=(("decimal", "DECIMAL"), ("exponent", "DOUBLE")),
173
394
  ),
174
395
  "snowflake": DialectSemantics(
396
+ # Tentative: a DATE beside a TIMESTAMP_NTZ (TIMESTAMP and DATETIME by
397
+ # default) is its midnight. Not TIMESTAMP_TZ: it keeps the zone.
398
+ injective_casts=(("DATE", "TIMESTAMP_NTZ"), ("DATE", "TIMESTAMP"), ("DATE", "DATETIME")),
175
399
  # Not `checked_arithmetic`: its docs never say integer overflow raises.
176
400
  checked_division=True,
401
+ text_is_binary=True, # With no COLLATE, text compares by its UTF-8 representation.
177
402
  pipes="strict",
178
403
  concat="strict",
179
404
  concat_ws="strict", # `concat_ws(',', 'a', NULL)` is NULL.
180
405
  unique_keys="rely",
181
406
  foreign_keys="rely",
182
407
  check_constraints="unenforced",
408
+ # Tentative (docs/dialect-provenance.json). `md5_binary` is MD5Digest.
409
+ # Tentative, from its docs. `ln` and the like are FLOAT but for a DECFLOAT.
410
+ result_types=(
411
+ ("MD5", "VARCHAR"), ("SHA", "VARCHAR"), ("MD5Digest", "BINARY"),
412
+ *((node, "VARCHAR") for node in ("Lower", "Upper", "Trim", "Replace", "Repeat", "Translate", "Initcap", "SplitPart", "RegexpReplace", "RegexpExtract", "Chr", "Dayname", "Monthname", "ToChar",)),
413
+ *((node, "NUMBER") for node in ("Length", "StrPosition", "Ascii", "Year", "Month", "Day", "DateDiff",)),
414
+ *((node, "FLOAT") for node in ("Ln", "Exp", "Sqrt", "Pow", "Log", "Sin", "Cos", "Tan", "Asin", "Acos", "Atan", "Atan2",)),
415
+ *((node, "BOOLEAN") for node in ("RegexpLike", "StartsWith", "EndsWith", "Contains",)),
416
+ *((node, "DATE") for node in ("LastDay",)),
417
+ ),
418
+ # VARCHAR or BINARY, as the argument is.
419
+ argument_result_types=(
420
+ ("Pad", "this", (("*", "="),)),
421
+ ("Substring", "this", (("*", "="),)),
422
+ ("Left", "this", (("*", "="),)),
423
+ ("Right", "this", (("*", "="),)),
424
+ ("Reverse", "this", (("*", "="),)),
425
+ ("TimestampTrunc", "this", (("*", "="),)),
426
+ ("Abs", "this", (("*", "="),)),
427
+ ("DPipe", "this", (("VARCHAR", "VARCHAR"),)),
428
+ ),
429
+ hash_functions=("MD5", "SHA", "MD5Digest"),
430
+ # `0.1` is a NUMBER(1,1) (tentative, from memory); the docs give `1e10` an exact NUMBER(11,0).
431
+ literal_types=(("decimal", "NUMBER"), ("exponent", "NUMBER")),
183
432
  ),
184
433
  "bigquery": DialectSemantics(
434
+ # Tentative: a DATE beside a DATETIME is its midnight.
435
+ injective_casts=(("DATE", "DATETIME"),),
185
436
  checked_arithmetic=True,
186
437
  checked_division=True,
187
438
  # Its docs: overflow raises, and NaN or an infinity makes NaN or an infinity.
188
439
  checked_sum=True,
440
+ text_is_binary=True, # With no collation specification, binary collation.
189
441
  zoned_timestamp_is_instant=True,
190
442
  pipes="strict",
191
443
  concat="strict",
192
444
  unique_keys="unenforced",
193
445
  foreign_keys="unenforced",
194
446
  check_constraints="unenforced",
447
+ # Tentative. `md5` and `sha256` return BYTES; `to_hex(md5(x))` parses as MD5.
448
+ # Tentative, from its docs. String functions return STRING or BYTES as
449
+ # their argument is; `floor` and the like of an INT64 are a FLOAT64.
450
+ result_types=(
451
+ ("MD5", "STRING"), ("MD5Digest", "BYTES"), ("SHA1Digest", "BYTES"), ("SHA2Digest", "BYTES"),
452
+ *((node, "INT64") for node in ("Length", "StrPosition", "Ascii", "DateDiff",)),
453
+ *((node, "STRING") for node in ("Chr", "Normalize", "Initcap", "TimeToStr",)),
454
+ *((node, "BOOL") for node in ("RegexpLike", "StartsWith", "EndsWith",)),
455
+ *((node, "FLOAT64") for node in ("Sin", "Cos", "Tan", "Asin", "Acos", "Atan", "Atan2",)),
456
+ *((node, "DATE") for node in ("LastDay",)),
457
+ ),
458
+ argument_result_types=(
459
+ ("Lower", "this", (("*", "="),)),
460
+ ("Upper", "this", (("*", "="),)),
461
+ ("Trim", "this", (("*", "="),)),
462
+ ("Pad", "this", (("*", "="),)),
463
+ ("Reverse", "this", (("*", "="),)),
464
+ ("Left", "this", (("*", "="),)),
465
+ ("Right", "this", (("*", "="),)),
466
+ ("Replace", "this", (("*", "="),)),
467
+ ("Substring", "this", (("*", "="),)),
468
+ ("RegexpReplace", "this", (("*", "="),)),
469
+ ("RegexpExtract", "this", (("*", "="),)),
470
+ ("DPipe", "this", (("*", "="),)),
471
+ ("Abs", "this", (("*", "="),)),
472
+ ("Sign", "this", (("*", "="),)),
473
+ ("DateTrunc", "this", (("*", "="),)),
474
+ ("Ln", "this", (("INT64", "FLOAT64"), ("FLOAT64", "FLOAT64"), ("NUMERIC", "NUMERIC"), ("BIGNUMERIC", "BIGNUMERIC"),)),
475
+ ("Exp", "this", (("INT64", "FLOAT64"), ("FLOAT64", "FLOAT64"), ("NUMERIC", "NUMERIC"), ("BIGNUMERIC", "BIGNUMERIC"),)),
476
+ ("Sqrt", "this", (("INT64", "FLOAT64"), ("FLOAT64", "FLOAT64"), ("NUMERIC", "NUMERIC"), ("BIGNUMERIC", "BIGNUMERIC"),)),
477
+ ),
478
+ hash_functions=("MD5", "MD5Digest", "SHA1Digest", "SHA2Digest"),
479
+ # A decimal is written `NUMERIC '0.1'`: `0.1` is a FLOAT64.
480
+ literal_types=(("decimal", "DOUBLE"), ("exponent", "DOUBLE")),
481
+ # Tentative. `UNNEST(xs) AS x` has the one column `x` (SQLGlot reads the alias as a column list).
482
+ table_functions=(("unnest", ("unnest",)),),
195
483
  ),
196
484
  "redshift": DialectSemantics(
485
+ # Tentative: a DATE beside a TIMESTAMP or TIMESTAMPTZ is its midnight.
486
+ injective_casts=(("DATE", "TIMESTAMP"), ("DATE", "TIMESTAMPTZ")),
197
487
  checked_arithmetic=True,
198
488
  checked_division=True,
199
489
  # Not `checked_sum`: its docs say nothing of a sum that overflows or meets NaN.
490
+ # Not `text_is_binary`: a comparison ignores trailing spaces, in VARCHAR too.
200
491
  zoned_timestamp_is_instant=True,
201
492
  pipes="strict",
202
493
  unique_keys="unenforced",
203
494
  foreign_keys="unenforced",
204
495
  check_constraints="unenforced",
496
+ # Tentative.
497
+ # Tentative, from its docs and memory. A CHAR argument may give a CHAR.
498
+ # `datediff` parses as TsOrDsDiff.
499
+ result_types=(
500
+ ("MD5", "VARCHAR"), ("SHA", "VARCHAR"),
501
+ *((node, "VARCHAR") for node in ("Lower", "Upper", "Trim", "Replace", "Left", "Right", "Substring", "Pad", "Repeat", "Reverse", "Initcap", "SplitPart", "RegexpReplace", "RegexpExtract", "Concat", "TimeToStr",)),
502
+ *((node, "INTEGER") for node in ("Length", "StrPosition", "Ascii", "Anonymous:octet_length",)),
503
+ *((node, "DOUBLE PRECISION") for node in ("Ln", "Exp", "Sqrt", "Pow", "Log", "Sin", "Cos", "Tan", "Asin", "Acos", "Atan", "Atan2",)),
504
+ *((node, "DATE") for node in ("LastDay",)),
505
+ *((node, "BIGINT") for node in ("TsOrDsDiff",)),
506
+ ),
507
+ argument_result_types=(
508
+ ("Abs", "this", (("*", "="),)),
509
+ ("Sign", "this", (("*", "="),)),
510
+ ("DPipe", "this", (("VARCHAR", "VARCHAR"),)),
511
+ ("TimestampTrunc", "this", (("DATE", "TIMESTAMP"), ("TIMESTAMP", "TIMESTAMP"), ("TIMESTAMP WITH TIME ZONE", "TIMESTAMP WITH TIME ZONE"),)),
512
+ ),
513
+ hash_functions=("MD5", "SHA"),
514
+ # Tentative, from memory: `0.1` is a NUMERIC as in PostgreSQL, `1e0` a DOUBLE PRECISION.
515
+ literal_types=(("decimal", "DECIMAL"), ("exponent", "DOUBLE")),
516
+ # Tentative. Unnesting a SUPER array, `FROM t, t.xs AS x`, has the one column `x` (SQLGlot reads it as an UNNEST).
517
+ table_functions=(("unnest", ("unnest",)),),
205
518
  ),
206
519
  "databricks": replace(
207
520
  _SPARK, checked_division=True, casts_raise=True,
@@ -210,22 +523,108 @@ _SEMANTICS: dict[str, DialectSemantics] = {
210
523
  ),
211
524
  "spark": _SPARK,
212
525
  "hive": DialectSemantics(casts_raise=False, pipes="strict", concat="strict", unique_keys="unenforced", foreign_keys="unenforced",
526
+ # Tentative: a DATE beside a TIMESTAMP is its midnight.
527
+ injective_casts=(("DATE", "TIMESTAMP"),),
213
528
  check_constraints="unenforced",
529
+ # Tentative. Not SHA2: `sha2(x, n)` is NULL for an unsupported `n`.
530
+ # Tentative, from its docs and memory. Not `concat` (BINARY of BINARY);
531
+ # `last_day` is a STRING.
532
+ result_types=(
533
+ ("MD5", "STRING"), ("SHA", "STRING"),
534
+ *((node, "STRING") for node in ("Lower", "Upper", "Trim", "Replace", "Substring", "Pad", "Repeat", "Reverse", "Initcap", "Translate", "Chr", "ConcatWs", "RegexpReplace", "RegexpExtract", "TimeToStr", "LastDay",)),
535
+ *((node, "INT") for node in ("Length", "StrPosition", "Ascii", "Year", "Month", "Day", "Hour", "Minute", "Second", "Quarter", "DateDiff",)),
536
+ *((node, "BOOLEAN") for node in ("RegexpLike",)),
537
+ *((node, "DOUBLE") for node in ("Ln", "Exp", "Sqrt", "Pow", "Log", "Sin", "Cos", "Tan", "Asin", "Acos", "Atan",)),
538
+ ),
539
+ argument_result_types=(
540
+ ("Abs", "this", (("*", "="),)),
541
+ ),
542
+ hash_functions=("MD5", "SHA"),
543
+ # A decimal literal is a DOUBLE unless it has a `BD` suffix.
544
+ literal_types=(("decimal", "DOUBLE"), ("exponent", "DOUBLE")),
214
545
  ),
546
+ # SQLite claims no function result type: a value's type is its own
547
+ # (storage class), not its expression's.
215
548
  "sqlite": DialectSemantics(
549
+ # No `injective_casts`: SQLite has no date or time type.
216
550
  pipes="strict",
217
551
  concat_ws="skips-null",
552
+ using_star_order="left_position",
218
553
  # Foreign keys are checked only under `PRAGMA foreign_keys = ON`, off by default.
219
554
  foreign_keys="unenforced",
220
555
  # Only an INTEGER PRIMARY KEY (the rowid) is never NULL.
221
556
  primary_key_not_null=False,
557
+ table_functions=(("json_each", _JSON_TABLE_COLUMNS), ("json_tree", _JSON_TABLE_COLUMNS)),
558
+ # A number with a point or an exponent is a REAL, a float.
559
+ literal_types=(("decimal", "real"), ("exponent", "real")),
222
560
  ),
223
561
  # 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),
562
+ # Its `MD5`/`SHA1`/`SHA256` return FixedString bytes, wrapped in Nullable
563
+ # for a Nullable argument: a type that follows the argument, so no result
564
+ # type is claimed.
565
+ "clickhouse": DialectSemantics(
566
+ # Tentative: a Date beside a DateTime or DateTime64 is its midnight.
567
+ injective_casts=(("Date", "DateTime"), ("Date", "DateTime64")),
568
+ concat_ws="strict", unique_keys="unenforced", foreign_keys="unenforced", hash_functions=("MD5Digest", "SHA", "SHA2"),
569
+ # Tentative (probed by hand on 26.10, not certified): of a Nullable or
570
+ # LowCardinality argument, the result is wrapped alike. Not `abs`
571
+ # (Int32 gives UInt32) or `date_trunc` (by the unit).
572
+ result_types=(
573
+ *((node, "UInt64") for node in ("Length", "StrPosition", "Anonymous:octet_length",)),
574
+ *((node, "String") for node in ("Lower", "Upper", "Trim", "Replace", "Left", "Right", "Substring", "Pad", "Repeat", "Reverse", "Initcap", "Translate", "Overlay", "Concat", "ConcatWs", "DPipe", "RegexpReplace", "RegexpExtract", "Monthname", "TimeToStr",)),
575
+ *((node, "UInt8") for node in ("RegexpLike", "Month", "Day",)),
576
+ *((node, "UInt16") for node in ("Year",)),
577
+ *((node, "Int32") for node in ("Ascii",)),
578
+ *((node, "Float64") for node in ("Ln", "Exp", "Sqrt", "Pow", "Log", "Sin", "Cos", "Tan", "Asin", "Acos", "Atan", "Atan2",)),
579
+ *((node, "Int8") for node in ("Sign",)),
580
+ *((node, "Date") for node in ("LastDay",)),
581
+ *((node, "Int64") for node in ("DateDiff",)),
582
+ ),
583
+ literal_types=(("decimal", "Float64"), ("exponent", "Float64")),
584
+ ),
585
+ "oracle": DialectSemantics(
586
+ # Tentative: a DATE beside a TIMESTAMP keeps its time of day. Not
587
+ # TIMESTAMP WITH TIME ZONE: it keeps the zone.
588
+ injective_casts=(("DATE", "TIMESTAMP"),),
589
+ empty_string_is_null=True,
590
+ # Tentative, from its docs and memory: text functions return VARCHAR2
591
+ # or CLOB as their argument is, math functions keep NUMBER or a binary float.
592
+ result_types=(
593
+ *((node, "NUMBER") for node in ("Length", "StrPosition", "Ascii", "Sign",)),
594
+ *((node, "VARCHAR2") for node in ("Chr", "ToChar",)),
595
+ *((node, "DATE") for node in ("LastDay", "DateTrunc",)),
596
+ ),
597
+ argument_result_types=(
598
+ ("Lower", "this", (("*", "="),)),
599
+ ("Upper", "this", (("*", "="),)),
600
+ ("Initcap", "this", (("*", "="),)),
601
+ ("Trim", "this", (("*", "="),)),
602
+ ("Pad", "this", (("*", "="),)),
603
+ ("Replace", "this", (("*", "="),)),
604
+ ("Substring", "this", (("*", "="),)),
605
+ ("Translate", "this", (("*", "="),)),
606
+ ("RegexpReplace", "this", (("*", "="),)),
607
+ ("RegexpSubstr", "this", (("*", "="),)),
608
+ ("Abs", "this", (("*", "="),)),
609
+ ("Ln", "this", (("*", "="),)),
610
+ ("Exp", "this", (("*", "="),)),
611
+ ("Sqrt", "this", (("*", "="),)),
612
+ ("Sin", "this", (("*", "="),)),
613
+ ("Cos", "this", (("*", "="),)),
614
+ ("Tan", "this", (("*", "="),)),
615
+ ("Asin", "this", (("*", "="),)),
616
+ ("Acos", "this", (("*", "="),)),
617
+ ("Atan", "this", (("*", "="),)),
618
+ ),
619
+ # A number literal without an `f` or `d` suffix is a NUMBER, point or exponent alike.
620
+ literal_types=(("decimal", "NUMBER"), ("exponent", "NUMBER")),
621
+ ),
226
622
  # Trino has no constraint but NOT NULL: its CREATE TABLE rejects a key, so
227
623
  # one in the SQL describes a table some other engine holds.
228
624
  "trino": DialectSemantics(
625
+ # Tentative: a DATE beside a TIMESTAMP(p) is its midnight. Not
626
+ # TIMESTAMP WITH TIME ZONE: it keeps the zone.
627
+ injective_casts=(("DATE", "TIMESTAMP"),),
229
628
  checked_arithmetic=True,
230
629
  checked_division=True,
231
630
  checked_sum=True,
@@ -245,6 +644,37 @@ _SEMANTICS: dict[str, DialectSemantics] = {
245
644
  foreign_keys="unenforced",
246
645
  check_constraints="unenforced",
247
646
  set_operations_all=True,
647
+ # `md5`/`sha1`/`sha256` take and return VARBINARY.
648
+ # Beyond the hashes, tentative (probed by hand on 484, not certified).
649
+ # A text result keeps its argument's length, so only those that lose it
650
+ # are fixed; `repeat` is an array function.
651
+ result_types=(
652
+ ("MD5Digest", "VARBINARY"), ("SHA", "VARBINARY"), ("SHA2Digest", "VARBINARY"),
653
+ *((node, "BIGINT") for node in ("Length", "StrPosition", "Year", "Month", "Day", "Hour", "Minute", "Second", "Quarter", "DayOfWeek", "DayOfYear", "DateDiff",)),
654
+ *((node, "VARCHAR") for node in ("Pad", "Translate", "Concat", "ConcatWs", "Normalize", "TimeToStr",)),
655
+ *((node, "BOOLEAN") for node in ("RegexpLike", "StartsWith",)),
656
+ *((node, "DOUBLE") for node in ("Ln", "Exp", "Sqrt", "Pow", "Log", "Sin", "Cos", "Tan", "Asin", "Acos", "Atan", "Atan2",)),
657
+ *((node, "DATE") for node in ("LastDay",)),
658
+ ),
659
+ argument_result_types=(
660
+ ("Abs", "this", (("*", "="),)),
661
+ ("TimestampTrunc", "this", (("*", "="),)),
662
+ ("Upper", "this", (("*", "="),)),
663
+ ("Lower", "this", (("*", "="),)),
664
+ ("Reverse", "this", (("*", "="),)),
665
+ ("DPipe", "this", (("VARCHAR", "VARCHAR"),)),
666
+ ),
667
+ hash_functions=("MD5Digest", "SHA", "SHA2Digest"),
668
+ # A string is `varchar(n)` for its longest value.
669
+ values_types=(("string", "varchar"), ("integer", "integer"), ("bigint", "bigint"), ("decimal", "decimal")),
670
+ literal_types=(("decimal", "DECIMAL"), ("exponent", "DOUBLE")),
671
+ # Certified on Trino 484 (docs/dialect-provenance.json). `UNNEST(xs) AS u(x)` of one
672
+ # array has the one column `x`: Trino requires a column list to name it
673
+ # (an unaliased column has no name), and rejects one of another length.
674
+ # Not an array of rows (one column per field), a map (`k`, `v`), several
675
+ # arguments, nor `WITH ORDINALITY`; an alias list longer than one name
676
+ # reads as one of those.
677
+ table_functions=(("unnest", ("unnest",)),),
248
678
  ),
249
679
  }
250
680
 
@@ -7,8 +7,10 @@ the default dataset unqualified names resolve in. Every view is read from
7
7
 
8
8
  BigQuery has no `REFERENTIAL_CONSTRAINTS`: a foreign key's referenced table
9
9
  and columns come from `CONSTRAINT_COLUMN_USAGE`, which does not order them,
10
- so a foreign key over more than one column is skipped. Keys are not
10
+ so a foreign key over more than one column is skipped. BigQuery has no
11
+ unique indexes (its search and vector indexes enforce nothing). Keys are not
11
12
  enforced: they hold only under `trust_unenforced_keys` (`dialects.py`).
13
+ BigQuery has no CHECK constraints, so none are read.
12
14
  """
13
15
 
14
16
  from __future__ import annotations