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/ir/model.py CHANGED
@@ -6,7 +6,9 @@ nodes and carry no identifiers.
6
6
 
7
7
  from __future__ import annotations
8
8
 
9
+ from collections.abc import Callable, Sequence
9
10
  from dataclasses import dataclass, field, fields
11
+ from functools import cached_property
10
12
  from enum import Enum
11
13
  from typing import TYPE_CHECKING, Literal, assert_never, cast, dataclass_transform
12
14
 
@@ -21,13 +23,19 @@ type SetOperator = Literal["union", "intersect", "except"]
21
23
 
22
24
  @dataclass_transform(eq_default=False, frozen_default=True, kw_only_default=True)
23
25
  class NodeMeta(type):
24
- """Turn every Node subclass into the same kind of semantic value."""
26
+ """Turn every Node subclass into the same kind of semantic value.
27
+
28
+ A node is the occurrence it stands for, so it equals only itself: two
29
+ Aliases of one table, or two Output Columns named alike, are different
30
+ nodes. A metaclass with `value_equality` makes its classes compare by
31
+ class and fields instead (ADR 0002)."""
25
32
 
26
33
  _subclasses: list
34
+ value_equality = False
27
35
 
28
36
  def __new__(metaclass, name, bases, namespace, *, abstract: bool = False):
29
37
  node_type = super().__new__(metaclass, name, bases, namespace)
30
- node_type = dataclass(frozen=True, eq=False, kw_only=True)(node_type)
38
+ node_type = dataclass(frozen=True, eq=metaclass.value_equality, kw_only=True)(node_type)
31
39
  node_type.__ir_abstract__ = abstract
32
40
  node_type._subclasses = []
33
41
  if not abstract:
@@ -61,26 +69,79 @@ class ScalarExpr(Node, abstract=True):
61
69
  class OpaqueExpression(ScalarExpr):
62
70
  """An expression nothing is known about: not even which columns its value
63
71
  depends on. A user-defined or volatile function, an aggregate or window,
64
- a subquery, or a column that does not resolve."""
72
+ a subquery, or a column that does not resolve.
73
+
74
+ `typing` is how its values compare, where the type is known though the
75
+ value is not: a `row_number()` window is an integer."""
65
76
 
66
77
  description: str
78
+ typing: ValueTyping | None = None
67
79
 
68
80
 
69
81
  @dataclass(frozen=True)
70
- class Builtin:
71
- """A built-in operator or function whose behaviour is modelled: a pure
72
- function of its arguments' values, one flag of each kind per parameter.
82
+ class Argument:
83
+ """What a Builtin's property and typing functions see of one argument (ADR
84
+ 0011): its `typing`, when known, and its `literal` value, when it is a
85
+ literal; `null` when it is the NULL literal, which has no type of its
86
+ own. None is unknown, and an unknown gives no property."""
87
+
88
+ typing: ValueTyping | None = None
89
+ literal: LiteralValue | None = None
90
+ null: bool = False
91
+
92
+
93
+ @dataclass(frozen=True)
94
+ class CallProperties:
95
+ """What a Builtin is in each of its arguments, for one call (ADR 0011).
96
+
97
+ A `strict` argument makes the value NULL whenever it is NULL. The value is
98
+ non-null whenever every `total` argument is non-null: all False means
99
+ never NULL, and `total` None means it may be NULL even then (`n % 0` in
100
+ DuckDB). Unless `total` is None, a strict argument is total.
101
+
102
+ An argument the value `respects` equality in gives equal values for
103
+ equal arguments, the others fixed; one it `reflects` equality in (is
104
+ one-to-one in) gives different values for different arguments, the
105
+ others fixed: `a + 1` over integers. Each relative to the equality the
106
+ argument's and the value's types compare by. Values are assumed to stay
107
+ in range, so how the dialect overflows does not matter (ADR 0007).
108
+
109
+ `reason` says why, for explanations."""
110
+
111
+ strict: tuple[bool, ...]
112
+ total: tuple[bool, ...] | None
113
+ respects: tuple[bool, ...]
114
+ reflects: tuple[bool, ...]
115
+ reason: str
116
+
117
+ def __post_init__(self) -> None:
118
+ count = len(self.strict)
119
+ assert self.total is None or len(self.total) == count, "one total flag per argument"
120
+ assert len(self.respects) == len(self.reflects) == count, "one respects and reflects flag per argument"
121
+ assert self.total is None or all(total for strict, total in zip(self.strict, self.total) if strict), "a strict argument is total"
122
+
123
+
124
+ # A Builtin's properties as a function of what is known of its arguments and
125
+ # of the call's own typing (a CAST's target).
126
+ type PropertyFunction = Callable[[tuple[Argument, ...], ValueTyping | None], CallProperties]
73
127
 
74
- A `strict` parameter makes the value NULL whenever its argument is NULL.
75
- The value is non-null whenever every `total` parameter's argument is
76
- non-null: all False means never NULL, and `total` None means it may be NULL
77
- even then (`n % 0` in DuckDB). Unless `total` is None, a strict parameter
78
- is total.
128
+ # A Builtin's result type as a function of what is known of its arguments: the
129
+ # type, or None and why there is none.
130
+ type TypingFunction = Callable[[tuple[Argument, ...]], tuple[ValueTyping | None, str]]
79
131
 
