sqlassert 0.3.3__py3-none-any.whl → 0.4.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sqlassert/__init__.py +1 -2
- sqlassert/check.py +88 -13
- sqlassert/declared_types.py +158 -0
- sqlassert/diagnostics.py +15 -7
- sqlassert/dialects.py +259 -107
- sqlassert/discovery/bigquery.py +4 -2
- sqlassert/discovery/databricks.py +26 -5
- sqlassert/discovery/duckdb.py +49 -7
- sqlassert/discovery/fetcher.py +137 -58
- sqlassert/discovery/information_schema.py +31 -6
- sqlassert/discovery/mysql.py +21 -4
- sqlassert/discovery/postgres.py +28 -20
- sqlassert/discovery/redshift.py +3 -2
- sqlassert/discovery/snowflake.py +5 -2
- sqlassert/discovery/trino.py +2 -2
- sqlassert/functions/__init__.py +10 -0
- sqlassert/functions/load.py +375 -0
- sqlassert/functions/table.py +2721 -0
- sqlassert/hazards.py +249 -88
- sqlassert/ir/__init__.py +15 -4
- sqlassert/ir/convert/__init__.py +13 -0
- sqlassert/ir/convert/aggregation.py +438 -0
- sqlassert/ir/convert/expressions.py +581 -0
- sqlassert/ir/convert/joins.py +264 -0
- sqlassert/ir/convert/markers.py +249 -0
- sqlassert/ir/convert/parser.py +249 -0
- sqlassert/ir/convert/queries.py +259 -0
- sqlassert/ir/convert/schema.py +537 -0
- sqlassert/ir/convert/scopes.py +205 -0
- sqlassert/ir/convert/selects.py +352 -0
- sqlassert/ir/convert/shared.py +428 -0
- sqlassert/ir/convert/sources.py +433 -0
- sqlassert/ir/convert/subqueries.py +364 -0
- sqlassert/ir/convert/value_types.py +78 -0
- sqlassert/ir/convert/windows.py +275 -0
- sqlassert/ir/model.py +417 -146
- sqlassert/ir/names.py +63 -0
- sqlassert/main.py +7 -10
- 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 +564 -0
- sqlassert/rules/domain.py +9 -8
- 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 +277 -43
- sqlassert/rules/nullability.py +8 -8
- sqlassert/rules/uniqueness.py +212 -87
- sqlassert/rules/value_typing.py +470 -0
- sqlassert/sql_parse.py +28 -1
- sqlassert/suggest.py +13 -17
- sqlassert-0.4.2.dist-info/METADATA +239 -0
- sqlassert-0.4.2.dist-info/RECORD +72 -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.2.dist-info}/WHEEL +0 -0
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/entry_points.txt +0 -0
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/licenses/LICENSE +0 -0
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.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)
|
|
@@ -178,7 +178,7 @@ def _expression_sources(expression: ir.ScalarExpr) -> tuple[_Sources, list[Resul
|
|
|
178
178
|
return result, []
|
|
179
179
|
reason = f"{expression.function.name} is non-null when its arguments are" if arguments else f"{expression.function.name} is never NULL"
|
|
180
180
|
return {}, [Result(True, reason, (expression,), premises)]
|
|
181
|
-
case ir.OpaqueExpression(description=description) | ir.
|
|
181
|
+
case ir.OpaqueExpression(description=description) | ir.Call(description=description):
|
|
182
182
|
return {ORGANIC: unknown(f"Nullability of {description} is not known", expression)}, []
|
|
183
183
|
case ir.Elements(operand=operand):
|
|
184
184
|
elements = _expression_elements(operand)
|
|
@@ -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:
|
|
@@ -248,7 +248,7 @@ def _expression_elements(expression: ir.ScalarExpr) -> Result[bool]:
|
|
|
248
248
|
case ir.SimpleCase(thens=thens, default=default):
|
|
249
249
|
return all_of(_expression_elements(arm) for arm in (*thens, default))
|
|
250
250
|
case (
|
|
251
|
-
ir.Constant() | ir.Count() | ir.Accumulation() | ir.Call() | ir.OpaqueExpression() | ir.
|
|
251
|
+
ir.Constant() | ir.Count() | ir.Accumulation() | ir.Call() | ir.OpaqueExpression() | ir.Elements()
|
|
252
252
|
| ir.Equality() | ir.NullSafeEquality() | ir.InList() | ir.IsNull() | ir.IsNotNull() | ir.And() | ir.Or()
|
|
253
253
|
):
|
|
254
254
|
return unknown("Its elements may be NULL", expression)
|
|
@@ -505,7 +505,7 @@ def _null_with(expression: ir.ScalarExpr) -> frozenset[Padding]:
|
|
|
505
505
|
case ir.And(parts=(first, *others)) | ir.Or(parts=(first, *others)):
|
|
506
506
|
return _null_with(first).intersection(*(_null_with(other) for other in others))
|
|
507
507
|
case (
|
|
508
|
-
ir.And() | ir.Or() | ir.Coalesce() | ir.Constant() | ir.NullLiteral() | ir.SimpleCase()
|
|
508
|
+
ir.And() | ir.Or() | ir.Coalesce() | ir.Constant() | ir.NullLiteral() | ir.SimpleCase()
|
|
509
509
|
| ir.OpaqueExpression() | ir.Count() | ir.AnyAggregate() | ir.Accumulation() | ir.Elements() | ir.IsNull()
|
|
510
510
|
| ir.IsNotNull() | ir.NullSafeEquality()
|
|
511
511
|
):
|
sqlassert/rules/uniqueness.py
CHANGED
|
@@ -23,14 +23,19 @@ 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 (
|
|
36
|
+
_binary_text, _boolean, _identity_comparison, _signed_integer, exact_comparison, fixes, reflected_column, reflected_operand, respected_inputs,
|
|
37
|
+
respects_equality, scalar_typing,
|
|
38
|
+
)
|
|
34
39
|
from sqlassert.rules.nullability import Padding, _null_sources, _padded_sides, non_null_column, non_null_columns
|
|
35
40
|
|
|
36
41
|
|
|
@@ -49,7 +54,7 @@ type Dependencies = dict[Dependency, Result[bool]]
|
|
|
49
54
|
# Public analyses ---------------------------------------------------------------
|
|
50
55
|
|
|
51
56
|
|
|
52
|
-
@analysis(Stratum.UNIQUE_SET)
|
|
57
|
+
@analysis(Stratum.UNIQUE_SET, evaluates=UniqueSet)
|
|
53
58
|
def unique_set(columns: frozenset[ir.OutputColumn]) -> Result[bool]:
|
|
54
59
|
relation = current_arena().program.relation_of(columns)
|
|
55
60
|
if relation is None:
|
|
@@ -57,12 +62,12 @@ def unique_set(columns: frozenset[ir.OutputColumn]) -> Result[bool]:
|
|
|
57
62
|
return _reaches_row_identity(_closure(relation, frozenset(columns), frozenset(columns)))
|
|
58
63
|
|
|
59
64
|
|
|
60
|
-
@analysis(Stratum.UNIQUE_SET)
|
|
65
|
+
@analysis(Stratum.UNIQUE_SET, evaluates=NonNullUniqueSet)
|
|
61
66
|
def non_null_unique_set(columns: frozenset[ir.OutputColumn]) -> Result[bool]:
|
|
62
67
|
return unique_set(columns) & non_null_columns(columns)
|
|
63
68
|
|
|
64
69
|
|
|
65
|
-
@analysis(Stratum.CLOSURE)
|
|
70
|
+
@analysis(Stratum.CLOSURE, evaluates=FunctionalDependency)
|
|
66
71
|
def functional_dependency(determinant: frozenset[ir.OutputColumn], dependent: frozenset[ir.OutputColumn]) -> Result[bool]:
|
|
67
72
|
relation = current_arena().program.relation_of(determinant | dependent)
|
|
68
73
|
if relation is None:
|
|
@@ -86,23 +91,38 @@ def _reaches_row_identity(closure: Result[Closure]) -> Result[bool]:
|
|
|
86
91
|
return any_of(gaps)
|
|
87
92
|
|
|
88
93
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
94
|
+
@dataclass(frozen=True)
|
|
95
|
+
class KeyGap:
|
|
96
|
+
"""A known key a closure misses: the key's `reached` attributes and its
|
|
97
|
+
`missing` columns, with the evidence of the key."""
|
|
98
|
+
|
|
99
|
+
reached: frozenset[Attribute]
|
|
100
|
+
missing: tuple[ir.OutputColumn, ...]
|
|
101
|
+
evidence: Result[bool]
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _key_gaps(closure: Result[Closure]) -> list[KeyGap]:
|
|
105
|
+
"""Each known key the closure misses, down through every input the
|
|
106
|
+
closure looked into."""
|
|
92
107
|
relation = closure.value.relation
|
|
93
108
|
identity = RowIdentity(relation)
|
|
94
|
-
gaps: list[
|
|
109
|
+
gaps: list[KeyGap] = []
|
|
95
110
|
for dependency, evidence in _functional_dependencies(relation).value.items():
|
|
96
111
|
if dependency.dependent != identity or dependency.determinant <= closure.value.columns:
|
|
97
112
|
continue
|
|
98
|
-
missing =
|
|
99
|
-
gaps.append(
|
|
113
|
+
missing = tuple(column for column in relation.output_columns if column in dependency.determinant - closure.value.columns)
|
|
114
|
+
gaps.append(KeyGap(dependency.determinant & closure.value.columns, missing, evidence))
|
|
100
115
|
for premise in closure.value.inputs:
|
|
101
116
|
if RowIdentity(premise.value.relation) not in premise.value.columns:
|
|
102
|
-
gaps.extend(
|
|
117
|
+
gaps.extend(_key_gaps(premise))
|
|
103
118
|
return gaps
|
|
104
119
|
|
|
105
120
|
|
|
121
|
+
def _uncovered_keys(closure: Result[Closure]) -> list[Result[bool]]:
|
|
122
|
+
"""Each known key the closure misses, naming its missing columns."""
|
|
123
|
+
return [gap.evidence & unknown("Unique-set columns are not covered", *gap.missing) for gap in _key_gaps(closure)]
|
|
124
|
+
|
|
125
|
+
|
|
106
126
|
# Closure -----------------------------------------------------------------------
|
|
107
127
|
|
|
108
128
|
|
|
@@ -163,10 +183,12 @@ def _closure(relation: ir.RelationExpr, columns: frozenset[Attribute], definite:
|
|
|
163
183
|
if closure is None:
|
|
164
184
|
continue
|
|
165
185
|
inputs[index] = closure
|
|
186
|
+
# The one-to-one calls that carried reached columns down.
|
|
187
|
+
carried = [proof for attribute, proof in delegation.through.items() if attribute in reached]
|
|
166
188
|
for source, attributes in delegation.back.items():
|
|
167
189
|
for attribute in attributes if source in closure.value.columns else ():
|
|
168
190
|
if attribute not in reached:
|
|
169
|
-
reach(attribute, Result(True, delegation.reason, (relation, attribute), [closure.members[source]]))
|
|
191
|
+
reach(attribute, Result(True, delegation.reason, (relation, attribute), [closure.members[source], *carried]))
|
|
170
192
|
for attribute, sources in delegation.computed.items():
|
|
171
193
|
if sources <= closure.value.columns and attribute not in reached:
|
|
172
194
|
reason = "A deterministic function of determined input columns"
|
|
@@ -228,6 +250,8 @@ def _distinct_tags(arms: tuple[ir.OutputColumn, ir.OutputColumn], first: ir.Lite
|
|
|
228
250
|
return first != second
|
|
229
251
|
if first.type == second.type == "string" and all(_binary_text(arm).value for arm in arms):
|
|
230
252
|
return first != second
|
|
253
|
+
if first.type == second.type == "boolean" and all(_boolean(arm) for arm in arms):
|
|
254
|
+
return first != second
|
|
231
255
|
if first.type == second.type == "numeric":
|
|
232
256
|
return (
|
|
233
257
|
all(_signed_integer(arm) or isinstance(arm.scalar_expr, ir.Constant) for arm in arms)
|
|
@@ -362,6 +386,8 @@ class _Delegation:
|
|
|
362
386
|
reason: str
|
|
363
387
|
valid: Callable[[dict[Attribute, Result[bool]], Callable[[Attribute], bool]], bool] | None = None
|
|
364
388
|
computed: dict[Attribute, frozenset[Attribute]] = field(default_factory=dict)
|
|
389
|
+
# Why each attribute `down` maps through a one-to-one call keeps rows apart.
|
|
390
|
+
through: dict[Attribute, Result] = field(default_factory=dict)
|
|
365
391
|
|
|
366
392
|
def run(self, reached: dict[Attribute, Result[bool]], is_definite: Callable[[Attribute], bool]) -> Result[Closure] | None:
|
|
367
393
|
if self.valid is not None and not self.valid(reached, is_definite):
|
|
@@ -419,17 +445,24 @@ def _pass_through(relation: ir.RelationExpr, source: ir.RelationExpr) -> dict[ir
|
|
|
419
445
|
|
|
420
446
|
def _one_to_one(relation: ir.RelationExpr, source: ir.RelationExpr) -> dict[ir.OutputColumn, ir.OutputColumn]:
|
|
421
447
|
"""Each output column that is an input column, or a one-to-one function
|
|
422
|
-
of
|
|
423
|
-
equal on the other."""
|
|
448
|
+
of one (`a + 1` over integers: `reflected_column`), with that column:
|
|
449
|
+
equal on one, equal on the other."""
|
|
424
450
|
passed = _pass_through(relation, source)
|
|
425
451
|
mapping: dict[ir.OutputColumn, ir.OutputColumn] = {}
|
|
426
452
|
for column in relation.output_columns:
|
|
427
|
-
upstream =
|
|
428
|
-
if column not in passed and upstream in source.output_columns
|
|
453
|
+
upstream = reflected_column(column.scalar_expr).value
|
|
454
|
+
if column not in passed and upstream in source.output_columns:
|
|
429
455
|
mapping[column] = upstream
|
|
430
456
|
return mapping | passed
|
|
431
457
|
|
|
432
458
|
|
|
459
|
+
def _through(relation: ir.RelationExpr, source: ir.RelationExpr) -> dict[Attribute, Result]:
|
|
460
|
+
"""Each output column `_one_to_one` maps through a call, with why the call
|
|
461
|
+
keeps different values different (`reflected_column`)."""
|
|
462
|
+
passed = _pass_through(relation, source)
|
|
463
|
+
return {column: reflected_column(column.scalar_expr) for column in _one_to_one(relation, source) if column not in passed}
|
|
464
|
+
|
|
465
|
+
|
|
433
466
|
def _inverse(down: dict[Attribute, Attribute]) -> dict[Attribute, tuple[Attribute, ...]]:
|
|
434
467
|
"""Each input attribute `down` reaches, with every attribute mapped onto it."""
|
|
435
468
|
back: dict[Attribute, tuple[Attribute, ...]] = {}
|
|
@@ -444,7 +477,7 @@ def _row_preserving(relation: ir.RelationExpr, source: ir.RelationExpr) -> _Dele
|
|
|
444
477
|
down[RowIdentity(relation)] = RowIdentity(source)
|
|
445
478
|
return _Delegation(
|
|
446
479
|
source, down, _inverse(down), "Determined in the input",
|
|
447
|
-
computed=_computed(relation, source),
|
|
480
|
+
computed=_computed(relation, source), through=_through(relation, source),
|
|
448
481
|
)
|
|
449
482
|
|
|
450
483
|
|
|
@@ -472,7 +505,8 @@ def _grouped(relation: ir.RelationExpr, source: ir.RelationExpr) -> _Delegation:
|
|
|
472
505
|
back[upstream] = (*back.get(upstream, ()), column)
|
|
473
506
|
# A computed column of an Aggregate that is not a grouping item wraps its
|
|
474
507
|
# value in AnyAggregate, so only grouping items and DISTINCT values remain.
|
|
475
|
-
|
|
508
|
+
through = {column: proof for column, proof in _through(relation, source).items() if column in down}
|
|
509
|
+
return _Delegation(source, down, back, "Determined in the input rows", computed=_computed(relation, source), through=through)
|
|
476
510
|
|
|
477
511
|
|
|
478
512
|
def _picked(aggregate: ir.Aggregate, base: _Delegation) -> list[_Delegation]:
|
|
@@ -501,45 +535,31 @@ def _picked(aggregate: ir.Aggregate, base: _Delegation) -> list[_Delegation]:
|
|
|
501
535
|
def _picked_input(expression: ir.ScalarExpr) -> ir.OutputColumn | None:
|
|
502
536
|
"""The input column whose value on the row an AnyAggregate picks
|
|
503
537
|
`expression` is a one-to-one function of: the AnyAggregate of that
|
|
504
|
-
column, or one with
|
|
505
|
-
(`max(empno + 1)`, `max(empno) + 1`
|
|
506
|
-
|
|
507
|
-
match expression.closed:
|
|
508
|
-
case ir.AnyAggregate(input=ir.ColumnRef(column=column)):
|
|
509
|
-
return column
|
|
538
|
+
column, or one with a one-to-one function inside it or around it
|
|
539
|
+
(`max(empno + 1)`, `max(empno) + 1` over integers: `reflected_operand`)."""
|
|
540
|
+
match reflected_operand(expression).value.closed:
|
|
510
541
|
case ir.AnyAggregate(input=value):
|
|
511
|
-
|
|
512
|
-
case ir.Call(injective_argument=ir.ScalarExpr() as argument):
|
|
513
|
-
column = _picked_input(argument)
|
|
542
|
+
return reflected_column(value).value
|
|
514
543
|
case _:
|
|
515
544
|
return None
|
|
516
|
-
return column if column is not None and exact_numeric(column).value else None
|
|
517
545
|
|
|
518
546
|
|
|
519
547
|
def _computed(relation: ir.RelationExpr, source: ir.RelationExpr) -> dict[Attribute, frozenset[Attribute]]:
|
|
520
|
-
"""Paulley §3.1.4: each column computed from columns of `source` by a
|
|
521
|
-
function
|
|
522
|
-
|
|
523
|
-
|
|
548
|
+
"""Paulley §3.1.4: each column computed from columns of `source` by a
|
|
549
|
+
function that respects their equality (`respected_inputs`), with those
|
|
550
|
+
columns. Any pure function of columns compared by identity does; under
|
|
551
|
+
NOCASE `'a' = 'A'` while `upper(x) || x` tells them apart, and a DOUBLE's
|
|
552
|
+
`-0.0 = 0.0` while its text does not."""
|
|
524
553
|
computed: dict[Attribute, frozenset[Attribute]] = {}
|
|
525
554
|
for column in relation.output_columns:
|
|
526
555
|
if isinstance(column.scalar_expr, ir.ColumnRef):
|
|
527
556
|
continue # Pass-through columns map back directly.
|
|
528
|
-
inputs =
|
|
529
|
-
if inputs is not None:
|
|
557
|
+
inputs = respected_inputs(column.scalar_expr).value
|
|
558
|
+
if inputs is not None and all(read in source.output_columns for read in inputs):
|
|
530
559
|
computed[column] = frozenset(inputs)
|
|
531
560
|
return computed
|
|
532
561
|
|
|
533
562
|
|
|
534
|
-
def _identity_inputs(expression: ir.ScalarExpr, columns: tuple[ir.OutputColumn, ...]) -> tuple[ir.OutputColumn, ...] | None:
|
|
535
|
-
"""The columns `expression` is a pure function of, when all are among
|
|
536
|
-
`columns` and compared by identity."""
|
|
537
|
-
inputs = ir.determinants(expression)
|
|
538
|
-
if inputs is None or not all(column in columns and _identity_comparison(column).value for column in inputs):
|
|
539
|
-
return None
|
|
540
|
-
return inputs
|
|
541
|
-
|
|
542
|
-
|
|
543
563
|
def _join_side(join: ir.Join, left: bool) -> _Delegation:
|
|
544
564
|
side = join.left if left else join.right
|
|
545
565
|
offset = 0 if left else len(join.left.output_columns)
|
|
@@ -583,11 +603,11 @@ def _match_status(join: ir.Join, padded_left: bool) -> frozenset[Attribute] | No
|
|
|
583
603
|
reads = [operand.column for operand in operands if isinstance(operand, ir.ColumnRef)]
|
|
584
604
|
else:
|
|
585
605
|
# Paulley Lemma 9 (L6): a pure conjunct is fixed by the preserved
|
|
586
|
-
# columns it reads, when
|
|
606
|
+
# columns it reads, when it respects their equality (under NOCASE
|
|
587
607
|
# `'a' = 'A'` while `x LIKE 'a%'` tells them apart).
|
|
588
608
|
inputs = ir.determinants(conjunct)
|
|
589
609
|
reads = [column for column in inputs or () if column in preserved.output_columns]
|
|
590
|
-
if inputs is None or not all(
|
|
610
|
+
if inputs is None or not all(respects_equality(conjunct, column).value for column in reads):
|
|
591
611
|
# Volatile, opaque, or read under a collation: only the preserved row fixes it.
|
|
592
612
|
return frozenset({RowIdentity(preserved)})
|
|
593
613
|
referenced.update(outputs[column] for column in reads if column in preserved.output_columns)
|
|
@@ -627,14 +647,15 @@ def _functional_dependencies(relation: ir.RelationExpr) -> Result[Dependencies]:
|
|
|
627
647
|
|
|
628
648
|
identity = RowIdentity(relation)
|
|
629
649
|
columns = set(relation.output_columns)
|
|
630
|
-
for
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
650
|
+
for claim, accepted in current_arena().accepted.items():
|
|
651
|
+
match claim:
|
|
652
|
+
case NonNullUniqueSet():
|
|
653
|
+
pass # Also accepted as its Unique Set, which adds the dependency once.
|
|
654
|
+
case UniqueSet(columns=known) if known <= columns:
|
|
655
|
+
add(known, identity, False, any_of(accepted))
|
|
656
|
+
case FunctionalDependency(determinant=determinant, dependent=dependents) if determinant | dependents <= columns:
|
|
657
|
+
for dependent in dependents:
|
|
658
|
+
add(determinant, dependent, False, any_of(accepted))
|
|
638
659
|
case _:
|
|
639
660
|
pass # Other Knowledge is not a dependency of this relation.
|
|
640
661
|
|
|
@@ -675,7 +696,10 @@ def _functional_dependencies(relation: ir.RelationExpr) -> Result[Dependencies]:
|
|
|
675
696
|
add(relation.output_columns, identity, True, Result(True, f"{relation.operator.upper()} removes duplicate rows", (relation,)))
|
|
676
697
|
case ir.Limit(count=int() as count) if count <= 1:
|
|
677
698
|
add((), identity, True, Result(True, "LIMIT keeps at most one row", (relation,)))
|
|
678
|
-
case ir.
|
|
699
|
+
case ir.Project():
|
|
700
|
+
for determinant, dependent, strict, evidence in _merged_key_dependencies(relation):
|
|
701
|
+
add(determinant, dependent, strict, evidence)
|
|
702
|
+
case ir.Alias() | ir.NamedRelation() | ir.Limit() | ir.SetOperation() | ir.OpaqueRelation():
|
|
679
703
|
pass
|
|
680
704
|
case _:
|
|
681
705
|
assert_never(relation)
|
|
@@ -686,7 +710,7 @@ def _equality_dependencies(conjuncts: tuple[ir.ScalarExpr, ...], outputs: dict[i
|
|
|
686
710
|
"""Dependencies of conjuncts that hold on every row: `a = b` and
|
|
687
711
|
`a IS NOT DISTINCT FROM b` both ways, `a = literal` (or IS NOT DISTINCT
|
|
688
712
|
FROM it) and `a IS NULL` from the empty set, and `b = f(x...)` from
|
|
689
|
-
`x...` (Paulley Claim 20) when f
|
|
713
|
+
`x...` (Paulley Claim 20) when f respects their equality."""
|
|
690
714
|
for conjunct in conjuncts:
|
|
691
715
|
evidence = Result(True, f"{clause} conjunct", (conjunct,))
|
|
692
716
|
match conjunct:
|
|
@@ -697,37 +721,38 @@ def _equality_dependencies(conjuncts: tuple[ir.ScalarExpr, ...], outputs: dict[i
|
|
|
697
721
|
for first, second in _predicate_equalities((conjunct,)):
|
|
698
722
|
if first in outputs and second in outputs and _identity_comparison(second).value:
|
|
699
723
|
yield (outputs[first],), outputs[second], evidence
|
|
700
|
-
# An equality
|
|
701
|
-
# values that differ: it gives no dependency.
|
|
724
|
+
# An equality with a lossy cast, or under a collation, relates
|
|
725
|
+
# values that differ: it gives no dependency (`fixes`).
|
|
702
726
|
# IS NOT DISTINCT FROM equates NULLs too, so NULL agrees with NULL.
|
|
703
727
|
case (
|
|
704
728
|
ir.Equality(left=ir.ColumnRef(column=first) as left, right=ir.ColumnRef(column=second) as right)
|
|
705
729
|
| ir.NullSafeEquality(left=ir.ColumnRef(column=first) as left, right=ir.ColumnRef(column=second) as right)
|
|
706
730
|
) if first in outputs and second in outputs:
|
|
707
|
-
if
|
|
731
|
+
if fixes(right, left).value:
|
|
708
732
|
yield (outputs[first],), outputs[second], evidence
|
|
709
|
-
if
|
|
733
|
+
if fixes(left, right).value:
|
|
710
734
|
yield (outputs[second],), outputs[first], evidence
|
|
711
735
|
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))
|
|
736
|
+
ir.Equality(left=ir.ColumnRef(column=column) as operand, right=ir.Constant() as constant)
|
|
737
|
+
| ir.Equality(left=ir.Constant() as constant, right=ir.ColumnRef(column=column) as operand)
|
|
738
|
+
| ir.NullSafeEquality(left=ir.ColumnRef(column=column) as operand, right=ir.Constant() as constant)
|
|
739
|
+
| ir.NullSafeEquality(left=ir.Constant() as constant, right=ir.ColumnRef(column=column) as operand)
|
|
716
740
|
) if column in outputs:
|
|
717
|
-
if
|
|
741
|
+
if fixes(operand, constant).value:
|
|
718
742
|
yield (), outputs[column], evidence
|
|
719
743
|
case ir.IsNull(operand=ir.ColumnRef(column=column)) if column in outputs:
|
|
720
744
|
yield (), outputs[column], evidence
|
|
721
745
|
case ir.Equality(left=left, right=right):
|
|
722
746
|
for target, value in ((left, right), (right, left)):
|
|
723
|
-
|
|
747
|
+
# The comparison must lose nothing, or `b` equals `f(x)` for values of `b` that differ.
|
|
748
|
+
if not (isinstance(target, ir.ColumnRef) and target.column in outputs and fixes(target, value).value):
|
|
724
749
|
continue
|
|
725
|
-
inputs =
|
|
726
|
-
if inputs is not None:
|
|
750
|
+
inputs = respected_inputs(value).value
|
|
751
|
+
if inputs is not None and all(column in outputs for column in inputs):
|
|
727
752
|
yield tuple(outputs[column] for column in inputs), outputs[target.column], evidence
|
|
728
|
-
# One-to-one: `b = a + 1` also gives b -> a,
|
|
729
|
-
source =
|
|
730
|
-
if source in outputs
|
|
753
|
+
# One-to-one: `b = a + 1` also gives b -> a, the comparison fixing each side.
|
|
754
|
+
source = reflected_column(value).value
|
|
755
|
+
if source in outputs:
|
|
731
756
|
yield (outputs[target.column],), outputs[source], evidence
|
|
732
757
|
case _:
|
|
733
758
|
pass # Other conjuncts only remove rows.
|
|
@@ -781,25 +806,26 @@ def _matched_dependencies(join: ir.Join, outputs: dict[ir.OutputColumn, ir.Outpu
|
|
|
781
806
|
column or a literal, that fixes it, and it fixes each left column ON pins
|
|
782
807
|
to it. `d.deptno = e.mgr AND d.deptno = e.comm` gives mgr -> comm."""
|
|
783
808
|
right = join.right.output_columns
|
|
784
|
-
pairs: list[tuple[ir.
|
|
809
|
+
pairs: list[tuple[ir.ColumnRef, ir.ScalarExpr, ir.ScalarExpr]] = []
|
|
785
810
|
for conjunct in join.conjuncts:
|
|
786
811
|
match conjunct:
|
|
787
812
|
case ir.Equality(left=first, right=second) | ir.NullSafeEquality(left=first, right=second):
|
|
788
|
-
pairs.extend((other
|
|
813
|
+
pairs.extend((other, value, conjunct) for other, value in ((first, second), (second, first)) if isinstance(other, ir.ColumnRef) and other.column in right)
|
|
789
814
|
case _:
|
|
790
815
|
pass # Other conjuncts pin nothing.
|
|
791
|
-
for
|
|
816
|
+
for matched, value, conjunct in pairs:
|
|
792
817
|
# What fixes the right column: a left column or a literal it is pinned to.
|
|
793
818
|
match value:
|
|
794
|
-
case ir.ColumnRef(column=source) if source in outputs and
|
|
819
|
+
case ir.ColumnRef(column=source) if source in outputs and fixes(matched, value).value:
|
|
795
820
|
determinant: tuple[ir.OutputColumn, ...] = (outputs[source],)
|
|
796
|
-
case ir.Constant() if
|
|
821
|
+
case ir.Constant() if fixes(matched, value).value:
|
|
797
822
|
determinant = ()
|
|
798
823
|
case _:
|
|
799
824
|
continue
|
|
825
|
+
column = matched.column
|
|
800
826
|
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
|
|
827
|
+
if other.column is column and other_conjunct is not conjunct and isinstance(bound, ir.ColumnRef) and bound.column in outputs:
|
|
828
|
+
if fixes(bound, other).value:
|
|
803
829
|
evidence = Result(True, f"ON conjuncts equal through {quoted(column.name)} of the matched right row", (conjunct, other_conjunct))
|
|
804
830
|
yield determinant, outputs[bound.column], True, evidence
|
|
805
831
|
|
|
@@ -834,14 +860,14 @@ def _outer_on_dependencies(join: ir.Join, outputs: dict[ir.OutputColumn, ir.Outp
|
|
|
834
860
|
continue
|
|
835
861
|
match value:
|
|
836
862
|
case ir.ColumnRef(column=other) if other in padded.output_columns:
|
|
837
|
-
if
|
|
863
|
+
if fixes(bound, value).value:
|
|
838
864
|
yield (outputs[other],), outputs[bound.column], True, evidence
|
|
839
865
|
case ir.ColumnRef(column=other):
|
|
840
|
-
if
|
|
866
|
+
if fixes(bound, value).value:
|
|
841
867
|
yield status, outputs[bound.column], True, evidence
|
|
842
|
-
if
|
|
868
|
+
if fixes(value, bound).value:
|
|
843
869
|
yield (outputs[bound.column],), outputs[other], False, evidence
|
|
844
|
-
case ir.Constant() if
|
|
870
|
+
case ir.Constant() if fixes(bound, value).value:
|
|
845
871
|
yield status, outputs[bound.column], True, evidence
|
|
846
872
|
case _:
|
|
847
873
|
pass # A NULL, an unpinned constant, or an expression binds nothing.
|
|
@@ -867,7 +893,7 @@ def _full_on_dependencies(join: ir.Join, outputs: dict[ir.OutputColumn, ir.Outpu
|
|
|
867
893
|
for bound, value in ((first, second), (second, first)):
|
|
868
894
|
match bound, value:
|
|
869
895
|
case ir.ColumnRef(column=column), ir.ColumnRef(column=other) if (
|
|
870
|
-
column in padded.output_columns and other not in padded.output_columns and
|
|
896
|
+
column in padded.output_columns and other not in padded.output_columns and fixes(bound, value).value
|
|
871
897
|
):
|
|
872
898
|
yield status | {outputs[other]}, outputs[column], False, evidence
|
|
873
899
|
case _:
|
|
@@ -876,6 +902,84 @@ def _full_on_dependencies(join: ir.Join, outputs: dict[ir.OutputColumn, ir.Outpu
|
|
|
876
902
|
pass # Other conjuncts hold on matched rows only.
|
|
877
903
|
|
|
878
904
|
|
|
905
|
+
def _merged_key_dependencies(project: ir.Project):
|
|
906
|
+
"""A FULL join on a key of both inputs, projected as the coalesced key.
|
|
907
|
+
|
|
908
|
+
`SELECT coalesce(a.k, b.k) AS k FROM a FULL JOIN b ON a.k = b.k` (the
|
|
909
|
+
merged column of `USING (k)` is one): when the pairs of columns the ON
|
|
910
|
+
equates (`=` or `IS NOT DISTINCT FROM`) are every conjunct of it, a Unique Set of `a` on the left ones and
|
|
911
|
+
of `b` on the right ones, the coalesced columns are a Unique Set of the
|
|
912
|
+
join's rows, laxly: a row's non-NULL key value is that of its `a` row, of
|
|
913
|
+
its `b` row, or of both, equal (the comparison loses nothing and the
|
|
914
|
+
coalesce keeps the value), so two rows with it share an `a` row or a `b`
|
|
915
|
+
row (excluded: each repeats only on a repeated key) or one is an unmatched
|
|
916
|
+
row whose key equals one of the other, which ON would have matched. A row
|
|
917
|
+
with a NULL key part is unmatched and coalesces to NULL, and the Unique Set
|
|
918
|
+
does not constrain it (`IS NOT DISTINCT FROM` also matches NULL to NULL,
|
|
919
|
+
which merges to the same NULL; a non-NULL value matches as with `=`). Another ON conjunct would leave two unmatched rows
|
|
920
|
+
of one value, so it gives nothing. Rows a WHERE drops keep the property."""
|
|
921
|
+
found = _full_join_beneath(project)
|
|
922
|
+
if found is None:
|
|
923
|
+
return
|
|
924
|
+
join, outputs = found
|
|
925
|
+
inputs = {output: column for column, output in _join_outputs(join).items()}
|
|
926
|
+
pairs: list[tuple[ir.OutputColumn, ir.OutputColumn]] = []
|
|
927
|
+
for conjunct in join.conjuncts:
|
|
928
|
+
match conjunct:
|
|
929
|
+
case ir.Equality(left=ir.ColumnRef(column=first) as one, right=ir.ColumnRef(column=second) as other) | ir.NullSafeEquality(
|
|
930
|
+
left=ir.ColumnRef(column=first) as one, right=ir.ColumnRef(column=second) as other
|
|
931
|
+
):
|
|
932
|
+
for left, right in ((first, second), (second, first)):
|
|
933
|
+
if left in join.left.output_columns and right in join.right.output_columns:
|
|
934
|
+
if not exact_comparison(one, other).value:
|
|
935
|
+
return
|
|
936
|
+
pairs.append((left, right))
|
|
937
|
+
break
|
|
938
|
+
else:
|
|
939
|
+
return # An equality within one input holds on matched rows only.
|
|
940
|
+
case _:
|
|
941
|
+
return # Any other conjunct leaves matched rows unrelated to equal keys.
|
|
942
|
+
if not pairs:
|
|
943
|
+
return
|
|
944
|
+
passed = _pass_through(project, project.input)
|
|
945
|
+
choices: list[list[ir.OutputColumn]] = [[] for _ in pairs]
|
|
946
|
+
for column in project.output_columns:
|
|
947
|
+
match column.scalar_expr:
|
|
948
|
+
case ir.Coalesce(arguments=(ir.ColumnRef(column=first), ir.ColumnRef(column=second))):
|
|
949
|
+
# USING's merged column reads the columns its own Project passes through.
|
|
950
|
+
first, second = passed.get(first, first), passed.get(second, second)
|
|
951
|
+
if first not in outputs or second not in outputs or scalar_typing(column.scalar_expr).value is None:
|
|
952
|
+
continue
|
|
953
|
+
taken = (inputs[outputs[first]], inputs[outputs[second]])
|
|
954
|
+
for index, (left, right) in enumerate(pairs):
|
|
955
|
+
if taken in ((left, right), (right, left)):
|
|
956
|
+
choices[index].append(column)
|
|
957
|
+
case _:
|
|
958
|
+
pass
|
|
959
|
+
if not all(choices):
|
|
960
|
+
return
|
|
961
|
+
left_key, right_key = frozenset(left for left, _ in pairs), frozenset(right for _, right in pairs)
|
|
962
|
+
proof = unique_set(left_key) & unique_set(right_key)
|
|
963
|
+
if not proof.value:
|
|
964
|
+
return
|
|
965
|
+
evidence = Result(True, "A FULL join on a key of both inputs matches each key value once", (project,), [proof])
|
|
966
|
+
for determinant in product(*choices):
|
|
967
|
+
yield determinant, RowIdentity(project), False, evidence
|
|
968
|
+
|
|
969
|
+
|
|
970
|
+
def _full_join_beneath(project: ir.Project) -> tuple[ir.Join, dict[ir.OutputColumn, ir.OutputColumn]] | None:
|
|
971
|
+
"""The FULL join under `project`, through the filters between them, with
|
|
972
|
+
each column of the project's input mapped to the join's output column it
|
|
973
|
+
passes through."""
|
|
974
|
+
source = project.input
|
|
975
|
+
mapping: dict[ir.OutputColumn, ir.OutputColumn] = {column: column for column in source.output_columns}
|
|
976
|
+
while isinstance(source, ir.Filter):
|
|
977
|
+
through = _pass_through(source, source.input)
|
|
978
|
+
mapping = {column: through[passed] for column, passed in mapping.items() if passed in through}
|
|
979
|
+
source = source.input
|
|
980
|
+
return (source, mapping) if isinstance(source, ir.Join) and source.kind == "full" else None
|
|
981
|
+
|
|
982
|
+
|
|
879
983
|
def minimal_keys(relation: ir.RelationExpr, max_size: int = 3) -> list[tuple[ir.OutputColumn, ...]]:
|
|
880
984
|
"""The minimal Unique Sets of `relation`, in output order.
|
|
881
985
|
|
|
@@ -889,11 +993,32 @@ def minimal_keys(relation: ir.RelationExpr, max_size: int = 3) -> list[tuple[ir.
|
|
|
889
993
|
|
|
890
994
|
if not columns or not unique(columns):
|
|
891
995
|
return []
|
|
892
|
-
keys: list[tuple[ir.OutputColumn, ...]] = []
|
|
893
|
-
|
|
894
|
-
|
|
996
|
+
keys: list[tuple[ir.OutputColumn, ...]] = [(column,) for column in columns if max_size >= 1 and unique((column,))]
|
|
997
|
+
candidates = columns
|
|
998
|
+
required: tuple[ir.OutputColumn, ...] = ()
|
|
999
|
+
if max_size > 1 and keys:
|
|
1000
|
+
singletons = {key[0] for key in keys}
|
|
1001
|
+
candidates = tuple(column for column in columns if column not in singletons)
|
|
1002
|
+
# A larger minimal key must avoid every singleton key. If their complement
|
|
1003
|
+
# cannot determine the row, neither can any subset of it.
|
|
1004
|
+
if len(candidates) < 2 or not unique(candidates):
|
|
1005
|
+
return keys
|
|
1006
|
+
elif max_size > 1:
|
|
1007
|
+
# Every Unique Set holds each column the others cannot do without: a set
|
|
1008
|
+
# lacking it is a subset of those others, so not unique either. When
|
|
1009
|
+
# those columns alone are unique, they are the only minimal Unique Set.
|
|
1010
|
+
required = tuple(column for column in columns if not unique(tuple(other for other in columns if other is not column)))
|
|
1011
|
+
if required and unique(required):
|
|
1012
|
+
return [required]
|
|
1013
|
+
candidates = tuple(column for column in columns if column not in required)
|
|
1014
|
+
position = {column: index for index, column in enumerate(columns)}
|
|
1015
|
+
for size in range(max(2, len(required) + 1), min(max_size, len(required) + len(candidates)) + 1):
|
|
1016
|
+
found = []
|
|
1017
|
+
for extra in combinations(candidates, size - len(required)):
|
|
1018
|
+
members = tuple(sorted((*required, *extra), key=position.__getitem__))
|
|
895
1019
|
if not any(set(key) <= set(members) for key in keys) and unique(members):
|
|
896
|
-
|
|
1020
|
+
found.append(members)
|
|
1021
|
+
keys.extend(sorted(found, key=lambda members: [position[column] for column in members]))
|
|
897
1022
|
if keys:
|
|
898
1023
|
return keys
|
|
899
1024
|
members = columns
|