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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. sqlassert/__init__.py +34 -9
  2. sqlassert/__main__.py +9 -0
  3. sqlassert/check.py +451 -0
  4. sqlassert/diagnostics.py +70 -0
  5. sqlassert/dialects.py +258 -0
  6. sqlassert/discovery/__init__.py +30 -0
  7. sqlassert/discovery/bigquery.py +71 -0
  8. sqlassert/discovery/databricks.py +18 -0
  9. sqlassert/discovery/duckdb.py +159 -0
  10. sqlassert/discovery/fetcher.py +418 -0
  11. sqlassert/discovery/information_schema.py +327 -0
  12. sqlassert/discovery/mysql.py +70 -0
  13. sqlassert/discovery/postgres.py +142 -0
  14. sqlassert/discovery/redshift.py +36 -0
  15. sqlassert/discovery/snowflake.py +63 -0
  16. sqlassert/discovery/trino.py +37 -0
  17. sqlassert/edits.py +240 -0
  18. sqlassert/hazards.py +574 -0
  19. sqlassert/ir/__init__.py +58 -0
  20. sqlassert/ir/convert.py +3509 -0
  21. sqlassert/ir/model.py +779 -0
  22. sqlassert/main.py +51 -0
  23. sqlassert/properties.py +121 -0
  24. sqlassert/provenance.py +73 -0
  25. sqlassert/python_engine.py +356 -0
  26. sqlassert/reporting.py +105 -0
  27. sqlassert/rewrites.py +1541 -0
  28. sqlassert/rules/STYLEGUIDE.md +19 -0
  29. sqlassert/rules/__init__.py +11 -0
  30. sqlassert/rules/column_set.py +34 -0
  31. sqlassert/rules/domain.py +472 -0
  32. sqlassert/rules/equality.py +442 -0
  33. sqlassert/rules/exactly_one.py +114 -0
  34. sqlassert/rules/foreign_key.py +319 -0
  35. sqlassert/rules/join_cardinality.py +116 -0
  36. sqlassert/rules/nullability.py +627 -0
  37. sqlassert/rules/uniqueness.py +904 -0
  38. sqlassert/sql_parse.py +1081 -0
  39. sqlassert/suggest.py +418 -0
  40. sqlassert-0.3.3.dist-info/METADATA +807 -0
  41. sqlassert-0.3.3.dist-info/RECORD +46 -0
  42. {sqlassert-0.1.2.dist-info → sqlassert-0.3.3.dist-info}/WHEEL +1 -1
  43. sqlassert-0.3.3.dist-info/entry_points.txt +2 -0
  44. sqlassert-0.3.3.dist-info/licenses/LICENSE +21 -0
  45. sqlassert-0.3.3.dist-info/top_level.txt +2 -0
  46. sqlassert_cli.py +130 -0
  47. sqlassert/unique.py +0 -605
  48. sqlassert-0.1.2.dist-info/METADATA +0 -173
  49. sqlassert-0.1.2.dist-info/RECORD +0 -6
  50. sqlassert-0.1.2.dist-info/top_level.txt +0 -1
