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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. sqlassert/declared_types.py +158 -0
  2. sqlassert/diagnostics.py +1 -4
  3. sqlassert/dialects.py +118 -396
  4. sqlassert/discovery/bigquery.py +2 -2
  5. sqlassert/discovery/databricks.py +4 -6
  6. sqlassert/discovery/fetcher.py +22 -52
  7. sqlassert/discovery/information_schema.py +7 -10
  8. sqlassert/discovery/mysql.py +4 -8
  9. sqlassert/discovery/postgres.py +17 -26
  10. sqlassert/discovery/redshift.py +2 -2
  11. sqlassert/discovery/snowflake.py +2 -2
  12. sqlassert/functions/__init__.py +10 -0
  13. sqlassert/functions/load.py +375 -0
  14. sqlassert/functions/table.py +2721 -0
  15. sqlassert/hazards.py +1 -1
  16. sqlassert/ir/__init__.py +13 -5
  17. sqlassert/ir/convert/aggregation.py +2 -3
  18. sqlassert/ir/convert/expressions.py +76 -67
  19. sqlassert/ir/convert/parser.py +0 -4
  20. sqlassert/ir/convert/schema.py +11 -80
  21. sqlassert/ir/convert/selects.py +30 -15
  22. sqlassert/ir/convert/shared.py +2 -3
  23. sqlassert/ir/convert/sources.py +2 -1
  24. sqlassert/ir/convert/value_types.py +12 -157
  25. sqlassert/ir/model.py +331 -138
  26. sqlassert/main.py +7 -10
  27. sqlassert/rules/causes/domain.py +1 -1
  28. sqlassert/rules/causes/unique.py +46 -5
  29. sqlassert/rules/domain.py +1 -1
  30. sqlassert/rules/join_cardinality.py +14 -21
  31. sqlassert/rules/nullability.py +3 -3
  32. sqlassert/rules/uniqueness.py +42 -41
  33. sqlassert/rules/value_typing.py +266 -133
  34. sqlassert/suggest.py +2 -2
  35. {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/METADATA +18 -14
  36. sqlassert-0.4.2.dist-info/RECORD +72 -0
  37. sqlassert/ir/convert/builtins.py +0 -140
  38. sqlassert-0.4.1.dist-info/RECORD +0 -69
  39. {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/WHEEL +0 -0
  40. {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/entry_points.txt +0 -0
  41. {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/licenses/LICENSE +0 -0
  42. {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/top_level.txt +0 -0
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
 
@@ -77,20 +79,69 @@ class OpaqueExpression(ScalarExpr):
77
79
 
78
80
 
79
81
  @dataclass(frozen=True)
80
- class Builtin:
81
- """A built-in operator or function whose behaviour is modelled: a pure
82
- 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]
127
+
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]]
83
131
 
84
- A `strict` parameter makes the value NULL whenever its argument is NULL.
85
- The value is non-null whenever every `total` parameter's argument is
86
- non-null: all False means never NULL, and `total` None means it may be NULL
87
- even then (`n % 0` in DuckDB). Unless `total` is None, a strict parameter
88
- is total.
89
132
 
90
- An `injective` one is one-to-one in its single argument that is not an
91
- integer or decimal literal, when that argument is an integer or decimal:
92
- `a + 1`, `10 - a`, `-a`. Values are assumed to stay in range, so how the
93
- dialect overflows does not matter (ADR 0007).
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.
94
145
 
95
146
  A `rejecting` parameter makes the value never TRUE (FALSE or NULL)
96
147
  whenever its argument is NULL, though perhaps not NULL: `x > ANY (...)`
@@ -102,58 +153,124 @@ class Builtin:
102
153
  that argument would.
103
154
 
104
155
  With `skips_null` the value is non-null whenever any argument is
105
- (`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.
106
166
  """
107
167
 
108
168
  name: str
109
- strict: tuple[bool, ...]
110
- total: tuple[bool, ...] | None
111
- injective: bool
169
+ arity: int
170
+ properties: PropertyFunction
171
+ variadic: bool = field(default=False, kw_only=True)
112
172
  rejecting: tuple[bool, ...] = field(default=(), kw_only=True)
113
173
  skips_null: bool = field(default=False, kw_only=True)
114
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)
115
179
 
116
180
  def __post_init__(self) -> None:
117
- assert self.total is None or len(self.total) == len(self.strict), f"{self.name}: one total flag per parameter"
118
- assert not self.rejecting or len(self.rejecting) == len(self.strict), f"{self.name}: one rejecting flag per parameter"
119
- assert not self.skips_null or self.total is None, f"{self.name}: skipping NULLs, it is not total in each argument"
120
- assert not self.true_only_if_argument or len(self.strict) == 1, f"{self.name}: TRUE only if its one argument is"
121
- assert self.total is None or all(total for strict, total in zip(self.strict, self.total) if strict), (
122
- 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,
123
214
  )
124
215
 
125
216
  def accepts(self, count: int) -> bool:
126
- return count == len(self.strict)
127
-
128
- def strict_flags(self, count: int) -> tuple[bool, ...]:
129
- return self.strict
130
-
131
- def total_flags(self, count: int) -> tuple[bool, ...] | None:
132
- return self.total
133
-
134
-
135
- @dataclass(frozen=True)
136
- class BuiltinVariadic(Builtin):
137
- """A Builtin whose last parameter repeats any number of times (none
138
- included), each repetition with the `repeated_` flags:
139
- `concat_ws(sep, value, ...)` is strict and total in `sep` alone."""
140
-
141
- repeated_strict: bool
142
- repeated_total: bool
143
-
144
- def __post_init__(self) -> None:
145
- super().__post_init__()
146
- assert not self.injective, f"{self.name}: a variadic Builtin is not injective"
147
- assert self.total is None or self.repeated_total or not self.repeated_strict, f"{self.name}: a strict parameter is total"
148
-
149
- def accepts(self, count: int) -> bool:
150
- return count >= len(self.strict)
151
-
152
- def strict_flags(self, count: int) -> tuple[bool, ...]:
153
- return self.strict + (self.repeated_strict,) * (count - len(self.strict))
154
-
155
- def total_flags(self, count: int) -> tuple[bool, ...] | None:
156
- return None if self.total is None else self.total + (self.repeated_total,) * (count - len(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"]
157
274
 
158
275
 
159
276
  @dataclass(frozen=True)
@@ -170,10 +287,15 @@ class ValueTyping:
170
287
  its `integer` width rank when it is a signed integer type (TINYINT 0, up;
171
288
  unsigned types are none), whether it is `text` (any character type, in any
172
289
  collation the dialect ships as default), and whether it is `temporal` (a
173
- date, time or timestamp), and the types it `casts_to` when compared with
174
- them, keeping different values different (`DialectSemantics.injective_casts`:
175
- a DATE becomes its midnight beside a TIMESTAMP). An expression whose type
176
- is not known has no ValueTyping."""
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."""
177
299
 
178
300
  comparison_type: str
179
301
  binary_text: bool
@@ -183,51 +305,177 @@ class ValueTyping:
183
305
  integer: int | None = None
184
306
  text: bool = False
185
307
  temporal: bool = False
186
- casts_to: frozenset[str] = frozenset()
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 ""
187
340
 
188
341
 
189
342
  @dataclass(frozen=True)
190
- class ArgumentTyping:
191
- """The type of a call that depends on one argument's type
192
- (`DialectSemantics.argument_result_types`): `results` by the argument's
193
- `comparison_type`, and, when `keeps`, any other type is the argument's
194
- own. A type not listed, or an argument of unknown type, leaves the call
195
- untyped."""
196
-
197
- argument: int
198
- results: tuple[tuple[str, ValueTyping], ...]
199
- keeps: bool = False
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"
200
444
 
201
445
 
202
446
  class Call(ScalarExpr):
203
447
  """A Builtin applied to arguments: `n + 1`, `n > 0`, `CAST(n AS BIGINT)`, `NOT p`.
204
448
 
205
- `typing` is how its values compare, where the type is known from the call
206
- itself: a CAST's (`IrParser._cast_typing`) or a function the dialect gives
207
- a fixed result type (`DialectSemantics.result_types`). Arithmetic and
208
- NULLIF are typed by their operands (`rules/value_typing.py`), and a
209
- function whose type follows an argument's by `typed_by`."""
449
+ How its values compare is its Builtin's `typing`, asked with the
450
+ arguments' types (`rules/value_typing.scalar_typing`)."""
210
451
 
211
452
  function: Builtin
212
453
  arguments: tuple[ScalarExpr, ...]
213
454
  description: str
214
- typing: ValueTyping | None = None
215
- typed_by: ArgumentTyping | None = None
216
455
 
217
456
  def __post_init__(self) -> None:
218
457
  assert self.function.accepts(len(self.arguments)), f"{self.function.name} takes no {len(self.arguments)} arguments"
219
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
+
220
469
  @property
221
470
  def strict_arguments(self) -> tuple[ScalarExpr, ...]:
222
471
  """The arguments whose NULL makes the value NULL."""
223
- flags = self.function.strict_flags(len(self.arguments))
224
- 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)
225
473
 
226
474
  @property
227
475
  def rejecting_arguments(self) -> tuple[ScalarExpr, ...]:
228
476
  """The arguments whose NULL makes the value never TRUE: the strict ones
229
477
  and the `rejecting` ones."""
230
- flags = self.function.strict_flags(len(self.arguments))
478
+ flags = self.properties.strict
231
479
  rejecting = self.function.rejecting or (False,) * len(flags)
232
480
  return tuple(argument for argument, strict, rejects in zip(self.arguments, flags, rejecting) if strict or rejects)
233
481
 
@@ -235,36 +483,9 @@ class Call(ScalarExpr):
235
483
  def total_arguments(self) -> tuple[ScalarExpr, ...] | None:
236
484
  """The arguments whose being non-null makes the value non-null (none:
237
485
  never NULL), or None when the value may be NULL regardless."""
238
- flags = self.function.total_flags(len(self.arguments))
486
+ flags = self.properties.total
239
487
  return None if flags is None else tuple(argument for argument, total in zip(self.arguments, flags) if total)
240
488
 
241
- @property
242
- def injective_argument(self) -> ScalarExpr | None:
243
- """The argument the value is one-to-one in, when it is an integer or
244
- decimal: the single one that is not an integer or decimal literal."""
245
- if not self.function.injective:
246
- return None
247
- others = [argument for argument in self.arguments if not _exact_literal(argument)]
248
- return others[0] if len(others) == 1 else None
249
-
250
-
251
- class OpaquePureFunction(ScalarExpr):
252
- """A built-in function or operator whose behaviour is not modelled: a pure
253
- function of its arguments, and nothing else is known about it. Searched
254
- CASE, and `concat`, `||` or `greatest` where the dialect's is not modelled.
255
-
256
- `typing` is how its values compare, where the dialect fixes the result
257
- type of the function (`DialectSemantics.result_types`). `results` are the
258
- positions of the arguments it returns one of, or NULL, when it only
259
- selects among them (a searched CASE, IF): its type is the type they share.
260
- `typed_by`: its type follows an argument's (`ArgumentTyping`)."""
261
-
262
- arguments: tuple[ScalarExpr, ...]
263
- description: str
264
- typing: ValueTyping | None = None
265
- results: tuple[int, ...] | None = None
266
- typed_by: ArgumentTyping | None = None
267
-
268
489
 
269
490
  class Count(ScalarExpr):
270
491
  """`count(*)` or `count(...)`: never NULL, even over no rows; its value is
@@ -455,7 +676,7 @@ def determinants(expression: ScalarExpr) -> tuple[OutputColumn, ...] | None:
455
676
  case OpaqueExpression() | Count() | AnyAggregate() | Accumulation():
456
677
  return None
457
678
  case (
458
- Constant() | NullLiteral() | Call() | OpaquePureFunction() | Coalesce() | SimpleCase() | Elements() | Equality()
679
+ Constant() | NullLiteral() | Call() | Coalesce() | SimpleCase() | Elements() | Equality()
459
680
  | NullSafeEquality() | InList() | IsNull() | IsNotNull() | And() | Or()
460
681
  ):
461
682
  found: dict[OutputColumn, None] = {}
@@ -470,34 +691,6 @@ def determinants(expression: ScalarExpr) -> tuple[OutputColumn, ...] | None:
470
691
  assert_never(expression)
471
692
 
472
693
 
473
- def injective_input(expression: ScalarExpr) -> OutputColumn | None:
474
- """The one column `expression` is a one-to-one function of, given that the
475
- column is an integer or decimal: the column itself, or an injective
476
- Builtin of such an expression and integer or decimal literals."""
477
- expression = expression.closed
478
- match expression:
479
- case ColumnRef(column=column):
480
- return column
481
- case Call(injective_argument=ScalarExpr() as argument):
482
- return injective_input(argument)
483
- case (
484
- Call() | Constant() | NullLiteral() | Coalesce() | SimpleCase() | OpaquePureFunction() | OpaqueExpression()
485
- | Count() | AnyAggregate() | Accumulation() | Elements() | Equality() | NullSafeEquality() | InList() | IsNull() | IsNotNull() | And() | Or()
486
- ):
487
- return None
488
- case _:
489
- assert_never(expression)
490
-
491
-
492
- def _exact_literal(expression: ScalarExpr) -> bool:
493
- """An integer or decimal literal: not an exponent form, which is a double."""
494
- match expression:
495
- case Constant(value=LiteralValue(type="numeric", text=text)):
496
- return "e" not in text
497
- case _:
498
- return False
499
-
500
-
501
694
  def total(expression: ScalarExpr) -> bool:
502
695
  """Whether `expression` is non-null whenever every column it reads is: a
503
696
  column, a literal, `count(...)`, the IS family, a Builtin total in its
@@ -518,7 +711,7 @@ def total(expression: ScalarExpr) -> bool:
518
711
  case Coalesce(arguments=arguments):
519
712
  return any(total(argument) for argument in arguments)
520
713
  case (
521
- Call() | NullLiteral() | SimpleCase() | OpaquePureFunction() | OpaqueExpression() | AnyAggregate() | Accumulation() | Elements()
714
+ Call() | NullLiteral() | SimpleCase() | OpaqueExpression() | AnyAggregate() | Accumulation() | Elements()
522
715
  | Equality() | InList() | And() | Or()
523
716
  ):
524
717
  return False
@@ -549,7 +742,7 @@ def strict_inputs(expression: ScalarExpr) -> tuple[OutputColumn, ...]:
549
742
  rest = [strict_inputs(other) for other in others]
550
743
  return tuple(column for column in strict_inputs(first) if all(column in columns for columns in rest))
551
744
  case (
552
- And() | Or() | Constant() | NullLiteral() | Coalesce() | SimpleCase() | OpaquePureFunction() | OpaqueExpression()
745
+ And() | Or() | Constant() | NullLiteral() | Coalesce() | SimpleCase() | OpaqueExpression()
553
746
  | Count() | AnyAggregate() | Accumulation() | Elements() | IsNull() | IsNotNull() | NullSafeEquality()
554
747
  ):
555
748
  return ()
@@ -563,7 +756,7 @@ def strict_inputs(expression: ScalarExpr) -> tuple[OutputColumn, ...]:
563
756
  # it. tests/test_ir_unions.py checks these stay in sync with the subclasses,
564
757
  # which makes `ScalarExpr.closed` and `RelationExpr.closed` sound.
565
758
  type AnyScalar = (
566
- ColumnRef | Constant | NullLiteral | Coalesce | SimpleCase | Call | OpaquePureFunction | OpaqueExpression
759
+ ColumnRef | Constant | NullLiteral | Coalesce | SimpleCase | Call | OpaqueExpression
567
760
  | Count | AnyAggregate | Accumulation | Elements | Equality | NullSafeEquality | InList | IsNull | IsNotNull | And | Or
568
761
  )
569
762
 
sqlassert/main.py CHANGED
@@ -15,18 +15,16 @@ if TYPE_CHECKING:
15
15
  DEFAULT_DIALECT = "duckdb"
16
16
 
17
17
 
18
- def analyze(sql: str, *, dialect: str = DEFAULT_DIALECT, trust_unenforced_keys: bool = True) -> Report:
18
+ def analyze(sql: str, *, dialect: str = DEFAULT_DIALECT) -> Report:
19
19
  """Prove the Unique Join Assertions and Unique Set Assertions in one SQL Program.
20
20
 
21
21
  Pure: the Program is the only source of Knowledge. `analyze_database`
22
22
  adds a database catalog. Where a catalog would have helped (a table with
23
23
  no `CREATE`, a column only a catalog can resolve), the Report warns.
24
- `trust_unenforced_keys` (on by default) makes the keys the dialect does
25
- not enforce Property Declarations, as `RELY` does; off, they are ignored
26
- with an `unenforced-constraint` warning (`docs/dialects.md`).
24
+ Every declared constraint is Knowledge, enforced or not (ADR 0012).
27
25
  """
28
26
  sql_parser = SqlParser(dialect)
29
- ir_parser = IrParser(dialect, trust_unenforced_keys)
27
+ ir_parser = IrParser(dialect)
30
28
 
31
29
  ast = sql_parser.parse(sql)
32
30
  conversion = ir_parser.parse(ast)
@@ -35,17 +33,16 @@ def analyze(sql: str, *, dialect: str = DEFAULT_DIALECT, trust_unenforced_keys:
35
33
 
36
34
 
37
35
  def analyze_database(
38
- sql: str, fetcher: DatabaseKnowledgeFetcher, *, dialect: str = DEFAULT_DIALECT, trust_unenforced_keys: bool = True,
36
+ sql: str, fetcher: DatabaseKnowledgeFetcher, *, dialect: str = DEFAULT_DIALECT,
39
37
  ) -> Report:
40
38
  """`analyze`, with the external Relations the Program reaches hydrated from a catalog.
41
39
 
42
40
  The fetcher reads catalog metadata only, never rows, and binds it to the
43
41
  final IR before the engine runs once. No connection warnings: a relation
44
- the catalog lacks is already a diagnostic. A catalog key the dialect does
45
- not enforce warns, unless `trust_unenforced_keys` declares it, and so do
46
- the SQL's own warnings (`diagnostics.SQL_WARNINGS`).
42
+ the catalog lacks is already a diagnostic. The SQL's own warnings stay
43
+ (`diagnostics.SQL_WARNINGS`).
47
44
  """
48
45
  ast = SqlParser(dialect).parse(sql)
49
- conversion, _ = fetcher.convert(ast, dialect=dialect, trust_unenforced_keys=trust_unenforced_keys)
46
+ conversion, _ = fetcher.convert(ast, dialect=dialect)
50
47
  diagnostics = ast.diagnostics + conversion.diagnostics
51
48
  return Engine().run(conversion.program, conversion.knowledge, diagnostics, conversion.warnings)
@@ -116,7 +116,7 @@ def _cause(leaf: Result, anchor: ir.OutputColumn | None, place: _Place) -> Step:
116
116
  (f"a CHECK ({subject.name} IN (...)) in {table}, or DECLARE ENUM({subject.name} IN (...)), states its values",))
117
117
  if isinstance(subject, ir.ScalarExpr) and leaf.reason == "Values of this expression are not enumerated":
118
118
  written = brief(subject.origin.detail)
119
- if isinstance(subject, ir.OpaqueExpression | ir.OpaquePureFunction):
119
+ if isinstance(subject, ir.OpaqueExpression) or isinstance(subject, ir.Call) and not subject.function.modelled:
120
120
  return Step(f"{written}: sqlassert does not model its values", False, place.origin, "sqlassert", "not-modelled")
121
121
  return Step(f"{written}: its values are not enumerated", False, place.origin, "sql", "computed-value",
122
122
  ("only literals, coalesce and CASE of enumerated values, and enumerated columns enumerate a value",))