80
- An `injective` one is one-to-one in its single argument that is not an
81
- integer or decimal literal, when that argument is an integer or decimal:
82
- `a + 1`, `10 - a`, `-a`. Only where exact arithmetic raises an error on
83
- overflow instead of wrapping, saturating, or turning to a float.
132
+
133
+ def untyped(arguments: tuple[Argument, ...]) -> tuple[ValueTyping | None, str]:
134
+ """The typing of a Builtin whose result type is not known."""
135
+ return None, "sqlassert knows no result type for the function in this dialect"
136
+
137
+
138
+ @dataclass(frozen=True)
139
+ class Builtin:
140
+ """A built-in operator or function whose behaviour is modelled: a pure
141
+ function of its arguments' values, whose `properties` are a function of
142
+ what is known of them (ADR 0011; a constant one when they are fixed,
143
+ `Builtin.constant`). It takes `arity` arguments, or, when `variadic`, at
144
+ least that many, the last parameter repeating.
84
145
 
85
146
  A `rejecting` parameter makes the value never TRUE (FALSE or NULL)
86
147
  whenever its argument is NULL, though perhaps not NULL: `x > ANY (...)`
@@ -92,62 +153,301 @@ class Builtin:
92
153
  that argument would.
93
154
 
94
155
  With `skips_null` the value is non-null whenever any argument is
95
- (`greatest` where it ignores NULLs), and `total` is None.
156
+ (`greatest` where it ignores NULLs), and it is not total.
157
+
158
+ Its `typing` is the type of its value as a function of what is known of
159
+ its arguments (`untyped` when the dialect gives it no result type), which
160
+ `typed` says it is statically, and `typing_reads` the positions of the
161
+ arguments it reads. A CAST's target is captured in a Builtin built for
162
+ its call site (`functions.captured`), so `Call.arguments` stay values.
163
+ A Builtin that is not `modelled` (a function sqlassert knows only as a
164
+ pure function of its arguments, or a searched CASE) says nothing of its
165
+ properties: explanations say sqlassert does not model it.
96
166
  """
97
167
 
98
168
  name: str
99
- strict: tuple[bool, ...]
100
- total: tuple[bool, ...] | None
101
- injective: bool
169
+ arity: int
170
+ properties: PropertyFunction
171
+ variadic: bool = field(default=False, kw_only=True)
102
172
  rejecting: tuple[bool, ...] = field(default=(), kw_only=True)
103
173
  skips_null: bool = field(default=False, kw_only=True)
104
174
  true_only_if_argument: bool = field(default=False, kw_only=True)
175
+ typing: TypingFunction = field(default=untyped, kw_only=True)
176
+ typed: bool = field(default=False, kw_only=True)
177
+ typing_reads: tuple[int, ...] = field(default=(), kw_only=True)
178
+ modelled: bool = field(default=True, kw_only=True)
105
179
 
106
180
  def __post_init__(self) -> None:
