sqlassert 0.3.3__py3-none-any.whl → 0.4.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sqlassert/__init__.py +1 -2
- sqlassert/check.py +88 -13
- sqlassert/diagnostics.py +17 -6
- sqlassert/dialects.py +437 -7
- sqlassert/discovery/bigquery.py +3 -1
- sqlassert/discovery/databricks.py +25 -2
- sqlassert/discovery/duckdb.py +49 -7
- sqlassert/discovery/fetcher.py +130 -21
- sqlassert/discovery/information_schema.py +30 -2
- sqlassert/discovery/mysql.py +22 -1
- sqlassert/discovery/postgres.py +22 -5
- sqlassert/discovery/redshift.py +3 -2
- sqlassert/discovery/snowflake.py +3 -0
- sqlassert/discovery/trino.py +2 -2
- sqlassert/hazards.py +248 -87
- sqlassert/ir/__init__.py +4 -1
- sqlassert/ir/convert/__init__.py +13 -0
- sqlassert/ir/convert/aggregation.py +439 -0
- sqlassert/ir/convert/builtins.py +140 -0
- sqlassert/ir/convert/expressions.py +572 -0
- sqlassert/ir/convert/joins.py +264 -0
- sqlassert/ir/convert/markers.py +249 -0
- sqlassert/ir/convert/parser.py +253 -0
- sqlassert/ir/convert/queries.py +259 -0
- sqlassert/ir/convert/schema.py +606 -0
- sqlassert/ir/convert/scopes.py +205 -0
- sqlassert/ir/convert/selects.py +337 -0
- sqlassert/ir/convert/shared.py +429 -0
- sqlassert/ir/convert/sources.py +432 -0
- sqlassert/ir/convert/subqueries.py +364 -0
- sqlassert/ir/convert/value_types.py +223 -0
- sqlassert/ir/convert/windows.py +275 -0
- sqlassert/ir/model.py +125 -47
- sqlassert/ir/names.py +63 -0
- sqlassert/properties.py +12 -1
- sqlassert/provenance.py +5 -1
- sqlassert/python_engine.py +104 -44
- sqlassert/reporting.py +33 -32
- sqlassert/rewrites.py +111 -61
- sqlassert/rules/STYLEGUIDE.md +3 -2
- sqlassert/rules/causes/__init__.py +41 -0
- sqlassert/rules/causes/coverage.py +113 -0
- sqlassert/rules/causes/domain.py +123 -0
- sqlassert/rules/causes/joins.py +73 -0
- sqlassert/rules/causes/nulls.py +154 -0
- sqlassert/rules/causes/unique.py +523 -0
- sqlassert/rules/domain.py +8 -7
- sqlassert/rules/equality.py +6 -147
- sqlassert/rules/exactly_one.py +2 -1
- sqlassert/rules/foreign_key.py +8 -9
- sqlassert/rules/join_cardinality.py +282 -41
- sqlassert/rules/nullability.py +5 -5
- sqlassert/rules/uniqueness.py +171 -47
- sqlassert/rules/value_typing.py +337 -0
- sqlassert/sql_parse.py +28 -1
- sqlassert/suggest.py +11 -15
- sqlassert-0.4.1.dist-info/METADATA +235 -0
- sqlassert-0.4.1.dist-info/RECORD +69 -0
- sqlassert/ir/convert.py +0 -3509
- sqlassert-0.3.3.dist-info/METADATA +0 -807
- sqlassert-0.3.3.dist-info/RECORD +0 -46
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/WHEEL +0 -0
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/entry_points.txt +0 -0
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/licenses/LICENSE +0 -0
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/top_level.txt +0 -0
sqlassert/rules/nullability.py
CHANGED
|
@@ -16,7 +16,7 @@ from typing import assert_never
|
|
|
16
16
|
|
|
17
17
|
from sqlassert.diagnostics import quoted
|
|
18
18
|
from sqlassert import ir
|
|
19
|
-
from sqlassert.properties import NonNullElements
|
|
19
|
+
from sqlassert.properties import NonNullColumn, NonNullColumns, NonNullElements
|
|
20
20
|
from sqlassert.python_engine import Result, Stratum, all_of, analysis, any_of, current_arena, unknown
|
|
21
21
|
|
|
22
22
|
|
|
@@ -47,7 +47,7 @@ ORGANIC = Organic()
|
|
|
47
47
|
type _Sources = dict[NullSource, Result[bool]]
|
|
48
48
|
|
|
49
49
|
|
|
50
|
-
@analysis(Stratum.NON_NULL)
|
|
50
|
+
@analysis(Stratum.NON_NULL, evaluates=NonNullColumns)
|
|
51
51
|
def non_null_columns(columns: frozenset[ir.OutputColumn]) -> Result[bool]:
|
|
52
52
|
relation = current_arena().program.relation_of(columns)
|
|
53
53
|
if relation is None:
|
|
@@ -57,7 +57,7 @@ def non_null_columns(columns: frozenset[ir.OutputColumn]) -> Result[bool]:
|
|
|
57
57
|
return all_of(non_null_column(column) for column in ordered)
|
|
58
58
|
|
|
59
59
|
|
|
60
|
-
@analysis(Stratum.NON_NULL)
|
|
60
|
+
@analysis(Stratum.NON_NULL, evaluates=NonNullColumn)
|
|
61
61
|
def non_null_column(column: ir.OutputColumn) -> Result[bool]:
|
|
62
62
|
sources = _null_sources(column)
|
|
63
63
|
if sources.value:
|
|
@@ -68,7 +68,7 @@ def non_null_column(column: ir.OutputColumn) -> Result[bool]:
|
|
|
68
68
|
@analysis(Stratum.NON_NULL)
|
|
69
69
|
def _null_sources(column: ir.OutputColumn) -> Result[frozenset[NullSource]]:
|
|
70
70
|
arena = current_arena()
|
|
71
|
-
accepted = arena.
|
|
71
|
+
accepted = arena.accepted_evidence(NonNullColumn(column=column))
|
|
72
72
|
if accepted:
|
|
73
73
|
return Result(frozenset(), "Known non-null", (column,), [any_of(accepted)])
|
|
74
74
|
relation = column.get_relation(arena.program)
|
|
@@ -207,7 +207,7 @@ def _expression_sources(expression: ir.ScalarExpr) -> tuple[_Sources, list[Resul
|
|
|
207
207
|
assert_never(expression)
|
|
208
208
|
|
|
209
209
|
|
|
210
|
-
@analysis(Stratum.NON_NULL)
|
|
210
|
+
@analysis(Stratum.NON_NULL, evaluates=NonNullElements)
|
|
211
211
|
def non_null_elements(columns: frozenset[ir.OutputColumn]) -> Result[bool]:
|
|
212
212
|
relation = current_arena().program.relation_of(columns)
|
|
213
213
|
if relation is None:
|
sqlassert/rules/uniqueness.py
CHANGED
|
@@ -23,14 +23,16 @@ from __future__ import annotations
|
|
|
23
23
|
|
|
24
24
|
from collections.abc import Callable, Iterator
|
|
25
25
|
from dataclasses import dataclass, field
|
|
26
|
-
from itertools import combinations
|
|
26
|
+
from itertools import combinations, product
|
|
27
27
|
from typing import assert_never
|
|
28
28
|
|
|
29
29
|
from sqlassert.diagnostics import quoted
|
|
30
30
|
from sqlassert import ir
|
|
31
|
+
from sqlassert.properties import FunctionalDependency, NonNullUniqueSet, UniqueSet
|
|
31
32
|
from sqlassert.python_engine import Result, Stratum, all_of, analysis, any_of, current_arena, unknown
|
|
32
33
|
from sqlassert.rules.column_set import Attribute, Closure, RowIdentity
|
|
33
|
-
from sqlassert.rules.equality import
|
|
34
|
+
from sqlassert.rules.equality import _constant_value, _equal_columns, _predicate_constants, _predicate_equalities, _same_set_types, _typed_arms
|
|
35
|
+
from sqlassert.rules.value_typing import _binary_text, _boolean, _identity_comparison, _signed_integer, exact_comparison, exact_numeric, fixes, scalar_typing
|
|
34
36
|
from sqlassert.rules.nullability import Padding, _null_sources, _padded_sides, non_null_column, non_null_columns
|
|
35
37
|
|
|
36
38
|
|
|
@@ -49,7 +51,7 @@ type Dependencies = dict[Dependency, Result[bool]]
|
|
|
49
51
|
# Public analyses ---------------------------------------------------------------
|
|
50
52
|
|
|
51
53
|
|
|
52
|
-
@analysis(Stratum.UNIQUE_SET)
|
|
54
|
+
@analysis(Stratum.UNIQUE_SET, evaluates=UniqueSet)
|
|
53
55
|
def unique_set(columns: frozenset[ir.OutputColumn]) -> Result[bool]:
|
|
54
56
|
relation = current_arena().program.relation_of(columns)
|
|
55
57
|
if relation is None:
|
|
@@ -57,12 +59,12 @@ def unique_set(columns: frozenset[ir.OutputColumn]) -> Result[bool]:
|
|
|
57
59
|
return _reaches_row_identity(_closure(relation, frozenset(columns), frozenset(columns)))
|
|
58
60
|
|
|
59
61
|
|
|
60
|
-
@analysis(Stratum.UNIQUE_SET)
|
|
62
|
+
@analysis(Stratum.UNIQUE_SET, evaluates=NonNullUniqueSet)
|
|
61
63
|
def non_null_unique_set(columns: frozenset[ir.OutputColumn]) -> Result[bool]:
|
|
62
64
|
return unique_set(columns) & non_null_columns(columns)
|
|
63
65
|
|
|
64
66
|
|
|
65
|
-
@analysis(Stratum.CLOSURE)
|
|
67
|
+
@analysis(Stratum.CLOSURE, evaluates=FunctionalDependency)
|
|
66
68
|
def functional_dependency(determinant: frozenset[ir.OutputColumn], dependent: frozenset[ir.OutputColumn]) -> Result[bool]:
|
|
67
69
|
relation = current_arena().program.relation_of(determinant | dependent)
|
|
68
70
|
if relation is None:
|
|
@@ -86,23 +88,38 @@ def _reaches_row_identity(closure: Result[Closure]) -> Result[bool]:
|
|
|
86
88
|
return any_of(gaps)
|
|
87
89
|
|
|
88
90
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
91
|
+
@dataclass(frozen=True)
|
|
92
|
+
class KeyGap:
|
|
93
|
+
"""A known key a closure misses: the key's `reached` attributes and its
|
|
94
|
+
`missing` columns, with the evidence of the key."""
|
|
95
|
+
|
|
96
|
+
reached: frozenset[Attribute]
|
|
97
|
+
missing: tuple[ir.OutputColumn, ...]
|
|
98
|
+
evidence: Result[bool]
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _key_gaps(closure: Result[Closure]) -> list[KeyGap]:
|
|
102
|
+
"""Each known key the closure misses, down through every input the
|
|
103
|
+
closure looked into."""
|
|
92
104
|
relation = closure.value.relation
|
|
93
105
|
identity = RowIdentity(relation)
|
|
94
|
-
gaps: list[
|
|
106
|
+
gaps: list[KeyGap] = []
|
|
95
107
|
for dependency, evidence in _functional_dependencies(relation).value.items():
|
|
96
108
|
if dependency.dependent != identity or dependency.determinant <= closure.value.columns:
|
|
97
109
|
continue
|
|
98
|
-
missing =
|
|
99
|
-
gaps.append(
|
|
110
|
+
missing = tuple(column for column in relation.output_columns if column in dependency.determinant - closure.value.columns)
|
|
111
|
+
gaps.append(KeyGap(dependency.determinant & closure.value.columns, missing, evidence))
|
|
100
112
|
for premise in closure.value.inputs:
|
|
101
113
|
if RowIdentity(premise.value.relation) not in premise.value.columns:
|
|
102
|
-
gaps.extend(
|
|
114
|
+
gaps.extend(_key_gaps(premise))
|
|
103
115
|
return gaps
|
|
104
116
|
|
|
105
117
|
|
|
118
|
+
def _uncovered_keys(closure: Result[Closure]) -> list[Result[bool]]:
|
|
119
|
+
"""Each known key the closure misses, naming its missing columns."""
|
|
120
|
+
return [gap.evidence & unknown("Unique-set columns are not covered", *gap.missing) for gap in _key_gaps(closure)]
|
|
121
|
+
|
|
122
|
+
|
|
106
123
|
# Closure -----------------------------------------------------------------------
|
|
107
124
|
|
|
108
125
|
|
|
@@ -228,6 +245,8 @@ def _distinct_tags(arms: tuple[ir.OutputColumn, ir.OutputColumn], first: ir.Lite
|
|
|
228
245
|
return first != second
|
|
229
246
|
if first.type == second.type == "string" and all(_binary_text(arm).value for arm in arms):
|
|
230
247
|
return first != second
|
|
248
|
+
if first.type == second.type == "boolean" and all(_boolean(arm) for arm in arms):
|
|
249
|
+
return first != second
|
|
231
250
|
if first.type == second.type == "numeric":
|
|
232
251
|
return (
|
|
233
252
|
all(_signed_integer(arm) or isinstance(arm.scalar_expr, ir.Constant) for arm in arms)
|
|
@@ -627,14 +646,15 @@ def _functional_dependencies(relation: ir.RelationExpr) -> Result[Dependencies]:
|
|
|
627
646
|
|
|
628
647
|
identity = RowIdentity(relation)
|
|
629
648
|
columns = set(relation.output_columns)
|
|
630
|
-
for
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
649
|
+
for claim, accepted in current_arena().accepted.items():
|
|
650
|
+
match claim:
|
|
651
|
+
case NonNullUniqueSet():
|
|
652
|
+
pass # Also accepted as its Unique Set, which adds the dependency once.
|
|
653
|
+
case UniqueSet(columns=known) if known <= columns:
|
|
654
|
+
add(known, identity, False, any_of(accepted))
|
|
655
|
+
case FunctionalDependency(determinant=determinant, dependent=dependents) if determinant | dependents <= columns:
|
|
656
|
+
for dependent in dependents:
|
|
657
|
+
add(determinant, dependent, False, any_of(accepted))
|
|
638
658
|
case _:
|
|
639
659
|
pass # Other Knowledge is not a dependency of this relation.
|
|
640
660
|
|
|
@@ -675,7 +695,10 @@ def _functional_dependencies(relation: ir.RelationExpr) -> Result[Dependencies]:
|
|
|
675
695
|
add(relation.output_columns, identity, True, Result(True, f"{relation.operator.upper()} removes duplicate rows", (relation,)))
|
|
676
696
|
case ir.Limit(count=int() as count) if count <= 1:
|
|
677
697
|
add((), identity, True, Result(True, "LIMIT keeps at most one row", (relation,)))
|
|
678
|
-
case ir.
|
|
698
|
+
case ir.Project():
|
|
699
|
+
for determinant, dependent, strict, evidence in _merged_key_dependencies(relation):
|
|
700
|
+
add(determinant, dependent, strict, evidence)
|
|
701
|
+
case ir.Alias() | ir.NamedRelation() | ir.Limit() | ir.SetOperation() | ir.OpaqueRelation():
|
|
679
702
|
pass
|
|
680
703
|
case _:
|
|
681
704
|
assert_never(relation)
|
|
@@ -697,30 +720,31 @@ def _equality_dependencies(conjuncts: tuple[ir.ScalarExpr, ...], outputs: dict[i
|
|
|
697
720
|
for first, second in _predicate_equalities((conjunct,)):
|
|
698
721
|
if first in outputs and second in outputs and _identity_comparison(second).value:
|
|
699
722
|
yield (outputs[first],), outputs[second], evidence
|
|
700
|
-
# An equality
|
|
701
|
-
# values that differ: it gives no dependency.
|
|
723
|
+
# An equality with a lossy cast, or under a collation, relates
|
|
724
|
+
# values that differ: it gives no dependency (`fixes`).
|
|
702
725
|
# IS NOT DISTINCT FROM equates NULLs too, so NULL agrees with NULL.
|
|
703
726
|
case (
|
|
704
727
|
ir.Equality(left=ir.ColumnRef(column=first) as left, right=ir.ColumnRef(column=second) as right)
|
|
705
728
|
| ir.NullSafeEquality(left=ir.ColumnRef(column=first) as left, right=ir.ColumnRef(column=second) as right)
|
|
706
729
|
) if first in outputs and second in outputs:
|
|
707
|
-
if
|
|
730
|
+
if fixes(right, left).value:
|
|
708
731
|
yield (outputs[first],), outputs[second], evidence
|
|
709
|
-
if
|
|
732
|
+
if fixes(left, right).value:
|
|
710
733
|
yield (outputs[second],), outputs[first], evidence
|
|
711
734
|
case (
|
|
712
|
-
ir.Equality(left=ir.ColumnRef(column=column), right=ir.Constant() as constant)
|
|
713
|
-
| ir.Equality(left=ir.Constant() as constant, right=ir.ColumnRef(column=column))
|
|
714
|
-
| ir.NullSafeEquality(left=ir.ColumnRef(column=column), right=ir.Constant() as constant)
|
|
715
|
-
| ir.NullSafeEquality(left=ir.Constant() as constant, right=ir.ColumnRef(column=column))
|
|
735
|
+
ir.Equality(left=ir.ColumnRef(column=column) as operand, right=ir.Constant() as constant)
|
|
736
|
+
| ir.Equality(left=ir.Constant() as constant, right=ir.ColumnRef(column=column) as operand)
|
|
737
|
+
| ir.NullSafeEquality(left=ir.ColumnRef(column=column) as operand, right=ir.Constant() as constant)
|
|
738
|
+
| ir.NullSafeEquality(left=ir.Constant() as constant, right=ir.ColumnRef(column=column) as operand)
|
|
716
739
|
) if column in outputs:
|
|
717
|
-
if
|
|
740
|
+
if fixes(operand, constant).value:
|
|
718
741
|
yield (), outputs[column], evidence
|
|
719
742
|
case ir.IsNull(operand=ir.ColumnRef(column=column)) if column in outputs:
|
|
720
743
|
yield (), outputs[column], evidence
|
|
721
744
|
case ir.Equality(left=left, right=right):
|
|
722
745
|
for target, value in ((left, right), (right, left)):
|
|
723
|
-
|
|
746
|
+
# The comparison must lose nothing, or `b` equals `f(x)` for values of `b` that differ.
|
|
747
|
+
if not (isinstance(target, ir.ColumnRef) and target.column in outputs and fixes(target, value).value):
|
|
724
748
|
continue
|
|
725
749
|
inputs = _identity_inputs(value, tuple(outputs))
|
|
726
750
|
if inputs is not None:
|
|
@@ -781,25 +805,26 @@ def _matched_dependencies(join: ir.Join, outputs: dict[ir.OutputColumn, ir.Outpu
|
|
|
781
805
|
column or a literal, that fixes it, and it fixes each left column ON pins
|
|
782
806
|
to it. `d.deptno = e.mgr AND d.deptno = e.comm` gives mgr -> comm."""
|
|
783
807
|
right = join.right.output_columns
|
|
784
|
-
pairs: list[tuple[ir.
|
|
808
|
+
pairs: list[tuple[ir.ColumnRef, ir.ScalarExpr, ir.ScalarExpr]] = []
|
|
785
809
|
for conjunct in join.conjuncts:
|
|
786
810
|
match conjunct:
|
|
787
811
|
case ir.Equality(left=first, right=second) | ir.NullSafeEquality(left=first, right=second):
|
|
788
|
-
pairs.extend((other
|
|
812
|
+
pairs.extend((other, value, conjunct) for other, value in ((first, second), (second, first)) if isinstance(other, ir.ColumnRef) and other.column in right)
|
|
789
813
|
case _:
|
|
790
814
|
pass # Other conjuncts pin nothing.
|
|
791
|
-
for
|
|
815
|
+
for matched, value, conjunct in pairs:
|
|
792
816
|
# What fixes the right column: a left column or a literal it is pinned to.
|
|
793
817
|
match value:
|
|
794
|
-
case ir.ColumnRef(column=source) if source in outputs and
|
|
818
|
+
case ir.ColumnRef(column=source) if source in outputs and fixes(matched, value).value:
|
|
795
819
|
determinant: tuple[ir.OutputColumn, ...] = (outputs[source],)
|
|
796
|
-
case ir.Constant() if
|
|
820
|
+
case ir.Constant() if fixes(matched, value).value:
|
|
797
821
|
determinant = ()
|
|
798
822
|
case _:
|
|
799
823
|
continue
|
|
824
|
+
column = matched.column
|
|
800
825
|
for other, bound, other_conjunct in pairs:
|
|
801
|
-
if other is column and other_conjunct is not conjunct and isinstance(bound, ir.ColumnRef) and bound.column in outputs:
|
|
802
|
-
if
|
|
826
|
+
if other.column is column and other_conjunct is not conjunct and isinstance(bound, ir.ColumnRef) and bound.column in outputs:
|
|
827
|
+
if fixes(bound, other).value:
|
|
803
828
|
evidence = Result(True, f"ON conjuncts equal through {quoted(column.name)} of the matched right row", (conjunct, other_conjunct))
|
|
804
829
|
yield determinant, outputs[bound.column], True, evidence
|
|
805
830
|
|
|
@@ -834,14 +859,14 @@ def _outer_on_dependencies(join: ir.Join, outputs: dict[ir.OutputColumn, ir.Outp
|
|
|
834
859
|
continue
|
|
835
860
|
match value:
|
|
836
861
|
case ir.ColumnRef(column=other) if other in padded.output_columns:
|
|
837
|
-
if
|
|
862
|
+
if fixes(bound, value).value:
|
|
838
863
|
yield (outputs[other],), outputs[bound.column], True, evidence
|
|
839
864
|
case ir.ColumnRef(column=other):
|
|
840
|
-
if
|
|
865
|
+
if fixes(bound, value).value:
|
|
841
866
|
yield status, outputs[bound.column], True, evidence
|
|
842
|
-
if
|
|
867
|
+
if fixes(value, bound).value:
|
|
843
868
|
yield (outputs[bound.column],), outputs[other], False, evidence
|
|
844
|
-
case ir.Constant() if
|
|
869
|
+
case ir.Constant() if fixes(bound, value).value:
|
|
845
870
|
yield status, outputs[bound.column], True, evidence
|
|
846
871
|
case _:
|
|
847
872
|
pass # A NULL, an unpinned constant, or an expression binds nothing.
|
|
@@ -867,7 +892,7 @@ def _full_on_dependencies(join: ir.Join, outputs: dict[ir.OutputColumn, ir.Outpu
|
|
|
867
892
|
for bound, value in ((first, second), (second, first)):
|
|
868
893
|
match bound, value:
|
|
869
894
|
case ir.ColumnRef(column=column), ir.ColumnRef(column=other) if (
|
|
870
|
-
column in padded.output_columns and other not in padded.output_columns and
|
|
895
|
+
column in padded.output_columns and other not in padded.output_columns and fixes(bound, value).value
|
|
871
896
|
):
|
|
872
897
|
yield status | {outputs[other]}, outputs[column], False, evidence
|
|
873
898
|
case _:
|
|
@@ -876,6 +901,84 @@ def _full_on_dependencies(join: ir.Join, outputs: dict[ir.OutputColumn, ir.Outpu
|
|
|
876
901
|
pass # Other conjuncts hold on matched rows only.
|
|
877
902
|
|
|
878
903
|
|
|
904
|
+
def _merged_key_dependencies(project: ir.Project):
|
|
905
|
+
"""A FULL join on a key of both inputs, projected as the coalesced key.
|
|
906
|
+
|
|
907
|
+
`SELECT coalesce(a.k, b.k) AS k FROM a FULL JOIN b ON a.k = b.k` (the
|
|
908
|
+
merged column of `USING (k)` is one): when the pairs of columns the ON
|
|
909
|
+
equates (`=` or `IS NOT DISTINCT FROM`) are every conjunct of it, a Unique Set of `a` on the left ones and
|
|
910
|
+
of `b` on the right ones, the coalesced columns are a Unique Set of the
|
|
911
|
+
join's rows, laxly: a row's non-NULL key value is that of its `a` row, of
|
|
912
|
+
its `b` row, or of both, equal (the comparison loses nothing and the
|
|
913
|
+
coalesce keeps the value), so two rows with it share an `a` row or a `b`
|
|
914
|
+
row (excluded: each repeats only on a repeated key) or one is an unmatched
|
|
915
|
+
row whose key equals one of the other, which ON would have matched. A row
|
|
916
|
+
with a NULL key part is unmatched and coalesces to NULL, and the Unique Set
|
|
917
|
+
does not constrain it (`IS NOT DISTINCT FROM` also matches NULL to NULL,
|
|
918
|
+
which merges to the same NULL; a non-NULL value matches as with `=`). Another ON conjunct would leave two unmatched rows
|
|
919
|
+
of one value, so it gives nothing. Rows a WHERE drops keep the property."""
|
|
920
|
+
found = _full_join_beneath(project)
|
|
921
|
+
if found is None:
|
|
922
|
+
return
|
|
923
|
+
join, outputs = found
|
|
924
|
+
inputs = {output: column for column, output in _join_outputs(join).items()}
|
|
925
|
+
pairs: list[tuple[ir.OutputColumn, ir.OutputColumn]] = []
|
|
926
|
+
for conjunct in join.conjuncts:
|
|
927
|
+
match conjunct:
|
|
928
|
+
case ir.Equality(left=ir.ColumnRef(column=first) as one, right=ir.ColumnRef(column=second) as other) | ir.NullSafeEquality(
|
|
929
|
+
left=ir.ColumnRef(column=first) as one, right=ir.ColumnRef(column=second) as other
|
|
930
|
+
):
|
|
931
|
+
for left, right in ((first, second), (second, first)):
|
|
932
|
+
if left in join.left.output_columns and right in join.right.output_columns:
|
|
933
|
+
if not exact_comparison(one, other).value:
|
|
934
|
+
return
|
|
935
|
+
pairs.append((left, right))
|
|
936
|
+
break
|
|
937
|
+
else:
|
|
938
|
+
return # An equality within one input holds on matched rows only.
|
|
939
|
+
case _:
|
|
940
|
+
return # Any other conjunct leaves matched rows unrelated to equal keys.
|
|
941
|
+
if not pairs:
|
|
942
|
+
return
|
|
943
|
+
passed = _pass_through(project, project.input)
|
|
944
|
+
choices: list[list[ir.OutputColumn]] = [[] for _ in pairs]
|
|
945
|
+
for column in project.output_columns:
|
|
946
|
+
match column.scalar_expr:
|
|
947
|
+
case ir.Coalesce(arguments=(ir.ColumnRef(column=first), ir.ColumnRef(column=second))):
|
|
948
|
+
# USING's merged column reads the columns its own Project passes through.
|
|
949
|
+
first, second = passed.get(first, first), passed.get(second, second)
|
|
950
|
+
if first not in outputs or second not in outputs or scalar_typing(column.scalar_expr).value is None:
|
|
951
|
+
continue
|
|
952
|
+
taken = (inputs[outputs[first]], inputs[outputs[second]])
|
|
953
|
+
for index, (left, right) in enumerate(pairs):
|
|
954
|
+
if taken in ((left, right), (right, left)):
|
|
955
|
+
choices[index].append(column)
|
|
956
|
+
case _:
|
|
957
|
+
pass
|
|
958
|
+
if not all(choices):
|
|
959
|
+
return
|
|
960
|
+
left_key, right_key = frozenset(left for left, _ in pairs), frozenset(right for _, right in pairs)
|
|
961
|
+
proof = unique_set(left_key) & unique_set(right_key)
|
|
962
|
+
if not proof.value:
|
|
963
|
+
return
|
|
964
|
+
evidence = Result(True, "A FULL join on a key of both inputs matches each key value once", (project,), [proof])
|
|
965
|
+
for determinant in product(*choices):
|
|
966
|
+
yield determinant, RowIdentity(project), False, evidence
|
|
967
|
+
|
|
968
|
+
|
|
969
|
+
def _full_join_beneath(project: ir.Project) -> tuple[ir.Join, dict[ir.OutputColumn, ir.OutputColumn]] | None:
|
|
970
|
+
"""The FULL join under `project`, through the filters between them, with
|
|
971
|
+
each column of the project's input mapped to the join's output column it
|
|
972
|
+
passes through."""
|
|
973
|
+
source = project.input
|
|
974
|
+
mapping: dict[ir.OutputColumn, ir.OutputColumn] = {column: column for column in source.output_columns}
|
|
975
|
+
while isinstance(source, ir.Filter):
|
|
976
|
+
through = _pass_through(source, source.input)
|
|
977
|
+
mapping = {column: through[passed] for column, passed in mapping.items() if passed in through}
|
|
978
|
+
source = source.input
|
|
979
|
+
return (source, mapping) if isinstance(source, ir.Join) and source.kind == "full" else None
|
|
980
|
+
|
|
981
|
+
|
|
879
982
|
def minimal_keys(relation: ir.RelationExpr, max_size: int = 3) -> list[tuple[ir.OutputColumn, ...]]:
|
|
880
983
|
"""The minimal Unique Sets of `relation`, in output order.
|
|
881
984
|
|
|
@@ -889,11 +992,32 @@ def minimal_keys(relation: ir.RelationExpr, max_size: int = 3) -> list[tuple[ir.
|
|
|
889
992
|
|
|
890
993
|
if not columns or not unique(columns):
|
|
891
994
|
return []
|
|
892
|
-
keys: list[tuple[ir.OutputColumn, ...]] = []
|
|
893
|
-
|
|
894
|
-
|
|
995
|
+
keys: list[tuple[ir.OutputColumn, ...]] = [(column,) for column in columns if max_size >= 1 and unique((column,))]
|
|
996
|
+
candidates = columns
|
|
997
|
+
required: tuple[ir.OutputColumn, ...] = ()
|
|
998
|
+
if max_size > 1 and keys:
|
|
999
|
+
singletons = {key[0] for key in keys}
|
|
1000
|
+
candidates = tuple(column for column in columns if column not in singletons)
|
|
1001
|
+
# A larger minimal key must avoid every singleton key. If their complement
|
|
1002
|
+
# cannot determine the row, neither can any subset of it.
|
|
1003
|
+
if len(candidates) < 2 or not unique(candidates):
|
|
1004
|
+
return keys
|
|
1005
|
+
elif max_size > 1:
|
|
1006
|
+
# Every Unique Set holds each column the others cannot do without: a set
|
|
1007
|
+
# lacking it is a subset of those others, so not unique either. When
|
|
1008
|
+
# those columns alone are unique, they are the only minimal Unique Set.
|
|
1009
|
+
required = tuple(column for column in columns if not unique(tuple(other for other in columns if other is not column)))
|
|
1010
|
+
if required and unique(required):
|
|
1011
|
+
return [required]
|
|
1012
|
+
candidates = tuple(column for column in columns if column not in required)
|
|
1013
|
+
position = {column: index for index, column in enumerate(columns)}
|
|
1014
|
+
for size in range(max(2, len(required) + 1), min(max_size, len(required) + len(candidates)) + 1):
|
|
1015
|
+
found = []
|
|
1016
|
+
for extra in combinations(candidates, size - len(required)):
|
|
1017
|
+
members = tuple(sorted((*required, *extra), key=position.__getitem__))
|
|
895
1018
|
if not any(set(key) <= set(members) for key in keys) and unique(members):
|
|
896
|
-
|
|
1019
|
+
found.append(members)
|
|
1020
|
+
keys.extend(sorted(found, key=lambda members: [position[column] for column in members]))
|
|
897
1021
|
if keys:
|
|
898
1022
|
return keys
|
|
899
1023
|
members = columns
|