sqlassert 0.3.1__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.
- sqlassert/__main__.py +2 -131
- sqlassert/check.py +10 -3
- sqlassert/diagnostics.py +19 -6
- sqlassert/dialects.py +69 -22
- sqlassert/discovery/duckdb.py +12 -16
- sqlassert/discovery/fetcher.py +45 -29
- sqlassert/discovery/information_schema.py +4 -3
- sqlassert/discovery/postgres.py +6 -7
- sqlassert/edits.py +240 -0
- sqlassert/hazards.py +574 -0
- sqlassert/ir/__init__.py +3 -1
- sqlassert/ir/convert.py +1315 -183
- sqlassert/ir/model.py +128 -25
- sqlassert/main.py +3 -9
- sqlassert/python_engine.py +63 -6
- sqlassert/reporting.py +3 -0
- sqlassert/rewrites.py +1541 -0
- sqlassert/rules/domain.py +117 -21
- sqlassert/rules/equality.py +238 -29
- sqlassert/rules/exactly_one.py +40 -1
- sqlassert/rules/foreign_key.py +7 -4
- sqlassert/rules/join_cardinality.py +33 -11
- sqlassert/rules/nullability.py +239 -30
- sqlassert/rules/uniqueness.py +355 -52
- sqlassert/sql_parse.py +196 -89
- sqlassert/suggest.py +127 -48
- {sqlassert-0.3.1.dist-info → sqlassert-0.3.3.dist-info}/METADATA +121 -39
- sqlassert-0.3.3.dist-info/RECORD +46 -0
- sqlassert-0.3.3.dist-info/entry_points.txt +2 -0
- sqlassert-0.3.3.dist-info/top_level.txt +2 -0
- sqlassert_cli.py +130 -0
- sqlassert/improvements.py +0 -528
- sqlassert/smells.py +0 -306
- sqlassert-0.3.1.dist-info/RECORD +0 -44
- sqlassert-0.3.1.dist-info/entry_points.txt +0 -2
- sqlassert-0.3.1.dist-info/top_level.txt +0 -1
- {sqlassert-0.3.1.dist-info → sqlassert-0.3.3.dist-info}/WHEEL +0 -0
- {sqlassert-0.3.1.dist-info → sqlassert-0.3.3.dist-info}/licenses/LICENSE +0 -0
sqlassert/ir/model.py
CHANGED
|
@@ -81,15 +81,33 @@ class Builtin:
|
|
|
81
81
|
integer or decimal literal, when that argument is an integer or decimal:
|
|
82
82
|
`a + 1`, `10 - a`, `-a`. Only where exact arithmetic raises an error on
|
|
83
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.
|
|
84
96
|
"""
|
|
85
97
|
|
|
86
98
|
name: str
|
|
87
99
|
strict: tuple[bool, ...]
|
|
88
100
|
total: tuple[bool, ...] | None
|
|
89
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)
|
|
90
105
|
|
|
91
106
|
def __post_init__(self) -> None:
|
|
92
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"
|
|
93
111
|
assert self.total is None or all(total for strict, total in zip(self.strict, self.total) if strict), (
|
|
94
112
|
f"{self.name}: a strict parameter is total"
|
|
95
113
|
)
|
|
@@ -144,6 +162,14 @@ class Call(ScalarExpr):
|
|
|
144
162
|
flags = self.function.strict_flags(len(self.arguments))
|
|
145
163
|
return tuple(argument for argument, strict in zip(self.arguments, flags) if strict)
|
|
146
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
|
+
|
|
147
173
|
@property
|
|
148
174
|
def total_arguments(self) -> tuple[ScalarExpr, ...] | None:
|
|
149
175
|
"""The arguments whose being non-null makes the value non-null (none:
|
|
@@ -164,7 +190,7 @@ class Call(ScalarExpr):
|
|
|
164
190
|
class OpaquePureFunction(ScalarExpr):
|
|
165
191
|
"""A built-in function or operator whose behaviour is not modelled: a pure
|
|
166
192
|
function of its arguments, and nothing else is known about it. Searched
|
|
167
|
-
CASE, `concat`,
|
|
193
|
+
CASE, and `concat`, `||` or `greatest` where the dialect's is not modelled."""
|
|
168
194
|
|
|
169
195
|
arguments: tuple[ScalarExpr, ...]
|
|
170
196
|
description: str
|
|
@@ -235,9 +261,27 @@ class SimpleCase(ScalarExpr):
|
|
|
235
261
|
|
|
236
262
|
|
|
237
263
|
class AnyAggregate(ScalarExpr):
|
|
238
|
-
"""An arbitrary value selected from the input rows of an aggregate group
|
|
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."""
|
|
239
282
|
|
|
240
283
|
input: ScalarExpr
|
|
284
|
+
empty: bool = False
|
|
241
285
|
|
|
242
286
|
|
|
243
287
|
class Elements(ScalarExpr):
|
|
@@ -257,10 +301,30 @@ class ColumnRef(ScalarExpr):
|
|
|
257
301
|
|
|
258
302
|
|
|
259
303
|
class Equality(ScalarExpr):
|
|
260
|
-
"""`left = right`. As a conjunct it holds only on rows where both sides are non-null.
|
|
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)."""
|
|
261
310
|
|
|
262
311
|
left: ScalarExpr
|
|
263
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
|
|
264
328
|
|
|
265
329
|
|
|
266
330
|
class InList(ScalarExpr):
|
|
@@ -313,9 +377,12 @@ def determinants(expression: ScalarExpr) -> tuple[OutputColumn, ...] | None:
|
|
|
313
377
|
match expression:
|
|
314
378
|
case ColumnRef(column=column):
|
|
315
379
|
return (column,)
|
|
316
|
-
case OpaqueExpression() | Count() | AnyAggregate():
|
|
380
|
+
case OpaqueExpression() | Count() | AnyAggregate() | Accumulation():
|
|
317
381
|
return None
|
|
318
|
-
case
|
|
382
|
+
case (
|
|
383
|
+
Constant() | NullLiteral() | Call() | OpaquePureFunction() | Coalesce() | SimpleCase() | Elements() | Equality()
|
|
384
|
+
| NullSafeEquality() | InList() | IsNull() | IsNotNull() | And() | Or()
|
|
385
|
+
):
|
|
319
386
|
found: dict[OutputColumn, None] = {}
|
|
320
387
|
for child in children(expression):
|
|
321
388
|
assert isinstance(child, ScalarExpr)
|
|
@@ -340,7 +407,7 @@ def injective_input(expression: ScalarExpr) -> OutputColumn | None:
|
|
|
340
407
|
return injective_input(argument)
|
|
341
408
|
case (
|
|
342
409
|
Call() | Constant() | NullLiteral() | Coalesce() | SimpleCase() | OpaquePureFunction() | OpaqueExpression()
|
|
343
|
-
| Count() | AnyAggregate() | Elements() | Equality() | InList() | IsNull() | IsNotNull() | And() | Or()
|
|
410
|
+
| Count() | AnyAggregate() | Accumulation() | Elements() | Equality() | NullSafeEquality() | InList() | IsNull() | IsNotNull() | And() | Or()
|
|
344
411
|
):
|
|
345
412
|
return None
|
|
346
413
|
case _:
|
|
@@ -358,21 +425,26 @@ def _exact_literal(expression: ScalarExpr) -> bool:
|
|
|
358
425
|
|
|
359
426
|
def total(expression: ScalarExpr) -> bool:
|
|
360
427
|
"""Whether `expression` is non-null whenever every column it reads is: a
|
|
361
|
-
column, a literal, `count(...)`, a Builtin total in its
|
|
362
|
-
total ones,
|
|
363
|
-
|
|
364
|
-
|
|
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."""
|
|
365
433
|
expression = expression.closed
|
|
366
434
|
match expression:
|
|
367
|
-
case ColumnRef() | Constant() | Count():
|
|
435
|
+
case ColumnRef() | Constant() | Count() | IsNull() | IsNotNull() | NullSafeEquality():
|
|
368
436
|
return True
|
|
437
|
+
case Call(function=Builtin(skips_null=True), arguments=arguments):
|
|
438
|
+
return any(total(argument) for argument in arguments)
|
|
369
439
|
case Call(total_arguments=tuple() as arguments):
|
|
370
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)
|
|
371
443
|
case Coalesce(arguments=arguments):
|
|
372
444
|
return any(total(argument) for argument in arguments)
|
|
373
445
|
case (
|
|
374
|
-
Call() | NullLiteral() | SimpleCase() | OpaquePureFunction() | OpaqueExpression() | AnyAggregate() | Elements()
|
|
375
|
-
| Equality() | InList() |
|
|
446
|
+
Call() | NullLiteral() | SimpleCase() | OpaquePureFunction() | OpaqueExpression() | AnyAggregate() | Accumulation() | Elements()
|
|
447
|
+
| Equality() | InList() | And() | Or()
|
|
376
448
|
):
|
|
377
449
|
return False
|
|
378
450
|
case _:
|
|
@@ -384,7 +456,8 @@ def strict_inputs(expression: ScalarExpr) -> tuple[OutputColumn, ...]:
|
|
|
384
456
|
|
|
385
457
|
A Builtin passes on its strict arguments'; `=` both sides'; `IN (...)` its
|
|
386
458
|
operand's (`1 IN (1, NULL)` is TRUE); AND and OR only a column every part
|
|
387
|
-
is strict in (`NULL OR TRUE` is TRUE). Coalesce, CASE, the IS family
|
|
459
|
+
is strict in (`NULL OR TRUE` is TRUE). Coalesce, CASE, the IS family
|
|
460
|
+
(IS NOT DISTINCT FROM included) and
|
|
388
461
|
unmodelled functions may turn NULL into a value; a literal, `count(...)`,
|
|
389
462
|
an opaque expression or an aggregate's value has no column of its own."""
|
|
390
463
|
expression = expression.closed
|
|
@@ -402,7 +475,7 @@ def strict_inputs(expression: ScalarExpr) -> tuple[OutputColumn, ...]:
|
|
|
402
475
|
return tuple(column for column in strict_inputs(first) if all(column in columns for columns in rest))
|
|
403
476
|
case (
|
|
404
477
|
And() | Or() | Constant() | NullLiteral() | Coalesce() | SimpleCase() | OpaquePureFunction() | OpaqueExpression()
|
|
405
|
-
| Count() | AnyAggregate() | Elements() | IsNull() | IsNotNull()
|
|
478
|
+
| Count() | AnyAggregate() | Accumulation() | Elements() | IsNull() | IsNotNull() | NullSafeEquality()
|
|
406
479
|
):
|
|
407
480
|
return ()
|
|
408
481
|
case _:
|
|
@@ -416,7 +489,7 @@ def strict_inputs(expression: ScalarExpr) -> tuple[OutputColumn, ...]:
|
|
|
416
489
|
# which makes `ScalarExpr.closed` and `RelationExpr.closed` sound.
|
|
417
490
|
type AnyScalar = (
|
|
418
491
|
ColumnRef | Constant | NullLiteral | Coalesce | SimpleCase | Call | OpaquePureFunction | OpaqueExpression
|
|
419
|
-
| Count | AnyAggregate | Elements | Equality | InList | IsNull | IsNotNull | And | Or
|
|
492
|
+
| Count | AnyAggregate | Accumulation | Elements | Equality | NullSafeEquality | InList | IsNull | IsNotNull | And | Or
|
|
420
493
|
)
|
|
421
494
|
|
|
422
495
|
|
|
@@ -424,13 +497,14 @@ class OutputColumn(Node):
|
|
|
424
497
|
"""One named output of one relational stage and the expression producing it.
|
|
425
498
|
|
|
426
499
|
`binary_text` marks a table column declared as text compared by identity:
|
|
427
|
-
VARCHAR or TEXT
|
|
428
|
-
|
|
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.
|
|
429
503
|
|
|
430
504
|
`identity_comparison` marks a table column whose equal values are
|
|
431
505
|
identical: an integer, decimal, boolean, date, time, timestamp or UUID
|
|
432
506
|
type, or binary text. Not a float (`-0.0 = 0.0`), an interval, or text
|
|
433
|
-
under a collation.
|
|
507
|
+
under a case-insensitive default collation (MySQL's).
|
|
434
508
|
|
|
435
509
|
`exact_numeric` marks a table column declared as an integer or decimal.
|
|
436
510
|
"""
|
|
@@ -438,7 +512,7 @@ class OutputColumn(Node):
|
|
|
438
512
|
name: str
|
|
439
513
|
scalar_expr: ScalarExpr
|
|
440
514
|
binary_text: bool = False
|
|
441
|
-
# Declared SQL type where equality compares values without casts
|
|
515
|
+
# Declared SQL type where equality compares values without casts.
|
|
442
516
|
comparison_type: str | None = None
|
|
443
517
|
identity_comparison: bool = False
|
|
444
518
|
exact_numeric: bool = False
|
|
@@ -490,8 +564,8 @@ class Alias(RelationExpr):
|
|
|
490
564
|
class Join(RelationExpr):
|
|
491
565
|
"""A join and its ON (or USING) condition; None for a cross join.
|
|
492
566
|
|
|
493
|
-
A condition is `And` and `Or` over the recognized `Equality`,
|
|
494
|
-
`IsNull`, and `IsNotNull`; anything else is an opaque scalar expression, so
|
|
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
|
|
495
569
|
the predicate is the whole condition.
|
|
496
570
|
"""
|
|
497
571
|
|
|
@@ -532,9 +606,10 @@ class Limit(RelationExpr):
|
|
|
532
606
|
|
|
533
607
|
|
|
534
608
|
class AggregateCall(Node):
|
|
535
|
-
"""One aggregate function call in a grouped Select's list
|
|
536
|
-
arguments lowered against the Aggregate's input (none
|
|
537
|
-
Only
|
|
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."""
|
|
538
613
|
|
|
539
614
|
description: str
|
|
540
615
|
arguments: tuple[ScalarExpr, ...]
|
|
@@ -620,6 +695,10 @@ class Program:
|
|
|
620
695
|
# Each INTERSECT and EXCEPT, sited where its keyword follows its left
|
|
621
696
|
# input's last Select (no marker attaches there).
|
|
622
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], ...] = ()
|
|
623
702
|
column_to_parent_relation_index: dict[OutputColumn, RelationExpr] = field(init=False, repr=False, compare=False)
|
|
624
703
|
|
|
625
704
|
def __post_init__(self) -> None:
|
|
@@ -633,6 +712,30 @@ class Program:
|
|
|
633
712
|
f"output column {column.name} belongs to both {type(parent).__name__} and {type(relation).__name__}"
|
|
634
713
|
)
|
|
635
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.
|
|
636
739
|
|
|
637
740
|
def nodes(self) -> tuple[Node, ...]:
|
|
638
741
|
"""Every node reachable from the program, each once."""
|
sqlassert/main.py
CHANGED
|
@@ -2,10 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
-
from dataclasses import replace
|
|
6
5
|
from typing import TYPE_CHECKING
|
|
7
6
|
|
|
8
|
-
from sqlassert import diagnostics as diag
|
|
9
7
|
from sqlassert.ir.convert import IrParser
|
|
10
8
|
from sqlassert.python_engine import Engine
|
|
11
9
|
from sqlassert.reporting import Report
|
|
@@ -48,10 +46,6 @@ def analyze_database(
|
|
|
48
46
|
the SQL's own warnings (`diagnostics.SQL_WARNINGS`).
|
|
49
47
|
"""
|
|
50
48
|
ast = SqlParser(dialect).parse(sql)
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
program = replace(conversion.program, declarations=conversion.program.declarations + facts.declarations)
|
|
55
|
-
diagnostics = ast.diagnostics + hydration.diagnostics + conversion.diagnostics
|
|
56
|
-
warnings = (*facts.warnings, *(warning for warning in conversion.warnings if warning.code in diag.SQL_WARNINGS))
|
|
57
|
-
return Engine().run(program, conversion.knowledge + facts.knowledge, diagnostics, warnings)
|
|
49
|
+
conversion, _ = fetcher.convert(ast, dialect=dialect, trust_unenforced_keys=trust_unenforced_keys)
|
|
50
|
+
diagnostics = ast.diagnostics + conversion.diagnostics
|
|
51
|
+
return Engine().run(conversion.program, conversion.knowledge, diagnostics, conversion.warnings)
|
sqlassert/python_engine.py
CHANGED
|
@@ -13,7 +13,7 @@ from inspect import signature
|
|
|
13
13
|
from case_conversion import snake
|
|
14
14
|
|
|
15
15
|
from sqlassert import ir
|
|
16
|
-
from sqlassert.diagnostics import DUPLICATE_DECLARATION, Diagnostic
|
|
16
|
+
from sqlassert.diagnostics import ALWAYS_NULL_COLUMN, DUPLICATE_DECLARATION, UNSUPPORTED_CONSTRUCT, Diagnostic, quoted
|
|
17
17
|
from sqlassert.properties import Property
|
|
18
18
|
from sqlassert.reporting import ASSERTED_KINDS, AssertionReport, Outcome, RelationFacts, Report
|
|
19
19
|
|
|
@@ -141,9 +141,11 @@ class Stratum(IntEnum):
|
|
|
141
141
|
DAG, so this keeps the whole call graph acyclic: the memoized engine cannot
|
|
142
142
|
compute mutually recursive facts, which would need a fixpoint.
|
|
143
143
|
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
144
|
+
Comparisons come first: comparison types, directed lax equalities, and
|
|
145
|
+
the constants a predicate fixes, all read from conjuncts. Unique Joins
|
|
146
|
+
(and Exactly One Joins) follow, so a relation's Null Sources may use them.
|
|
147
|
+
Equality Groups follow Null Sources, which strengthen lax equalities;
|
|
148
|
+
dependencies also use Null Sources (a padded side's
|
|
147
149
|
dependencies hold only when the join cannot pad an agreeing row) and Unique
|
|
148
150
|
Joins; closure uses dependencies and non-nullness; Unique Sets and
|
|
149
151
|
Functional Dependency assertions are closure questions; Foreign Keys use
|
|
@@ -152,9 +154,10 @@ class Stratum(IntEnum):
|
|
|
152
154
|
with the analyzed SQL.
|
|
153
155
|
"""
|
|
154
156
|
|
|
155
|
-
|
|
157
|
+
COMPARISON = 5
|
|
156
158
|
UNIQUE_JOIN = 10
|
|
157
159
|
NON_NULL = 20
|
|
160
|
+
EQUALITY_GROUP = 25
|
|
158
161
|
FUNCTIONAL_DEPENDENCY = 30
|
|
159
162
|
CLOSURE = 40
|
|
160
163
|
UNIQUE_SET = 50
|
|
@@ -279,21 +282,75 @@ class Engine:
|
|
|
279
282
|
self, program: ir.Program, knowledge: tuple[Property, ...] = (), diagnostics: tuple[Diagnostic, ...] = (),
|
|
280
283
|
warnings: tuple[Diagnostic, ...] = (),
|
|
281
284
|
) -> Report:
|
|
285
|
+
from sqlassert.rules.domain import always_null_columns
|
|
282
286
|
from sqlassert.rules.uniqueness import minimal_keys
|
|
283
287
|
|
|
284
288
|
with self.session(program, knowledge) as arena:
|
|
285
289
|
assertions = []
|
|
290
|
+
always_null: set[ir.OutputColumn] = set()
|
|
286
291
|
for index, assertion in enumerate(program.assertions, 1):
|
|
287
292
|
evidence = arena.prove(assertion.property)
|
|
288
293
|
if any(diagnostic.code == DUPLICATE_DECLARATION for diagnostic in diagnostics):
|
|
289
294
|
evidence = evidence & unknown("Duplicate declarations prevent accepting a proof", assertion)
|
|
295
|
+
unsupported = None if evidence.value else _unsupported_reached(program, assertion.property)
|
|
290
296
|
assertions.append(AssertionReport(
|
|
291
297
|
f"assert_{index}", Outcome.PROVED if evidence.value else Outcome.UNKNOWN, assertion.origin,
|
|
292
|
-
ASSERTED_KINDS[type(assertion.property)], evidence,
|
|
298
|
+
ASSERTED_KINDS[type(assertion.property)], evidence, unsupported,
|
|
293
299
|
))
|
|
300
|
+
if evidence.value:
|
|
301
|
+
# NULL is exempt from the Property, so a column that is always NULL satisfies it: say so, once.
|
|
302
|
+
kind = ASSERTED_KINDS[type(assertion.property)].upper().replace("-", " ")
|
|
303
|
+
for column in always_null_columns(assertion.property):
|
|
304
|
+
if column not in always_null:
|
|
305
|
+
always_null.add(column)
|
|
306
|
+
warnings = (*warnings, Diagnostic(
|
|
307
|
+
ALWAYS_NULL_COLUMN, f"{quoted(column.name)} is always NULL, so this {kind} holds trivially: no non-null value of it is possible",
|
|
308
|
+
assertion.origin,
|
|
309
|
+
))
|
|
310
|
+
if unsupported is not None:
|
|
311
|
+
warnings = (*warnings, Diagnostic(
|
|
312
|
+
UNSUPPORTED_CONSTRUCT, f"{unsupported} is not supported by sqlassert yet, which may be why this assertion is UNKNOWN",
|
|
313
|
+
assertion.origin,
|
|
314
|
+
))
|
|
294
315
|
facts = {}
|
|
295
316
|
for relation in program.named_relations:
|
|
296
317
|
facts[relation.report_name.lower()] = tuple(
|
|
297
318
|
tuple(column.name for column in key) for key in minimal_keys(relation)
|
|
298
319
|
)
|
|
299
320
|
return Report(tuple(assertions), tuple(diagnostics), RelationFacts(facts), tuple(warnings))
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _unsupported_reached(program: ir.Program, property: Property) -> str | None:
|
|
324
|
+
"""The first construct sqlassert does not support yet that `property`'s
|
|
325
|
+
proof depends on: reached from its columns through the expressions that
|
|
326
|
+
compute them, and from their relations through those relations' inputs.
|
|
327
|
+
Sibling columns are not followed, so a window function beside an
|
|
328
|
+
asserted column is not blamed for it."""
|
|
329
|
+
unsupported = {id(node): construct for node, construct in program.unsupported}
|
|
330
|
+
if not unsupported:
|
|
331
|
+
return None
|
|
332
|
+
seen: set[int] = set()
|
|
333
|
+
pending: list[ir.Node] = []
|
|
334
|
+
for item in fields(property):
|
|
335
|
+
value = getattr(property, item.name)
|
|
336
|
+
pending.extend(value if isinstance(value, frozenset | tuple) else (value,))
|
|
337
|
+
while pending:
|
|
338
|
+
node = pending.pop()
|
|
339
|
+
if not isinstance(node, ir.Node) or id(node) in seen:
|
|
340
|
+
continue
|
|
341
|
+
seen.add(id(node))
|
|
342
|
+
if id(node) in unsupported:
|
|
343
|
+
return unsupported[id(node)]
|
|
344
|
+
match node:
|
|
345
|
+
case ir.OutputColumn():
|
|
346
|
+
pending.append(node.scalar_expr)
|
|
347
|
+
pending.append(node.get_relation(program))
|
|
348
|
+
case ir.ColumnRef(column=column):
|
|
349
|
+
pending.append(column)
|
|
350
|
+
case ir.ScalarExpr():
|
|
351
|
+
pending.extend(ir.children(node))
|
|
352
|
+
case ir.RelationExpr():
|
|
353
|
+
pending.extend(child for child in ir.children(node) if isinstance(child, ir.RelationExpr | ir.ScalarExpr))
|
|
354
|
+
case _:
|
|
355
|
+
pass
|
|
356
|
+
return None
|
sqlassert/reporting.py
CHANGED
|
@@ -35,6 +35,9 @@ class AssertionReport:
|
|
|
35
35
|
origin: Origin
|
|
36
36
|
kind: str
|
|
37
37
|
evidence: Result[bool] | None = field(default=None, compare=False)
|
|
38
|
+
# For an UNKNOWN assertion whose proof reaches a construct sqlassert does
|
|
39
|
+
# not support yet: what that construct is.
|
|
40
|
+
unsupported: str | None = None
|
|
38
41
|
|
|
39
42
|
|
|
40
43
|
# The marker each assertable Property is written as, in the words of its `/**ASSERT ...**/`.
|