sqlassert/ir/model.py ADDED
@@ -0,0 +1,779 @@
1
+ """Framework-independent relational intermediate representation.
2
+
3
+ The IR is an immutable semantic object graph. Nodes refer directly to other
4
+ nodes and carry no identifiers.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass, field, fields
10
+ from enum import Enum
11
+ from typing import TYPE_CHECKING, Literal, assert_never, cast, dataclass_transform
12
+
13
+ from sqlassert.provenance import AttachmentSite, Origin
14
+
15
+ if TYPE_CHECKING:
16
+ from sqlassert.properties import Property
17
+
18
+ type JoinKind = Literal["inner", "cross", "left", "right", "full", "semi", "anti"]
19
+ type SetOperator = Literal["union", "intersect", "except"]
20
+
21
+
22
+ @dataclass_transform(eq_default=False, frozen_default=True, kw_only_default=True)
23
+ class NodeMeta(type):
24
+ """Turn every Node subclass into the same kind of semantic value."""
25
+
26
+ _subclasses: list
27
+
28
+ def __new__(metaclass, name, bases, namespace, *, abstract: bool = False):
29
+ node_type = super().__new__(metaclass, name, bases, namespace)
30
+ node_type = dataclass(frozen=True, eq=False, kw_only=True)(node_type)
31
+ node_type.__ir_abstract__ = abstract
32
+ node_type._subclasses = []
33
+ if not abstract:
34
+ for base in node_type.__mro__[1:]:
35
+ match base:
36
+ case NodeMeta():
37
+ base._subclasses.append(node_type)
38
+ return node_type
39
+
40
+ def __call__(cls, *args, **kwargs):
41
+ if getattr(cls, "__ir_abstract__", False):
42
+ raise TypeError(f"cannot construct abstract IR node {cls.__name__}")
43
+ return super().__call__(*args, **kwargs)
44
+
45
+
46
+ class Node(metaclass=NodeMeta, abstract=True):
47
+ """An immutable semantic node with object-identity equality."""
48
+
49
+ origin: Origin
50
+
51
+
52
+ class ScalarExpr(Node, abstract=True):
53
+ """A scalar expression produced or consumed by a relational operation."""
54
+
55
+ @property
56
+ def closed(self) -> AnyScalar:
57
+ """This node as one of the concrete ScalarExprs, to match exhaustively."""
58
+ return cast(AnyScalar, self)
59
+
60
+
61
+ class OpaqueExpression(ScalarExpr):
62
+ """An expression nothing is known about: not even which columns its value
63
+ depends on. A user-defined or volatile function, an aggregate or window,
64
+ a subquery, or a column that does not resolve."""
65
+
66
+ description: str
67
+
68
+
69
+ @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.
73
+
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.
79
+
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.
84
+
85
+ A `rejecting` parameter makes the value never TRUE (FALSE or NULL)
86
+ whenever its argument is NULL, though perhaps not NULL: `x > ANY (...)`
87
+ is FALSE over no rows. A strict parameter is one too, so only one that
88
+ is not strict needs the flag; `()` when none does.
89
+
90
+ With `true_only_if_argument` the value is TRUE only where its one
91
+ argument is TRUE (`p IS TRUE`), so as a condition it rejects whatever
92
+ that argument would.
93
+
94
+ With `skips_null` the value is non-null whenever any argument is
95
+ (`greatest` where it ignores NULLs), and `total` is None.
96
+ """
97
+
98
+ name: str
99
+ strict: tuple[bool, ...]
100
+ total: tuple[bool, ...] | None
101
+ injective: bool
102
+ rejecting: tuple[bool, ...] = field(default=(), kw_only=True)
103
+ skips_null: bool = field(default=False, kw_only=True)
104
+ true_only_if_argument: bool = field(default=False, kw_only=True)
105
+
106
+ 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"
113
+ )
114
+
115
+ 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
123
+
124
+
125
+ @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)
141
+
142
+ def strict_flags(self, count: int) -> tuple[bool, ...]:
143
+ return self.strict + (self.repeated_strict,) * (count - len(self.strict))
144
+
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))
147
+
148
+
149
+ class Call(ScalarExpr):
150
+ """A Builtin applied to arguments: `n + 1`, `n > 0`, `CAST(n AS BIGINT)`, `NOT p`."""
151
+
152
+ function: Builtin
153
+ arguments: tuple[ScalarExpr, ...]
154
+ description: str
155
+
156
+ def __post_init__(self) -> None:
157
+ assert self.function.accepts(len(self.arguments)), f"{self.function.name} takes no {len(self.arguments)} arguments"
158
+
159
+ @property
160
+ def strict_arguments(self) -> tuple[ScalarExpr, ...]:
161
+ """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)
164
+
165
+ @property
166
+ def rejecting_arguments(self) -> tuple[ScalarExpr, ...]:
167
+ """The arguments whose NULL makes the value never TRUE: the strict ones
168
+ and the `rejecting` ones."""
169
+ flags = self.function.strict_flags(len(self.arguments))
170
+ rejecting = self.function.rejecting or (False,) * len(flags)
171
+ return tuple(argument for argument, strict, rejects in zip(self.arguments, flags, rejecting) if strict or rejects)
172
+
173
+ @property
174
+ def total_arguments(self) -> tuple[ScalarExpr, ...] | None:
175
+ """The arguments whose being non-null makes the value non-null (none:
176
+ never NULL), or None when the value may be NULL regardless."""
177
+ flags = self.function.total_flags(len(self.arguments))
178
+ return None if flags is None else tuple(argument for argument, total in zip(self.arguments, flags) if total)
179
+
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
+
199
+ class Count(ScalarExpr):
200
+ """`count(*)` or `count(...)`: never NULL, even over no rows; its value is
201
+ otherwise opaque."""
202
+
203
+ description: str
204
+
205
+
206
+ @dataclass(frozen=True)
207
+ class LiteralValue:
208
+ """A non-null SQL literal's value: its SQL type and canonical text.
209
+
210
+ `type` is "string", "numeric", or "boolean". Two values are the same only
211
+ when both match, so numeric 1 never collides with string '1'. A string's
212
+ text is its contents; a boolean's is TRUE or FALSE. A numeric literal's
213
+ text is its spelling, which carries its SQL type: an integer is written
214
+ without sign or leading zeros (`+007` is `7`), while a decimal keeps its
215
+ scale (`1.0` is not `1`) and an exponent form stays a double (`1e0` is
216
+ not `1`). Those differ in how a column is compared with them, so only
217
+ identical literals are the same value; whether distinct ones can equal one
218
+ value is a separate, conservative question (`rules/domain.py`).
219
+ """
220
+
221
+ type: Literal["string", "numeric", "boolean"]
222
+ text: str
223
+
224
+ def sql(self) -> str:
225
+ match self.type:
226
+ case "string":
227
+ return "'" + self.text.replace("'", "''") + "'"
228
+ case "numeric" | "boolean":
229
+ return self.text
230
+ case _:
231
+ assert_never(self.type)
232
+
233
+
234
+ class Constant(ScalarExpr):
235
+ """A non-null literal; `value` is None while its type is not modelled."""
236
+
237
+ value: LiteralValue | None = None
238
+
239
+
240
+ class NullLiteral(ScalarExpr):
241
+ """The NULL literal, kept apart from Constant so it is never taken as non-null."""
242
+
243
+
244
+ class Coalesce(ScalarExpr):
245
+ """The first non-null argument: `coalesce`, `ifnull`, and `nvl`."""
246
+
247
+ arguments: tuple[ScalarExpr, ...]
248
+
249
+
250
+ class SimpleCase(ScalarExpr):
251
+ """`CASE operand WHEN whens[i] THEN thens[i] ... ELSE default END`.
252
+
253
+ Each arm compares `operand = whens[i]`; a NULL operand matches none. A
254
+ missing ELSE is lowered as a NULL literal `default`.
255
+ """
256
+
257
+ operand: ScalarExpr
258
+ whens: tuple[ScalarExpr, ...]
259
+ thens: tuple[ScalarExpr, ...]
260
+ default: ScalarExpr
261
+
262
+
263
+ class AnyAggregate(ScalarExpr):
264
+ """An arbitrary value selected from the input rows of an aggregate group:
265
+ a column outside every aggregate that the grouping determines (constant
266
+ across the group), or `min` and `max`, which take one of its non-null values.
267
+
268
+ `empty` marks a group that may have no rows, where the value is NULL: an
269
+ aggregate grouped by nothing has one row even over no input rows, and one
270
+ with FILTER may see none of its group's rows."""
271
+
272
+ input: ScalarExpr
273
+ empty: bool = False
274
+
275
+
276
+ class Accumulation(ScalarExpr):
277
+ """An aggregate of a group's values of `input` that skips NULLs: `sum`
278
+ and `avg` where the dialect's `checked_sum` holds (never NULL over non-null
279
+ values: overflow raises, NaN and infinities are not NULL). NULL only
280
+ when no value is non-null, or when the group is `empty` (see
281
+ AnyAggregate); its value is otherwise opaque."""
282
+
283
+ input: ScalarExpr
284
+ empty: bool = False
285
+
286
+
287
+ class Elements(ScalarExpr):
288
+ """Every element of a composite `operand` (an ARRAY's elements, a ROW's
289
+ fields, a MAP's values, nested ones included) as one value, non-null when
290
+ each element is. Not a value SQL computes: a comparison of composites
291
+ takes one per composite operand as a non-strict argument, since
292
+ `ARRAY[1, NULL] <> ARRAY[1, NULL]` and `ROW(1, NULL) = ROW(1, NULL)` may be NULL."""
293
+
294
+ operand: ScalarExpr
295
+
296
+
297
+ class ColumnRef(ScalarExpr):
298
+ """A direct reference to an upstream relation expression's output."""
299
+
300
+ column: OutputColumn
301
+
302
+
303
+ class Equality(ScalarExpr):
304
+ """`left = right`. As a conjunct it holds only on rows where both sides are non-null.
305
+
306
+ `total` marks one that is non-null whenever both sides are: where a failed
307
+ implicit cast raises (`DialectSemantics.casts_raise`) and neither side is
308
+ a composite, which may hold a NULL element (`ROW(1, NULL) = ROW(1, NULL)`
309
+ is NULL)."""
310
+
311
+ left: ScalarExpr
312
+ right: ScalarExpr
313
+ total: bool = False
314
+
315
+
316
+ class NullSafeEquality(ScalarExpr):
317
+ """`left IS NOT DISTINCT FROM right`: never NULL, TRUE when both sides
318
+ are equal or both NULL.
319
+
320
+ `rejects` marks one where a non-null side stays non-null as it is
321
+ compared, so a TRUE comparison makes the other side non-null too: where a
322
+ failed implicit cast raises (in Hive `n <=> 'x'` is
323
+ `n IS NULL`) and neither side is a composite."""
324
+
325
+ left: ScalarExpr
326
+ right: ScalarExpr
327
+ rejects: bool = False
328
+
329
+
330
+ class InList(ScalarExpr):
331
+ """`operand IN (values...)` over a list of values, not a subquery."""
332
+
333
+ operand: ScalarExpr
334
+ values: tuple[ScalarExpr, ...]
335
+
336
+
337
+ class IsNull(ScalarExpr):
338
+ """`operand IS NULL`."""
339
+
340
+ operand: ScalarExpr
341
+
342
+
343
+ class IsNotNull(ScalarExpr):
344
+ """`operand IS NOT NULL`."""
345
+
346
+ operand: ScalarExpr
347
+
348
+
349
+ class And(ScalarExpr):
350
+ """`p AND q ...`, flattened: TRUE when every part is."""
351
+
352
+ parts: tuple[ScalarExpr, ...]
353
+
354
+
355
+ class Or(ScalarExpr):
356
+ """`p OR q ...`, flattened: TRUE when some part is."""
357
+
358
+ parts: tuple[ScalarExpr, ...]
359
+
360
+
361
+ def conjuncts(predicate: ScalarExpr | None) -> tuple[ScalarExpr, ...]:
362
+ """The parts of `predicate`'s top-level AND; none for no predicate."""
363
+ match predicate:
364
+ case None:
365
+ return ()
366
+ case And(parts=parts):
367
+ return parts
368
+ case _:
369
+ return (predicate,)
370
+
371
+
372
+ def determinants(expression: ScalarExpr) -> tuple[OutputColumn, ...] | None:
373
+ """The columns `expression` is a pure function of, in order of first use,
374
+ or None when it is not one of any: its value may depend on other rows, on
375
+ state, or on nothing known (Paulley §3.1.4)."""
376
+ expression = expression.closed
377
+ match expression:
378
+ case ColumnRef(column=column):
379
+ return (column,)
380
+ case OpaqueExpression() | Count() | AnyAggregate() | Accumulation():
381
+ return None
382
+ case (
383
+ Constant() | NullLiteral() | Call() | OpaquePureFunction() | Coalesce() | SimpleCase() | Elements() | Equality()
384
+ | NullSafeEquality() | InList() | IsNull() | IsNotNull() | And() | Or()
385
+ ):
386
+ found: dict[OutputColumn, None] = {}
387
+ for child in children(expression):
388
+ assert isinstance(child, ScalarExpr)
389
+ inputs = determinants(child)
390
+ if inputs is None:
391
+ return None
392
+ found.update(dict.fromkeys(inputs))
393
+ return tuple(found)
394
+ case _:
395
+ assert_never(expression)
396
+
397
+
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
+ def total(expression: ScalarExpr) -> bool:
427
+ """Whether `expression` is non-null whenever every column it reads is: a
428
+ column, a literal, `count(...)`, the IS family, a Builtin total in its
429
+ arguments over total ones, a total equality of total sides, or a coalesce
430
+ or a Builtin that skips NULLs with one total argument. NULL, CASE (a
431
+ missed WHEN), IN, AND, OR (not inferred), and unmodelled functions may be
432
+ NULL on non-null columns."""
433
+ expression = expression.closed
434
+ match expression:
435
+ case ColumnRef() | Constant() | Count() | IsNull() | IsNotNull() | NullSafeEquality():
436
+ return True
437
+ case Call(function=Builtin(skips_null=True), arguments=arguments):
438
+ return any(total(argument) for argument in arguments)
439
+ case Call(total_arguments=tuple() as arguments):
440
+ return all(total(argument) for argument in arguments)
441
+ case Equality(total=True, left=left, right=right):
442
+ return total(left) and total(right)
443
+ case Coalesce(arguments=arguments):
444
+ return any(total(argument) for argument in arguments)
445
+ case (
446
+ Call() | NullLiteral() | SimpleCase() | OpaquePureFunction() | OpaqueExpression() | AnyAggregate() | Accumulation() | Elements()
447
+ | Equality() | InList() | And() | Or()
448
+ ):
449
+ return False
450
+ case _:
451
+ assert_never(expression)
452
+
453
+
454
+ def strict_inputs(expression: ScalarExpr) -> tuple[OutputColumn, ...]:
455
+ """The columns whose NULL makes `expression` NULL, in order of first use.
456
+
457
+ A Builtin passes on its strict arguments'; `=` both sides'; `IN (...)` its
458
+ operand's (`1 IN (1, NULL)` is TRUE); AND and OR only a column every part
459
+ is strict in (`NULL OR TRUE` is TRUE). Coalesce, CASE, the IS family
460
+ (IS NOT DISTINCT FROM included) and
461
+ unmodelled functions may turn NULL into a value; a literal, `count(...)`,
462
+ an opaque expression or an aggregate's value has no column of its own."""
463
+ expression = expression.closed
464
+ match expression:
465
+ case ColumnRef(column=column):
466
+ return (column,)
467
+ case Call(strict_arguments=arguments):
468
+ return tuple(dict.fromkeys(column for argument in arguments for column in strict_inputs(argument)))
469
+ case Equality(left=left, right=right):
470
+ return tuple(dict.fromkeys((*strict_inputs(left), *strict_inputs(right))))
471
+ case InList(operand=operand):
472
+ return strict_inputs(operand)
473
+ case And(parts=(first, *others)) | Or(parts=(first, *others)):
474
+ rest = [strict_inputs(other) for other in others]
475
+ return tuple(column for column in strict_inputs(first) if all(column in columns for columns in rest))
476
+ case (
477
+ And() | Or() | Constant() | NullLiteral() | Coalesce() | SimpleCase() | OpaquePureFunction() | OpaqueExpression()
478
+ | Count() | AnyAggregate() | Accumulation() | Elements() | IsNull() | IsNotNull() | NullSafeEquality()
479
+ ):
480
+ return ()
481
+ case _:
482
+ assert_never(expression)
483
+
484
+
485
+ # Closed unions of every concrete ScalarExpr and RelationExpr, for an
486
+ # exhaustive `match` ending in `assert_never`. Python has no sealed classes, so
487
+ # a type checker treats a base class as open and cannot prove a match covers
488
+ # it. tests/test_ir_unions.py checks these stay in sync with the subclasses,
489
+ # which makes `ScalarExpr.closed` and `RelationExpr.closed` sound.
490
+ type AnyScalar = (
491
+ ColumnRef | Constant | NullLiteral | Coalesce | SimpleCase | Call | OpaquePureFunction | OpaqueExpression
492
+ | Count | AnyAggregate | Accumulation | Elements | Equality | NullSafeEquality | InList | IsNull | IsNotNull | And | Or
493
+ )
494
+
495
+
496
+ class OutputColumn(Node):
497
+ """One named output of one relational stage and the expression producing it.
498
+
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.
510
+ """
511
+
512
+ name: str
513
+ 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
519
+
520
+ def get_relation(self, program: Program) -> RelationExpr:
521
+ """The one relation in ``program`` whose output includes this column."""
522
+ relation = program.column_to_parent_relation_index.get(self)
523
+ assert relation is not None, f"output column {self.name} has no parent relation in this program"
524
+ return relation
525
+
526
+
527
+ class RelationExpr(Node, abstract=True):
528
+ """A relation-producing expression with an explicit output schema."""
529
+
530
+ output_columns: tuple[OutputColumn, ...]
531
+ is_schema_complete: bool = False
532
+
533
+ @property
534
+ def closed(self) -> AnyRelation:
535
+ """This node as one of the concrete RelationExprs, to match exhaustively."""
536
+ return cast(AnyRelation, self)
537
+
538
+
539
+ class RelationRole(Enum):
540
+ TABLE = "table"
541
+ VIEW = "view"
542
+ CTE = "cte"
543
+
544
+
545
+ class NamedRelation(RelationExpr):
546
+ """A table, view, or CTE declaration shared by every reference to it."""
547
+
548
+ name: str
549
+ role: RelationRole
550
+ body: RelationExpr | None = None
551
+
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
+
557
+ class Alias(RelationExpr):
558
+ """One occurrence of a relation expression in a query scope."""
559
+
560
+ source: RelationExpr
561
+ name: str
562
+
563
+
564
+ class Join(RelationExpr):
565
+ """A join and its ON (or USING) condition; None for a cross join.
566
+
567
+ A condition is `And` and `Or` over the recognized `Equality`,
568
+ `NullSafeEquality`, `InList`, `IsNull`, and `IsNotNull`; anything else is an opaque scalar expression, so
569
+ the predicate is the whole condition.
570
+ """
571
+
572
+ kind: JoinKind
573
+ left: RelationExpr
574
+ right: RelationExpr
575
+ predicate: ScalarExpr | None = None
576
+ # A left join a scalar subquery lowers to: its right input is the
577
+ # subquery's body, and each left row matches at most one right row, or
578
+ # the query fails (more than one row is a runtime error).
579
+ scalar_subquery: bool = False
580
+
581
+ @property
582
+ def conjuncts(self) -> tuple[ScalarExpr, ...]:
583
+ return conjuncts(self.predicate)
584
+
585
+
586
+ class Filter(RelationExpr):
587
+ """A WHERE clause, its condition lowered as in `Join`."""
588
+
589
+ input: RelationExpr
590
+ predicate: ScalarExpr | None = None
591
+
592
+ @property
593
+ def conjuncts(self) -> tuple[ScalarExpr, ...]:
594
+ return conjuncts(self.predicate)
595
+
596
+
597
+ class Project(RelationExpr):
598
+ input: RelationExpr
599
+
600
+
601
+ class Limit(RelationExpr):
602
+ """A row subset selected by LIMIT/FETCH or OFFSET; count is a known hard bound, if any."""
603
+
604
+ input: RelationExpr
605
+ count: int | None = None
606
+
607
+
608
+ class AggregateCall(Node):
609
+ """One aggregate function call in a grouped Select's list or its HAVING:
610
+ its SQL, and its arguments lowered against the Aggregate's input (none
611
+ for `count(*)`). Only hazards and rewrites read it; an aggregate's value
612
+ is opaque to every proof."""
613
+
614
+ description: str
615
+ arguments: tuple[ScalarExpr, ...]
616
+
617
+
618
+ class Aggregate(RelationExpr):
619
+ input: RelationExpr
620
+ grouping_outputs: tuple[OutputColumn, ...]
621
+ calls: tuple[AggregateCall, ...] = ()
622
+
623
+
624
+ class Distinct(RelationExpr):
625
+ input: RelationExpr
626
+
627
+
628
+ class SetOperation(RelationExpr):
629
+ """UNION, INTERSECT, or EXCEPT. Output columns refer to the left input;
630
+ `arms` pairs each with the right input's column at its position."""
631
+
632
+ operator: SetOperator
633
+ left: RelationExpr
634
+ right: RelationExpr
635
+ distinct: bool = True
636
+ by_name: bool = False
637
+
638
+ def arms(self, column: OutputColumn) -> tuple[OutputColumn, OutputColumn] | None:
639
+ """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):
643
+ return None
644
+ position = self.output_columns.index(column)
645
+ return self.left.output_columns[position], self.right.output_columns[position]
646
+
647
+
648
+ class QualifyByPartition(RelationExpr):
649
+ """One row per partition: ``QUALIFY row_number() OVER (PARTITION BY ...) = 1`` or ``DISTINCT ON (...)``."""
650
+
651
+ input: RelationExpr
652
+ partition_outputs: tuple[OutputColumn, ...]
653
+ ordering: tuple[ScalarExpr, ...] = ()
654
+
655
+
656
+ class OpaqueRelation(RelationExpr):
657
+ description: str
658
+
659
+
660
+ class RecursiveRelation(OpaqueRelation):
661
+ """An explicit unsupported recursive reference, represented without a cycle."""
662
+
663
+ relation_name: str
664
+
665
+
666
+ type AnyRelation = (
667
+ NamedRelation | Alias | Join | Filter | Project | Limit | Aggregate | Distinct | SetOperation
668
+ | QualifyByPartition | OpaqueRelation | RecursiveRelation
669
+ )
670
+
671
+
672
+ class Assertion(Node):
673
+ """A request to prove one Property. For now its just a wrapper around a Property, but it could be extended with metadata in the future"""
674
+
675
+ property: Property
676
+
677
+
678
+ @dataclass(frozen=True)
679
+ class Program:
680
+ named_relations: tuple[NamedRelation, ...] = () # First pass collects all named relations so that we can reference them
681
+ root: RelationExpr | None = None # The root of the query tree, which is the entry point for the engine to start reasoning
682
+ assertions: tuple[Assertion, ...] = () # The properties that the engine should attempt to prove
683
+ declarations: tuple[Property, ...] = () # The properties that the engine should assume to be true
684
+ # Every JOIN, Select Expression, and simple CASE a marker can attach to, with
685
+ # the Join, the relation the Select produces, or the lowered CASE.
686
+ 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
+ # Each node standing for a construct sqlassert does not support yet (an
699
+ # opaque relation or value), with what it is: an assertion whose proof
700
+ # reaches one says so when it stays UNKNOWN.
701
+ unsupported: tuple[tuple[Node, str], ...] = ()
702
+ column_to_parent_relation_index: dict[OutputColumn, RelationExpr] = field(init=False, repr=False, compare=False)
703
+
704
+ def __post_init__(self) -> None:
705
+ # Every stage mints its own output columns, so each column has exactly one parent relation.
706
+ index: dict[OutputColumn, RelationExpr] = {}
707
+ for relation in self.relations():
708
+ for column in relation.output_columns:
709
+ parent = index.setdefault(column, relation)
710
+ if parent is not relation:
711
+ raise ValueError(
712
+ f"output column {column.name} belongs to both {type(parent).__name__} and {type(relation).__name__}"
713
+ )
714
+ object.__setattr__(self, "column_to_parent_relation_index", index)
715
+ self._check_relations_read_once()
716
+
717
+ def _check_relations_read_once(self) -> None:
718
+ """Apart from Named Relations, the relations form a tree: a subquery
719
+ or other relation is the input of one relation, read once, and a
720
+ Named Relation is read only through an Alias, one per occurrence.
721
+ Analyses rely on it: two columns reaching one column through the
722
+ same Aliases reach it on the same row (`nullability._row_lineage`)."""
723
+ readers: dict[RelationExpr, RelationExpr] = {}
724
+ for relation in self.relations():
725
+ for child in children(relation):
726
+ match child:
727
+ case NamedRelation() if not isinstance(relation, Alias):
728
+ raise ValueError(f"named relation {child.name} is read by a {type(relation).__name__}, not an Alias")
729
+ case NamedRelation():
730
+ pass # Each occurrence has its own Alias.
731
+ case RelationExpr() if child in readers:
732
+ raise ValueError(
733
+ f"{type(child).__name__} is read twice, by {type(readers[child]).__name__} and {type(relation).__name__}"
734
+ )
735
+ case RelationExpr():
736
+ readers[child] = relation
737
+ case _:
738
+ pass # Scalar expressions and columns hold no relation.
739
+
740
+ def nodes(self) -> tuple[Node, ...]:
741
+ """Every node reachable from the program, each once."""
742
+ nodes: dict[Node, None] = {}
743
+
744
+ def visit(node: Node) -> None:
745
+ if node in nodes:
746
+ return
747
+ nodes[node] = None
748
+ for child in children(node):
749
+ visit(child)
750
+
751
+ for node in (*self.named_relations, *self.assertions):
752
+ visit(node)
753
+ if self.root is not None:
754
+ visit(self.root)
755
+ return tuple(nodes)
756
+
757
+ def relations(self) -> tuple[RelationExpr, ...]:
758
+ """Every relation reachable from the program, each once."""
759
+ return tuple(node for node in self.nodes() if isinstance(node, RelationExpr))
760
+
761
+ def relation_of(self, columns: frozenset[OutputColumn]) -> RelationExpr | None:
762
+ """The parent relation shared by every column, or None when they span several or none."""
763
+ parents = {self.column_to_parent_relation_index.get(column) for column in columns}
764
+ if len(parents) != 1 or None in parents:
765
+ return None
766
+ parent, = parents
767
+ return parent
768
+
769
+
770
+ def children(node: Node) -> tuple[Node, ...]:
771
+ """Direct semantic references held by ``node``, in dataclass field order."""
772
+ found: list[Node] = []
773
+ for node_field in fields(node):
774
+ value = getattr(node, node_field.name)
775
+ if isinstance(value, Node):
776
+ found.append(value)
777
+ elif isinstance(value, tuple):
778
+ found.extend(item for item in value if isinstance(item, Node))
779
+ return tuple(found)