107
- assert self.total is None or len(self.total) == len(self.strict), f"{self.name}: one total flag per parameter"
108
- assert not self.rejecting or len(self.rejecting) == len(self.strict), f"{self.name}: one rejecting flag per parameter"
109
- assert not self.skips_null or self.total is None, f"{self.name}: skipping NULLs, it is not total in each argument"
110
- assert not self.true_only_if_argument or len(self.strict) == 1, f"{self.name}: TRUE only if its one argument is"
111
- assert self.total is None or all(total for strict, total in zip(self.strict, self.total) if strict), (
112
- f"{self.name}: a strict parameter is total"
181
+ unknown = self.properties((Argument(),) * self.arity, None)
182
+ assert len(unknown.strict) == self.arity, f"{self.name}: one property per argument"
183
+ assert not self.rejecting or len(self.rejecting) == self.arity, f"{self.name}: one rejecting flag per parameter"
184
+ assert not self.rejecting or not self.variadic, f"{self.name}: a variadic Builtin rejects through its strict arguments only"
185
+ assert not self.skips_null or unknown.total is None, f"{self.name}: skipping NULLs, it is not total in each argument"
186
+ assert not self.true_only_if_argument or self.arity == 1 and not self.variadic, f"{self.name}: TRUE only if its one argument is"
187
+
188
+ @staticmethod
189
+ def constant(
190
+ name: str, strict: tuple[bool, ...], total: tuple[bool, ...] | None, *, repeated: tuple[bool, bool] | None = None,
191
+ rejecting: tuple[bool, ...] = (), skips_null: bool = False, true_only_if_argument: bool = False,
192
+ ) -> Builtin:
193
+ """A Builtin whose strictness and totality are the same for every call,
194
+ one flag of each per parameter, that respects equality in an argument
195
+ compared by identity (as any pure function does: equal values are
196
+ identical), and reflects it in none. With `repeated`, the (strict, total) flags of
197
+ a last parameter that repeats any number of times, none included:
198
+ `concat_ws(sep, value, ...)` is strict and total in `sep` alone."""
199
+ assert total is None or len(total) == len(strict), f"{name}: one total flag per parameter"
200
+
201
+ def properties(arguments: tuple[Argument, ...], result: ValueTyping | None) -> CallProperties:
202
+ extra = len(arguments) - len(strict)
203
+ repeated_strict, repeated_total = repeated or (False, False)
204
+ return CallProperties(
205
+ strict=strict + (repeated_strict,) * extra,
206
+ total=None if total is None else total + (repeated_total,) * extra,
207
+ respects=identity_arguments(arguments), reflects=(False,) * len(arguments),
208
+ reason=f"{name} is one-to-one in no argument",
209
+ )
210
+
211
+ return Builtin(
212
+ name, len(strict), properties, variadic=repeated is not None, rejecting=rejecting, skips_null=skips_null,
213
+ true_only_if_argument=true_only_if_argument,
113
214
  )
114
215
 
115
216
  def accepts(self, count: int) -> bool:
116
- return count == len(self.strict)
117
-
118
- def strict_flags(self, count: int) -> tuple[bool, ...]:
119
- return self.strict
120
-
121
- def total_flags(self, count: int) -> tuple[bool, ...] | None:
122
- return self.total
217
+ return count >= self.arity if self.variadic else count == self.arity
218
+
219
+
220
+ NO_KNOWN_TYPE = "A result has no known type"
221
+
222
+
223
+ def common_typing(arguments: Sequence[Argument]) -> tuple[ValueTyping | None, str]:
224
+ """The type of an expression that returns one of `arguments` (or NULL): the
225
+ one they share (the NULLs take it); among integer types the widest, an
226
+ integer type being all that every engine promotes them to; a string
227
+ literal beside text compared by identity, or beside a date, time or
228
+ timestamp, is that type. None when an argument has no known type, or the
229
+ types differ (the Hazard `Mixed CASE types`). NULLIF, a searched CASE or
230
+ IF, COALESCE and a simple CASE all ask this."""
231
+ values = [argument for argument in arguments if not argument.null]
232
+ literals = [value for value in values if value.literal is not None and value.literal.type == "string"]
233
+ rest = [value for value in values if not any(value is literal for literal in literals)]
234
+ typings = [value.typing for value in rest]
235
+ if None in typings:
236
+ return None, NO_KNOWN_TYPE
237
+ known = [typing for typing in typings if typing is not None]
238
+ if not known:
239
+ # Only NULLs and string literals: the literals' type.
240
+ if not literals:
241
+ return None, "Every result is NULL"
242
+ return literals[0].typing, "Every result is a string literal"
243
+ if literals and not all(typing.binary_text or typing.temporal for typing in known):
244
+ return None, "A string literal beside a type that is not text compared by identity, nor a date or time"
245
+ if len(set(known)) == 1:
246
+ return known[0], "The results share a type"
247
+ if all(typing.integer is not None for typing in known):
248
+ return max(known, key=lambda typing: typing.integer or 0), "The results are integers: the widest"
249
+ return None, "The results have different types"
250
+
251
+
252
+ def identity_arguments(arguments: tuple[Argument, ...]) -> tuple[bool, ...]:
253
+ """Which arguments compare by identity: any pure function respects
254
+ equality in those (ADR 0011)."""
255
+ return tuple(argument.typing is not None and argument.typing.identity_comparison for argument in arguments)
256
+
257
+
258
+ # What a type is, for its casts (`CastTable`): the families a dialect's
259
+ # cast table classifies casts between, and `on_arg` branches on (the function
260
+ # table). The cast table has no entry for an interval, bytes, json, array,
261
+ # struct or geography: they cast only to their own type. A type in no family
262
+ # (an unsigned integer, CHAR, a map) casts only to its own type too.
263
+ type TypeFamily = Literal[
264
+ "integer", "decimal", "float", "text", "boolean", "uuid", "date", "time", "timestamp", "timestamptz",
265
+ "interval", "bytes", "json", "array", "struct", "geography",
266
+ ]
267
+ # ADR 0009's three kinds of cast: values unchanged; values changed but
268
+ # different ones kept different; two values possibly made one.
269
+ type CastKind = Literal["widening", "injective", "lossy"]
270
+ # The target of a cast table entry: a family, or "sized text", a text type of
271
+ # declared length shorter than the value (`text -> sized text` is "widening"
272
+ # where such a cast keeps the value or raises, absent where it truncates).
273
+ type CastTarget = TypeFamily | Literal["sized text"]
123
274
 
124
275
 
125
276
  @dataclass(frozen=True)
126
- class BuiltinVariadic(Builtin):
127
- """A Builtin whose last parameter repeats any number of times (none
128
- included), each repetition with the `repeated_` flags:
129
- `concat_ws(sep, value, ...)` is strict and total in `sep` alone."""
130
-
131
- repeated_strict: bool
132
- repeated_total: bool
133
-
134
- def __post_init__(self) -> None:
135
- super().__post_init__()
136
- assert not self.injective, f"{self.name}: a variadic Builtin is not injective"
137
- assert self.total is None or self.repeated_total or not self.repeated_strict, f"{self.name}: a strict parameter is total"
138
-
139
- def accepts(self, count: int) -> bool:
140
- return count >= len(self.strict)
277
+ class ValueTyping:
278
+ """How the values of a typed expression compare, as a column declared with
279
+ that type would: its `comparison_type` (the type's SQL name, which two
280
+ values of one type share), whether it is `binary_text` (text compared by
281
+ identity: VARCHAR or TEXT in a dialect whose default collation is binary,
282
+ `DialectSemantics.text_is_binary`), whether `identity_comparison` holds
283
+ (equal values are identical: an integer, decimal, boolean, date, time,
284
+ timestamp, UUID or binary text; not a float, `-0.0 = 0.0`, an interval, or
285
+ text under a case-insensitive collation), whether it is `exact_numeric` (an
286
+ integer or decimal), whether it is `floating` (REAL, FLOAT, DOUBLE), and
287
+ its `integer` width rank when it is a signed integer type (TINYINT 0, up;
288
+ unsigned types are none), whether it is `text` (any character type, in any
289
+ collation the dialect ships as default), and whether it is `temporal` (a
290
+ date, time or timestamp).
291
+
292
+ For its casts (`CastTable`): its `family`, and the parameters that decide
293
+ a cast within one: a text type's declared `length` (None: unsized), a
294
+ decimal's `precision` and `scale`, a time or timestamp's fractional
295
+ `precision` (None: not declared, the dialect's default). `casts` is the
296
+ dialect's cast table, which a comparison with another type asks; None
297
+ where no dialect made the type. An expression whose type is not known
298
+ has no ValueTyping."""
299
+
300
+ comparison_type: str
301
+ binary_text: bool
302
+ identity_comparison: bool
303
+ exact_numeric: bool
304
+ floating: bool = False
305
+ integer: int | None = None
306
+ text: bool = False
307
+ temporal: bool = False
308
+ family: TypeFamily | None = None
309
+ length: int | None = None
310
+ precision: int | None = None
311
+ scale: int | None = None
312
+ casts: CastTable | None = field(default=None, compare=False, repr=False)
313
+
314
+
315
+ # The digits of the largest value of each signed integer width rank
316
+ # (`ValueTyping.integer`: TINYINT 127 has 3), and the digits every value of
317
+ # that many digits fits in (TINYINT holds every 2-digit number).
318
+ _INTEGER_DIGITS = (3, 5, 7, 10, 19, 39, 77)
319
+ _INTEGER_FULL_DIGITS = (2, 4, 6, 9, 18, 38, 76)
320
+
321
+ # Which side a comparison of two families casts (`CastTable.compared`): the
322
+ # one earlier in its group, into the other's type. Text beside any other
323
+ # family is cast to it. Pairs in no group have no modelled common type.
324
+ _COERCION_GROUPS: tuple[tuple[TypeFamily, ...], ...] = (("integer", "decimal", "float"), ("date", "timestamp", "timestamptz"))
325
+
326
+
327
+ def _merged(source: TypeFamily, target: TypeFamily) -> str:
328
+ """Two values a lossy cast between families makes one, for its reason."""
329
+ match source, target:
330
+ case "text", "integer" | "decimal" | "float":
331
+ return " (text like '01' and '1' becomes one number)"
332
+ case "text", _:
333
+ return f" (two spellings of one {target} become one value)"
334
+ case "float" | "decimal", "integer" | "decimal":
335
+ return " (1.2 and 1.4 may round to one value)"
336
+ case "timestamp" | "timestamptz", "date":
337
+ return " (two times of one day become one date)"
338
+ case _:
339
+ return ""
141
340
 
142
- def strict_flags(self, count: int) -> tuple[bool, ...]:
143
- return self.strict + (self.repeated_strict,) * (count - len(self.strict))
144
341
 
145
- def total_flags(self, count: int) -> tuple[bool, ...] | None:
146
- return None if self.total is None else self.total + (self.repeated_total,) * (count - len(self.total))
342
+ @dataclass(frozen=True)
343
+ class CastTable:
344
+ """A dialect's casts (ADR 0011): whether a cast from one type to another
345
+ keeps each value (widening), changes values but keeps different ones
346
+ different (injective), or may make two values one (lossy), ADR 0009.
347
+
348
+ Family rules, the same in every dialect, decide a cast within a family:
349
+ an integer into one at least as wide; a decimal into one with at least
350
+ its scale and integer digits; text into unsized text, or into text at
351
+ least as long; a time or timestamp into one of its own precision or a
352
+ declared finer one. An integer goes into a decimal with room for its
353
+ digits, a decimal of scale 0 into an integer that holds its digits. Any
354
+ other type casts only to itself. Across families, `entries` are the
355
+ dialect's facts (`DialectSemantics.casts`): each pair of families listed
356
+ is that kind; any other pair is lossy. An unknown type is lossy.
357
+
358
+ The same cast serves a comparison (`compared`), which casts one side into
359
+ the other's type."""
360
+
361
+ entries: tuple[tuple[TypeFamily, CastTarget, CastKind], ...] = ()
362
+
363
+ def classify(self, source: ValueTyping | None, target: ValueTyping | None) -> tuple[CastKind, str]:
364
+ """The kind of a cast of `source` values to `target`'s type, and why."""
365
+ if source is None or target is None:
366
+ return "lossy", "a type is not known"
367
+ cast = f"{source.comparison_type} to {target.comparison_type}"
368
+ if source.family is None or target.family is None:
369
+ if source.comparison_type == target.comparison_type:
370
+ return "widening", f"a cast from {cast} is to the same type"
371
+ return "lossy", f"sqlassert knows no cast from {cast} that keeps values apart"
372
+ if source.family == target.family:
373
+ return self._within(source, target, cast)
374
+ match source.family, target.family:
375
+ case "integer", "decimal":
376
+ room = target.precision is not None and target.scale is not None and source.integer is not None
377
+ if room and target.precision - target.scale >= _INTEGER_DIGITS[source.integer]:
378
+ return "widening", f"a cast from {cast} has room for every integer"
379
+ return "lossy", f"a cast from {cast} may lack room for an integer"
380
+ case "decimal", "integer":
381
+ if source.scale == 0 and source.precision is not None and target.integer is not None and source.precision <= _INTEGER_FULL_DIGITS[target.integer]:
382
+ return "widening", f"a cast from {cast} holds every value"
383
+ return "lossy", f"a cast from {cast} may round or lack room (1.2 and 1.4 both become 1)"
384
+ case _:
385
+ pass
386
+ kind = self._entry(source.family, target.family)
387
+ if kind == "lossy":
388
+ return "lossy", f"a cast from {cast} may make two values one{_merged(source.family, target.family)}"
389
+ if target.family == "text" and target.length is not None and self._entry("text", "sized text") != "widening":
390
+ return "lossy", f"a cast from {cast} truncates to {target.length} characters"
391
+ return kind, f"a cast from {cast} keeps different values different"
392
+
393
+ def _within(self, source: ValueTyping, target: ValueTyping, cast: str) -> tuple[CastKind, str]:
394
+ same = source.comparison_type == target.comparison_type
395
+ match source.family:
396
+ case "integer" if source.integer is not None and target.integer is not None:
397
+ if target.integer >= source.integer:
398
+ return "widening", f"a cast from {cast} widens"
399
+ return "lossy", f"a cast from {cast} narrows"
400
+ case "decimal" if not same:
401
+ match source.precision, source.scale, target.precision, target.scale:
402
+ case int(precision), int(scale), int(wider), int(finer) if finer >= scale and wider - finer >= precision - scale:
403
+ return "widening", f"a cast from {cast} widens"
404
+ case _:
405
+ pass
406
+ return "lossy", f"a cast from {cast} may round or lack room"
407
+ case "text":
408
+ if target.length is None or source.length is not None and source.length <= target.length:
409
+ return "widening", f"a cast from {cast} keeps the text"
410
+ if self._entry("text", "sized text") == "widening":
411
+ return "widening", f"a cast from {cast} keeps the text or raises"
412
+ return "lossy", f"a cast from {cast} truncates to {target.length} characters"
413
+ case "time" | "timestamp" | "timestamptz":
414
+ finer = source.precision is not None and target.precision is not None and target.precision >= source.precision
415
+ if same and (source.precision == target.precision or finer):
416
+ return "widening", f"a cast from {cast} keeps the fraction of a second"
417
+ return "lossy", f"a cast from {cast} may round"
418
+ case _:
419
+ pass
420
+ if same:
421
+ return "widening", f"a cast from {cast} is to the same type"
422
+ return "lossy", f"sqlassert knows no cast from {cast} that keeps values apart"
423
+
424
+ def _entry(self, source: TypeFamily, target: CastTarget) -> CastKind:
425
+ return next((kind for entry_source, entry_target, kind in self.entries if (entry_source, entry_target) == (source, target)), "lossy")
426
+
427
+ def compared(self, left: ValueTyping, right: ValueTyping) -> tuple[CastKind, str]:
428
+ """The kind of the cast a comparison of `left` with `right` applies to
429
+ the side it casts into the other's type (the other is unchanged):
430
+ within a family the narrower side, else the side earlier in its
431
+ coercion group (an integer beside a decimal, a date beside a
432
+ timestamp), text beside anything else. Lossy where no common type is
433
+ modelled."""
434
+ if left.family is not None and left.family == right.family:
435
+ kind, why = self.classify(left, right)
436
+ return (kind, why) if kind != "lossy" else self.classify(right, left)
437
+ for source, target in ((left, right), (right, left)):
438
+ if source.family == "text" and target.family is not None:
439
+ return self.classify(source, target)
440
+ for group in _COERCION_GROUPS:
441
+ if source.family in group and target.family in group and group.index(source.family) < group.index(target.family):
442
+ return self.classify(source, target)
443
+ return "lossy", f"no common type of {left.comparison_type} and {right.comparison_type} is modelled"
147
444
 
148
445
 
149
446
  class Call(ScalarExpr):
150
- """A Builtin applied to arguments: `n + 1`, `n > 0`, `CAST(n AS BIGINT)`, `NOT p`."""
447
+ """A Builtin applied to arguments: `n + 1`, `n > 0`, `CAST(n AS BIGINT)`, `NOT p`.
448
+
449
+ How its values compare is its Builtin's `typing`, asked with the
450
+ arguments' types (`rules/value_typing.scalar_typing`)."""
151
451
 
152
452
  function: Builtin
153
453
  arguments: tuple[ScalarExpr, ...]
@@ -156,17 +456,26 @@ class Call(ScalarExpr):
156
456
  def __post_init__(self) -> None:
157
457
  assert self.function.accepts(len(self.arguments)), f"{self.function.name} takes no {len(self.arguments)} arguments"
158
458
 
459
+ @cached_property
460
+ def properties(self) -> CallProperties:
461
+ """The Builtin's properties known from the call alone: each argument's
462
+ literal, no derived type. NULL reasoning reads these: a property that
463
+ needs a type is unknown here, so false (ADR 0011), and no Builtin's
464
+ strictness or totality needs one. The rules derive types and ask for
465
+ the rest (`rules/value_typing.call_properties`)."""
466
+ summaries = tuple(Argument(literal=argument.value if isinstance(argument, Constant) else None) for argument in self.arguments)
467
+ return self.function.properties(summaries, self.function.typing(summaries)[0])
468
+
159
469
  @property
160
470
  def strict_arguments(self) -> tuple[ScalarExpr, ...]:
161
471
  """The arguments whose NULL makes the value NULL."""
162
- flags = self.function.strict_flags(len(self.arguments))
163
- return tuple(argument for argument, strict in zip(self.arguments, flags) if strict)
472
+ return tuple(argument for argument, strict in zip(self.arguments, self.properties.strict) if strict)
164
473
 
165
474
  @property
166
475
  def rejecting_arguments(self) -> tuple[ScalarExpr, ...]:
167
476
  """The arguments whose NULL makes the value never TRUE: the strict ones
168
477
  and the `rejecting` ones."""
169
- flags = self.function.strict_flags(len(self.arguments))
478
+ flags = self.properties.strict
170
479
  rejecting = self.function.rejecting or (False,) * len(flags)
171
480
  return tuple(argument for argument, strict, rejects in zip(self.arguments, flags, rejecting) if strict or rejects)
172
481
 
@@ -174,27 +483,9 @@ class Call(ScalarExpr):
174
483
  def total_arguments(self) -> tuple[ScalarExpr, ...] | None:
175
484
  """The arguments whose being non-null makes the value non-null (none:
176
485
  never NULL), or None when the value may be NULL regardless."""
177
- flags = self.function.total_flags(len(self.arguments))
486
+ flags = self.properties.total
178
487
  return None if flags is None else tuple(argument for argument, total in zip(self.arguments, flags) if total)
179
488
 
180
- @property
181
- def injective_argument(self) -> ScalarExpr | None:
182
- """The argument the value is one-to-one in, when it is an integer or
183
- decimal: the single one that is not an integer or decimal literal."""
184
- if not self.function.injective:
185
- return None
186
- others = [argument for argument in self.arguments if not _exact_literal(argument)]
187
- return others[0] if len(others) == 1 else None
188
-
189
-
190
- class OpaquePureFunction(ScalarExpr):
191
- """A built-in function or operator whose behaviour is not modelled: a pure
192
- function of its arguments, and nothing else is known about it. Searched
193
- CASE, and `concat`, `||` or `greatest` where the dialect's is not modelled."""
194
-
195
- arguments: tuple[ScalarExpr, ...]
196
- description: str
197
-
198
489
 
199
490
  class Count(ScalarExpr):
200
491
  """`count(*)` or `count(...)`: never NULL, even over no rows; its value is
@@ -232,9 +523,14 @@ class LiteralValue:
232
523
 
233
524
 
234
525
  class Constant(ScalarExpr):
235
- """A non-null literal; `value` is None while its type is not modelled."""
526
+ """A non-null literal; `value` is None while its type is not modelled.
527
+
528
+ `typing` is how it compares, from the dialect's type for a literal of its
529
+ kind (`IrParser._literal_typing`); None where that is not known: a decimal
530
+ or exponent literal in a dialect whose type for it is not claimed."""
236
531
 
237
532
  value: LiteralValue | None = None
533
+ typing: ValueTyping | None = None
238
534
 
239
535
 
240
536
  class NullLiteral(ScalarExpr):
@@ -380,7 +676,7 @@ def determinants(expression: ScalarExpr) -> tuple[OutputColumn, ...] | None:
380
676
  case OpaqueExpression() | Count() | AnyAggregate() | Accumulation():
381
677
  return None
382
678
  case (
383
- Constant() | NullLiteral() | Call() | OpaquePureFunction() | Coalesce() | SimpleCase() | Elements() | Equality()
679
+ Constant() | NullLiteral() | Call() | Coalesce() | SimpleCase() | Elements() | Equality()
384
680
  | NullSafeEquality() | InList() | IsNull() | IsNotNull() | And() | Or()
385
681
  ):
386
682
  found: dict[OutputColumn, None] = {}
@@ -395,34 +691,6 @@ def determinants(expression: ScalarExpr) -> tuple[OutputColumn, ...] | None:
395
691
  assert_never(expression)
396
692
 
397
693
 
398
- def injective_input(expression: ScalarExpr) -> OutputColumn | None:
399
- """The one column `expression` is a one-to-one function of, given that the
400
- column is an integer or decimal: the column itself, or an injective
401
- Builtin of such an expression and integer or decimal literals."""
402
- expression = expression.closed
403
- match expression:
404
- case ColumnRef(column=column):
405
- return column
406
- case Call(injective_argument=ScalarExpr() as argument):
407
- return injective_input(argument)
408
- case (
409
- Call() | Constant() | NullLiteral() | Coalesce() | SimpleCase() | OpaquePureFunction() | OpaqueExpression()
410
- | Count() | AnyAggregate() | Accumulation() | Elements() | Equality() | NullSafeEquality() | InList() | IsNull() | IsNotNull() | And() | Or()
411
- ):
412
- return None
413
- case _:
414
- assert_never(expression)
415
-
416
-
417
- def _exact_literal(expression: ScalarExpr) -> bool:
418
- """An integer or decimal literal: not an exponent form, which is a double."""
419
- match expression:
420
- case Constant(value=LiteralValue(type="numeric", text=text)):
421
- return "e" not in text
422
- case _:
423
- return False
424
-
425
-
426
694
  def total(expression: ScalarExpr) -> bool:
427
695
  """Whether `expression` is non-null whenever every column it reads is: a
428
696
  column, a literal, `count(...)`, the IS family, a Builtin total in its
@@ -443,7 +711,7 @@ def total(expression: ScalarExpr) -> bool:
443
711
  case Coalesce(arguments=arguments):
444
712
  return any(total(argument) for argument in arguments)
445
713
  case (
446
- Call() | NullLiteral() | SimpleCase() | OpaquePureFunction() | OpaqueExpression() | AnyAggregate() | Accumulation() | Elements()
714
+ Call() | NullLiteral() | SimpleCase() | OpaqueExpression() | AnyAggregate() | Accumulation() | Elements()
447
715
  | Equality() | InList() | And() | Or()
448
716
  ):
449
717
  return False
@@ -474,7 +742,7 @@ def strict_inputs(expression: ScalarExpr) -> tuple[OutputColumn, ...]:
474
742
  rest = [strict_inputs(other) for other in others]
475
743
  return tuple(column for column in strict_inputs(first) if all(column in columns for columns in rest))
476
744
  case (
477
- And() | Or() | Constant() | NullLiteral() | Coalesce() | SimpleCase() | OpaquePureFunction() | OpaqueExpression()
745
+ And() | Or() | Constant() | NullLiteral() | Coalesce() | SimpleCase() | OpaqueExpression()
478
746
  | Count() | AnyAggregate() | Accumulation() | Elements() | IsNull() | IsNotNull() | NullSafeEquality()
479
747
  ):
480
748
  return ()
@@ -488,7 +756,7 @@ def strict_inputs(expression: ScalarExpr) -> tuple[OutputColumn, ...]:
488
756
  # it. tests/test_ir_unions.py checks these stay in sync with the subclasses,
489
757
  # which makes `ScalarExpr.closed` and `RelationExpr.closed` sound.
490
758
  type AnyScalar = (
491
- ColumnRef | Constant | NullLiteral | Coalesce | SimpleCase | Call | OpaquePureFunction | OpaqueExpression
759
+ ColumnRef | Constant | NullLiteral | Coalesce | SimpleCase | Call | OpaqueExpression
492
760
  | Count | AnyAggregate | Accumulation | Elements | Equality | NullSafeEquality | InList | IsNull | IsNotNull | And | Or
493
761
  )
494
762
 
@@ -496,26 +764,15 @@ type AnyScalar = (
496
764
  class OutputColumn(Node):
497
765
  """One named output of one relational stage and the expression producing it.
498
766
 
499
- `binary_text` marks a table column declared as text compared by identity:
500
- VARCHAR or TEXT in a dialect whose default collation is binary
501
- (`DialectSemantics.text_is_binary`). Equal to such a column, distinct
502
- strings are distinct values.
503
-
504
- `identity_comparison` marks a table column whose equal values are
505
- identical: an integer, decimal, boolean, date, time, timestamp or UUID
506
- type, or binary text. Not a float (`-0.0 = 0.0`), an interval, or text
507
- under a case-insensitive default collation (MySQL's).
508
-
509
- `exact_numeric` marks a table column declared as an integer or decimal.
767
+ `typing` is how the values of a column declared with a type compare: a
768
+ table column, or a VALUES column (`IrParser._declared_typing`). None for a
769
+ column whose type is not declared; one that computes or passes on a value
770
+ has the type of its expression (`rules/value_typing.py`).
510
771
  """
511
772
 
512
773
  name: str
513
774
  scalar_expr: ScalarExpr
514
- binary_text: bool = False
515
- # Declared SQL type where equality compares values without casts.
516
- comparison_type: str | None = None
517
- identity_comparison: bool = False
518
- exact_numeric: bool = False
775
+ typing: ValueTyping | None = None
519
776
 
520
777
  def get_relation(self, program: Program) -> RelationExpr:
521
778
  """The one relation in ``program`` whose output includes this column."""
@@ -549,10 +806,6 @@ class NamedRelation(RelationExpr):
549
806
  role: RelationRole
550
807
  body: RelationExpr | None = None
551
808
 
552
- @property
553
- def report_name(self) -> str:
554
- return f"CTE_{self.name}" if self.role is RelationRole.CTE else self.name
555
-
556
809
 
557
810
  class Alias(RelationExpr):
558
811
  """One occurrence of a relation expression in a query scope."""
@@ -577,6 +830,12 @@ class Join(RelationExpr):
577
830
  # subquery's body, and each left row matches at most one right row, or
578
831
  # the query fails (more than one row is a runtime error).
579
832
  scalar_subquery: bool = False
833
+ # An INNER, LEFT or CROSS join whose right input is a table function or
834
+ # UNNEST with an argument that reads a column of the left input: it is
835
+ # evaluated once per left row, so each right row is produced by exactly
836
+ # one left row and none is repeated (a left row may repeat, once per row
837
+ # the function returns for it).
838
+ lateral: bool = False
580
839
 
581
840
  @property
582
841
  def conjuncts(self) -> tuple[ScalarExpr, ...]:
@@ -627,26 +886,37 @@ class Distinct(RelationExpr):
627
886
 
628
887
  class SetOperation(RelationExpr):
629
888
  """UNION, INTERSECT, or EXCEPT. Output columns refer to the left input;
630
- `arms` pairs each with the right input's column at its position."""
889
+ `arms` pairs each with the right input's column at its position. A
890
+ `UNION BY NAME` is lowered to that form (convert's `_align_by_name`).
891
+
892
+ `recursive` is the body of a recursive CTE or view: the left input is the
893
+ base case and the right one reads the relation itself. The engine fixes
894
+ each output column's type from the base case, whatever the recursive arm
895
+ computes (it casts the arm, or rejects a mismatch), so the type of a
896
+ column is its base case column's. Typing only: values, NULLs, keys and
897
+ domains still come from both inputs."""
631
898
 
632
899
  operator: SetOperator
633
900
  left: RelationExpr
634
901
  right: RelationExpr
635
902
  distinct: bool = True
636
- by_name: bool = False
903
+ unpaired: bool = False
904
+ recursive: bool = False
637
905
 
638
906
  def arms(self, column: OutputColumn) -> tuple[OutputColumn, OutputColumn] | None:
639
907
  """The left and right input columns `column` is computed from, or None
640
- when the inputs pair by name (`UNION BY NAME`) or differ in width (an
641
- unanalyzed input whose columns are unknown)."""
642
- if self.by_name or len(self.left.output_columns) != len(self.right.output_columns):
908
+ when the inputs do not pair by position: `unpaired` (a form of `BY
909
+ NAME` the IR does not model) or a different width (an input whose
910
+ columns are unknown)."""
911
+ if self.unpaired or len(self.left.output_columns) != len(self.right.output_columns):
643
912
  return None
644
913
  position = self.output_columns.index(column)
645
914
  return self.left.output_columns[position], self.right.output_columns[position]
646
915
 
647
916
 
648
917
  class QualifyByPartition(RelationExpr):
649
- """One row per partition: ``QUALIFY row_number() OVER (PARTITION BY ...) = 1`` or ``DISTINCT ON (...)``."""
918
+ """One row per partition: ``QUALIFY row_number() OVER (PARTITION BY ...) = 1`` or ``DISTINCT ON (...)``.
919
+ A partition key is an output column, possibly hidden (a Project over this drops it); no key is one row in all."""
650
920
 
651
921
  input: RelationExpr
652
922
  partition_outputs: tuple[OutputColumn, ...]
@@ -658,14 +928,26 @@ class OpaqueRelation(RelationExpr):
658
928
 
659
929
 
660
930
  class RecursiveRelation(OpaqueRelation):
661
- """An explicit unsupported recursive reference, represented without a cycle."""
931
+ """An explicit unsupported recursive reference, represented without a cycle.
932
+
933
+ Its rows and values are unknown, but the engine fixes each column's type
934
+ from the base case, so `typed_by` is, per output column, the base case's
935
+ column whose type it takes (None when it has none: an untyped base column
936
+ is read through it). Typing only: no value, NULL, key, domain or lineage
937
+ is shared, since the recursive rows differ from the base case's."""
662
938
 
663
939
  relation_name: str
940
+ typed_by: tuple[OutputColumn | None, ...] = ()
941
+
942
+
943
+ class ValuesList(OpaqueRelation):
944
+ """`(VALUES (...), ...) AS t (a, ...)`: rows of written values, its
945
+ columns stated as Knowledge. No column has a declared type."""
664
946
 
665
947
 
666
948
  type AnyRelation = (
667
949
  NamedRelation | Alias | Join | Filter | Project | Limit | Aggregate | Distinct | SetOperation
668
- | QualifyByPartition | OpaqueRelation | RecursiveRelation
950
+ | QualifyByPartition | OpaqueRelation | RecursiveRelation | ValuesList
669
951
  )
670
952
 
671
953
 
@@ -684,17 +966,6 @@ class Program:
684
966
  # Every JOIN, Select Expression, and simple CASE a marker can attach to, with
685
967
  # the Join, the relation the Select produces, or the lowered CASE.
686
968
  attachment_sites: tuple[tuple[AttachmentSite, RelationExpr | SimpleCase], ...] = ()
687
- # Each scalar subquery lowered as a join, with where its Select is written.
688
- scalar_subqueries: tuple[tuple[AttachmentSite, Join], ...] = ()
689
- # Each Select Expression's ORDER BY keys, at its trailing site, as columns
690
- # of the stage it sorts: the input of a Project, else the Select's own
691
- # relation. Empty with no ORDER BY; None when a key is an expression or a
692
- # name that does not resolve to one column, and for DISTINCT ON, whose
693
- # ORDER BY picks the rows it keeps.
694
- sort_keys: tuple[tuple[AttachmentSite, tuple[OutputColumn, ...] | None], ...] = ()
695
- # Each INTERSECT and EXCEPT, sited where its keyword follows its left
696
- # input's last Select (no marker attaches there).
697
- set_operations: tuple[tuple[AttachmentSite, SetOperation], ...] = ()
698
969
  # Each node standing for a construct sqlassert does not support yet (an
699
970
  # opaque relation or value), with what it is: an assertion whose proof
700
971
  # reaches one says so when it stays UNKNOWN.