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.
Files changed (69) hide show
  1. sqlassert/__init__.py +1 -2
  2. sqlassert/check.py +88 -13
  3. sqlassert/declared_types.py +158 -0
  4. sqlassert/diagnostics.py +15 -7
  5. sqlassert/dialects.py +259 -107
  6. sqlassert/discovery/bigquery.py +4 -2
  7. sqlassert/discovery/databricks.py +26 -5
  8. sqlassert/discovery/duckdb.py +49 -7
  9. sqlassert/discovery/fetcher.py +137 -58
  10. sqlassert/discovery/information_schema.py +31 -6
  11. sqlassert/discovery/mysql.py +21 -4
  12. sqlassert/discovery/postgres.py +28 -20
  13. sqlassert/discovery/redshift.py +3 -2
  14. sqlassert/discovery/snowflake.py +5 -2
  15. sqlassert/discovery/trino.py +2 -2
  16. sqlassert/functions/__init__.py +10 -0
  17. sqlassert/functions/load.py +375 -0
  18. sqlassert/functions/table.py +2721 -0
  19. sqlassert/hazards.py +249 -88
  20. sqlassert/ir/__init__.py +15 -4
  21. sqlassert/ir/convert/__init__.py +13 -0
  22. sqlassert/ir/convert/aggregation.py +438 -0
  23. sqlassert/ir/convert/expressions.py +581 -0
  24. sqlassert/ir/convert/joins.py +264 -0
  25. sqlassert/ir/convert/markers.py +249 -0
  26. sqlassert/ir/convert/parser.py +249 -0
  27. sqlassert/ir/convert/queries.py +259 -0
  28. sqlassert/ir/convert/schema.py +537 -0
  29. sqlassert/ir/convert/scopes.py +205 -0
  30. sqlassert/ir/convert/selects.py +352 -0
  31. sqlassert/ir/convert/shared.py +428 -0
  32. sqlassert/ir/convert/sources.py +433 -0
  33. sqlassert/ir/convert/subqueries.py +364 -0
  34. sqlassert/ir/convert/value_types.py +78 -0
  35. sqlassert/ir/convert/windows.py +275 -0
  36. sqlassert/ir/model.py +417 -146
  37. sqlassert/ir/names.py +63 -0
  38. sqlassert/main.py +7 -10
  39. sqlassert/properties.py +12 -1
  40. sqlassert/provenance.py +5 -1
  41. sqlassert/python_engine.py +104 -44
  42. sqlassert/reporting.py +33 -32
  43. sqlassert/rewrites.py +111 -61
  44. sqlassert/rules/STYLEGUIDE.md +3 -2
  45. sqlassert/rules/causes/__init__.py +41 -0
  46. sqlassert/rules/causes/coverage.py +113 -0
  47. sqlassert/rules/causes/domain.py +123 -0
  48. sqlassert/rules/causes/joins.py +73 -0
  49. sqlassert/rules/causes/nulls.py +154 -0
  50. sqlassert/rules/causes/unique.py +564 -0
  51. sqlassert/rules/domain.py +9 -8
  52. sqlassert/rules/equality.py +6 -147
  53. sqlassert/rules/exactly_one.py +2 -1
  54. sqlassert/rules/foreign_key.py +8 -9
  55. sqlassert/rules/join_cardinality.py +277 -43
  56. sqlassert/rules/nullability.py +8 -8
  57. sqlassert/rules/uniqueness.py +212 -87
  58. sqlassert/rules/value_typing.py +470 -0
  59. sqlassert/sql_parse.py +28 -1
  60. sqlassert/suggest.py +13 -17
  61. sqlassert-0.4.2.dist-info/METADATA +239 -0
  62. sqlassert-0.4.2.dist-info/RECORD +72 -0
  63. sqlassert/ir/convert.py +0 -3509
  64. sqlassert-0.3.3.dist-info/METADATA +0 -807
  65. sqlassert-0.3.3.dist-info/RECORD +0 -46
  66. {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/WHEEL +0 -0
  67. {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/entry_points.txt +0 -0
  68. {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/licenses/LICENSE +0 -0
  69. {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,123 @@
1
+ """Why an Enumerated Domain or an exhaustive CASE is not proved: where the
2
+ column stops being enumerated, or which source admits a value not listed.
3
+
4
+ Two ways to fail. A domain that is not known: the walk reads `_domain`'s
5
+ evidence down to the leaves that know none (a table column with no CHECK or
6
+ ENUM, an expression whose values are not enumerated, a relation sqlassert does
7
+ not model). A value not listed: one Cause, the values the marker misses,
8
+ each with the sources that admit it (a literal, a CHECK, a DECLARE ENUM).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections.abc import Iterator
14
+
15
+ from sqlassert import ir
16
+ from sqlassert import properties as props
17
+ from sqlassert.diagnostics import quoted
18
+ from sqlassert.python_engine import Result, current_arena
19
+ from sqlassert.reporting import Step
20
+ from sqlassert.rules.causes.nulls import reading_alias
21
+ from sqlassert.rules.causes.unique import _Place, asserted_place, brief
22
+ from sqlassert.rules.domain import _domain, _expression_domain, _listed, _operand_name, _render
23
+
24
+
25
+ def explain_domain(property: props.EnumeratedDomain | props.ExhaustiveCase) -> Step | None:
26
+ program = current_arena().program
27
+ match property:
28
+ case props.EnumeratedDomain(column=column, values=values):
29
+ domain = _domain(column)
30
+ relation = program.relation_of(frozenset({column}))
31
+ place = asserted_place(relation) if relation is not None else _Place(column.name)
32
+ name, listed, lister, anchor = quoted(column.name), values, "the ENUM", column
33
+ case props.ExhaustiveCase(case=case):
34
+ domain = _expression_domain(case.operand)
35
+ place = _Place(brief(case.origin.detail), case.origin if case.origin.span else None)
36
+ name, listed, lister = _operand_name(case.operand), _listed(case), "no WHEN arm"
37
+ anchor = case.operand.column if isinstance(case.operand, ir.ColumnRef) else None
38
+ if domain.value is None:
39
+ shown: dict[tuple[str, str | None], Step] = {}
40
+ for leaf in _unenumerated(domain):
41
+ step = _cause(leaf, anchor, place)
42
+ shown.setdefault((step.text, step.code), step)
43
+ steps = tuple(shown.values())
44
+ top = Step(f"{place.subject}: no finite domain is known for {name}", False, None, steps=steps)
45
+ return top if top.causes() else None
46
+ missing = sorted(domain.value - listed, key=lambda value: (value.type, value.text))
47
+ if not missing:
48
+ return None
49
+ details = tuple(
50
+ f"{value.sql()} comes from {'; '.join(dict.fromkeys(_source(leaf, value) for leaf in _admitting(domain, value)))}"
51
+ for value in missing
52
+ )
53
+ verb = "does not list" if lister == "the ENUM" else "lists"
54
+ cause = Step(f"{name} may be {_render(frozenset(missing))}, which {lister} {verb}", False, place.origin, "sql", "unlisted-value",
55
+ (*details, f"list {'it' if len(missing) == 1 else 'them'}, or keep {'it' if len(missing) == 1 else 'them'} out where the values come from"))
56
+ return Step(f"{place.subject}: {name} may take a value not listed", False, None, steps=(cause,))
57
+
58
+
59
+ def _unenumerated(result: Result, seen: set[int] | None = None) -> Iterator[Result]:
60
+ """The leaves of domain evidence that know no domain."""
61
+ seen = set() if seen is None else seen
62
+ if id(result) in seen or result.value is not None:
63
+ return
64
+ seen.add(id(result))
65
+ children = [premise for premise in result.premises if premise.value is None]
66
+ if not children:
67
+ yield result
68
+ return
69
+ for child in children:
70
+ yield from _unenumerated(child, seen)
71
+
72
+
73
+ def _admitting(result: Result, value: ir.LiteralValue, seen: set[int] | None = None) -> Iterator[Result]:
74
+ """The leaves of domain evidence whose values include `value`."""
75
+ seen = set() if seen is None else seen
76
+ if id(result) in seen or not isinstance(result.value, frozenset) or value not in result.value:
77
+ return
78
+ seen.add(id(result))
79
+ children = [premise for premise in result.premises if isinstance(premise.value, frozenset) and value in premise.value]
80
+ if not children or "is known to be one of" in result.reason:
81
+ yield result
82
+ return
83
+ for child in children:
84
+ yield from _admitting(child, value, seen)
85
+
86
+
87
+ def _source(leaf: Result, value: ir.LiteralValue) -> str:
88
+ """Where a value enters a domain."""
89
+ subject = next((subject for subject in leaf.subjects if isinstance(subject, ir.Node)), None)
90
+ if isinstance(subject, ir.Constant):
91
+ return f"the literal {value.sql()}" + (f" (line {subject.origin.line})" if subject.origin.line else "")
92
+ if isinstance(subject, ir.OutputColumn) and "is known to be one of" in leaf.reason:
93
+ if _declared(leaf):
94
+ return f"the DECLARE ENUM on {quoted(subject.name)}"
95
+ owner = current_arena().program.column_to_parent_relation_index.get(subject)
96
+ where = f" in {owner.name}" if isinstance(owner, ir.NamedRelation | ir.Alias) else ""
97
+ return f"the CHECK on {quoted(subject.name)}{where}"
98
+ return leaf.reason[0].lower() + leaf.reason[1:]
99
+
100
+
101
+ def _declared(result: Result) -> bool:
102
+ """Whether evidence rests on a Property Declaration rather than Schema Knowledge."""
103
+ return result.reason.startswith("Declared ") or any(_declared(premise) for premise in result.premises)
104
+
105
+
106
+ def _cause(leaf: Result, anchor: ir.OutputColumn | None, place: _Place) -> Step:
107
+ subject = next((subject for subject in leaf.subjects if isinstance(subject, ir.Node)), None)
108
+ if isinstance(subject, ir.OutputColumn) and leaf.reason.endswith("is not enumerated"):
109
+ owner = current_arena().program.column_to_parent_relation_index.get(subject)
110
+ if isinstance(owner, ir.OpaqueRelation):
111
+ return Step(f"{quoted(subject.name)} comes from a relation sqlassert does not model", False, place.origin, "sqlassert", "not-modelled")
112
+ reader = reading_alias(anchor, subject) if anchor is not None else None
113
+ read = _Place(brief(reader.origin.detail), reader.origin) if reader is not None else place
114
+ table = owner.name if isinstance(owner, ir.NamedRelation) else "its table"
115
+ return Step(f"{read.subject}: {quoted(subject.name)} is not enumerated", False, read.origin, "declare", "not-enumerated",
116
+ (f"a CHECK ({subject.name} IN (...)) in {table}, or DECLARE ENUM({subject.name} IN (...)), states its values",))
117
+ if isinstance(subject, ir.ScalarExpr) and leaf.reason == "Values of this expression are not enumerated":
118
+ written = brief(subject.origin.detail)
119
+ if isinstance(subject, ir.OpaqueExpression) or isinstance(subject, ir.Call) and not subject.function.modelled:
120
+ return Step(f"{written}: sqlassert does not model its values", False, place.origin, "sqlassert", "not-modelled")
121
+ return Step(f"{written}: its values are not enumerated", False, place.origin, "sql", "computed-value",
122
+ ("only literals, coalesce and CASE of enumerated values, and enumerated columns enumerate a value",))
123
+ return Step(leaf.reason, False, place.origin, "sqlassert", "not-modelled")
@@ -0,0 +1,73 @@
1
+ """Why a Join Cardinality or Exactly One Join assertion is UNKNOWN.
2
+
3
+ A join matches each row of one input at most once in `matched` when the
4
+ columns its ON binds in `matched` are a Unique Set of it: the Unique Set walk,
5
+ started at `matched` from those columns, finds what it lacks. The join is
6
+ the Cause, with its Unproved Join Reason in that direction, unless the walk
7
+ finds one below. An Exactly One Join also needs at least one match (the
8
+ Referential Coverage walk) and non-null left columns (the Null Source walk).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from sqlassert import ir
14
+ from sqlassert import properties as props
15
+ from sqlassert.reporting import Step
16
+ from sqlassert.rules.causes.unique import _Place, brief, join_cause, side_place, walk_unique
17
+ from sqlassert.rules.join_cardinality import Side, _bound_columns, many_to_one_join, one_to_many_join
18
+ from sqlassert.rules.uniqueness import _closure
19
+
20
+
21
+
22
+ def explain_join(property: props.ManyToOneJoin | props.OneToManyJoin | props.OneToOneJoin | props.UniqueJoin | props.ExactlyOneJoin) -> Step | None:
23
+ join = property.join
24
+ match property:
25
+ case props.ManyToOneJoin():
26
+ marker, steps = "MANY TO ONE", at_most_one(join, ("right",))
27
+ case props.OneToManyJoin():
28
+ marker, steps = "ONE TO MANY", at_most_one(join, ("left",))
29
+ case props.OneToOneJoin():
30
+ # Both directions are needed: each that fails says why.
31
+ marker, steps = "ONE TO ONE", at_most_one(join, ("right", "left"))
32
+ case props.UniqueJoin():
33
+ # Either direction would do: each says why it fails.
34
+ marker, steps = "UNIQUE", at_most_one(join, ("right", "left"))
35
+ case props.ExactlyOneJoin():
36
+ marker, steps = "EXACTLY ONE", exactly_one(join)
37
+ top = Step(f"{brief(join.origin.detail)}: {marker} is not proved", False, None, steps=steps)
38
+ return top if top.causes() else None
39
+
40
+
41
+ def at_most_one(join: ir.Join, directions: tuple[Side, ...]) -> tuple[Step, ...]:
42
+ """For each direction not proved, why a row of the other input may match
43
+ several rows of that input."""
44
+ steps = []
45
+ for matched in directions:
46
+ if (many_to_one_join(join) if matched == "right" else one_to_many_join(join)).value:
47
+ continue
48
+ side = join.right if matched == "right" else join.left
49
+ if join.lateral and matched == "right":
50
+ steps.append(Step(f"{brief(join.origin.detail)} repeats each row of its left input once per row it returns", False, join.origin, "sql", "table-function"))
51
+ continue
52
+ bound = _bound_columns(join, matched).value
53
+ closure = _closure(side, frozenset(bound.columns), frozenset(bound.definite))
54
+ steps.append(join_cause(join, matched, walk_unique(closure, side_place(side, join))))
55
+ return tuple(steps)
56
+
57
+
58
+ def exactly_one(join: ir.Join) -> tuple[Step, ...]:
59
+ """At most one match, at least one, and non-null left columns: each that fails."""
60
+ from sqlassert.rules.causes.coverage import at_least_one
61
+ from sqlassert.rules.causes.nulls import null_causes
62
+ from sqlassert.rules.exactly_one import _cross_equalities
63
+
64
+ if join.kind == "anti":
65
+ return (Step(f"{brief(join.origin.detail)}: an anti join drops the rows it matches", False, join.origin, "sql", "anti-join"),)
66
+ steps = list(at_most_one(join, ("right",)))
67
+ steps.extend(at_least_one(join))
68
+ pairs, _ = _cross_equalities(join)
69
+ lefts = frozenset(left for left, _ in pairs)
70
+ nullable = null_causes(lefts, _Place(brief(join.origin.detail), join.origin))
71
+ if nullable:
72
+ steps.append(Step("a NULL left value matches no row", False, None, steps=nullable))
73
+ return tuple(steps)
@@ -0,0 +1,154 @@
1
+ """Why a column may be NULL, or hold a NULL element: its Null Sources, each
2
+ a Cause where it is written.
3
+
4
+ The walk reads the evidence `_null_sources` (and `_column_elements`) left,
5
+ down to the leaves that are not proved: a join that pads the column, a
6
+ nullable table column (named by the FROM item that reads it), a NULL literal,
7
+ a CASE with no ELSE, an aggregate over no rows, or an expression or relation
8
+ sqlassert does not model. Proved branches (a source a condition removed) are
9
+ not followed.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Iterator
15
+
16
+ from sqlassert import ir
17
+ from sqlassert.diagnostics import quoted
18
+ from sqlassert.python_engine import Result, current_arena
19
+ from sqlassert.reporting import Step
20
+ from sqlassert.rules.causes.unique import _Place, asserted_place, brief
21
+ from sqlassert.rules.nullability import _column_elements, _null_sources, non_null_column
22
+
23
+
24
+ def explain_non_null(columns: frozenset[ir.OutputColumn]) -> Step | None:
25
+ program = current_arena().program
26
+ relation = program.relation_of(columns)
27
+ if relation is None:
28
+ return None
29
+ place = asserted_place(relation)
30
+ steps = null_causes(columns, place)
31
+ ordered = [column for column in relation.output_columns if column in columns and not non_null_column(column).value]
32
+ top = Step(f"{place.subject}: {', '.join(quoted(column.name) for column in ordered)} may be NULL", False, None, steps=steps)
33
+ return top if top.causes() else None
34
+
35
+
36
+ def explain_elements(columns: frozenset[ir.OutputColumn]) -> Step | None:
37
+ program = current_arena().program
38
+ relation = program.relation_of(columns)
39
+ if relation is None:
40
+ return None
41
+ place = asserted_place(relation)
42
+ steps: list[Step] = []
43
+ for column in relation.output_columns:
44
+ if column in columns and not (elements := _column_elements(column)).value:
45
+ steps.extend(_dedupe(_cause(leaf, alias, column, place, elements=True) for leaf, alias in _leaves(elements)))
46
+ top = Step(f"{place.subject}: an element may be NULL", False, None, steps=tuple(steps))
47
+ return top if top.causes() else None
48
+
49
+
50
+ def null_causes(columns: frozenset[ir.OutputColumn], place: _Place) -> tuple[Step, ...]:
51
+ """A Cause for each Null Source of each column that may be NULL."""
52
+ relation = current_arena().program.relation_of(columns)
53
+ ordered = [column for column in relation.output_columns if column in columns] if relation is not None else sorted(columns, key=lambda column: column.name)
54
+ steps: list[Step] = []
55
+ for column in ordered:
56
+ if non_null_column(column).value:
57
+ continue
58
+ steps.extend(_dedupe(_cause(leaf, alias, column, place) for leaf, alias in _leaves(_null_sources(column))))
59
+ return tuple(steps)
60
+
61
+
62
+ def _leaves(result: Result, alias: ir.Alias | None = None, seen: set[int] | None = None) -> Iterator[tuple[Result, ir.Alias | None]]:
63
+ """The unproved leaves of Null Source evidence, each with the nearest
64
+ Alias the walk passed through on the way to it."""
65
+ seen = set() if seen is None else seen
66
+ if id(result) in seen or result.value is True or (isinstance(result.value, frozenset) and not result.value):
67
+ return
68
+ seen.add(id(result))
69
+ program = current_arena().program
70
+ for subject in result.subjects:
71
+ if isinstance(subject, ir.OutputColumn) and isinstance(owner := program.column_to_parent_relation_index.get(subject), ir.Alias):
72
+ alias = owner
73
+ if result.reason.startswith("With no ELSE"):
74
+ yield result, alias
75
+ return
76
+ children = list(result.members.values()) if result.members else result.premises
77
+ if not children:
78
+ if result.value is False:
79
+ yield result, alias
80
+ return
81
+ for child in children:
82
+ yield from _leaves(child, alias, seen)
83
+
84
+
85
+ def _cause(leaf: Result, alias: ir.Alias | None, column: ir.OutputColumn, place: _Place, *, elements: bool = False) -> Step:
86
+ """A Cause for one unproved leaf of `column`'s evidence."""
87
+ name = quoted(column.name)
88
+ subjects = leaf.subjects
89
+ join = next((subject for subject in subjects if isinstance(subject, ir.Join)), None)
90
+ table = next((subject for subject in subjects if isinstance(subject, ir.NamedRelation)), None)
91
+ read = _Place(brief(alias.origin.detail), alias.origin) if alias is not None else place
92
+ if join is not None and "padded" in leaf.reason:
93
+ return Step(f"{brief(join.origin.detail)} pads {name}", False, join.origin, "sql", "padded",
94
+ ("on rows it does not match; an INNER JOIN, or a WHERE that rejects NULL there, removes the padding",))
95
+ if table is not None and (source := next((subject for subject in subjects if isinstance(subject, ir.OutputColumn)), None)) is not None:
96
+ if (reader := reading_alias(column, source)) is not None:
97
+ read = _Place(brief(reader.origin.detail), reader.origin)
98
+ if table is not None and table.role is ir.RelationRole.TABLE and not table.is_schema_complete:
99
+ return Step(f"{read.subject}: no CREATE TABLE declares it, so whether {name} may be NULL is unknown", False, read.origin,
100
+ "declare", "undeclared-table", ("declare it with CREATE TABLE, or analyze with a database connection",))
101
+ if table is not None and "is nullable in" in leaf.reason:
102
+ source = next((subject for subject in subjects if isinstance(subject, ir.OutputColumn)), column)
103
+ return Step(f"{read.subject}: {quoted(source.name)} is nullable", False, read.origin, "declare", "nullable-column",
104
+ (f"declare it NOT NULL in {table.name} if it holds",))
105
+ if elements and "DECLARE NOT NULL ELEMENTS" in leaf.reason:
106
+ return Step(f"{read.subject}: {name} may hold a NULL element", False, read.origin, "declare", "nullable-elements",
107
+ (f"DECLARE NOT NULL ELEMENTS({column.name}) states it does not",))
108
+ expression = next((subject for subject in subjects if isinstance(subject, ir.ScalarExpr)), None)
109
+ written = f" ({brief(expression.origin.detail)})" if expression is not None else ""
110
+ if leaf.reason.startswith("With no ELSE"):
111
+ return Step(f"{name}: a CASE with no ELSE is NULL where no WHEN matches{written}", False, place.origin, "sql", "case-without-else",
112
+ ("an ELSE, or a WHEN for every value of the operand's domain, removes it",))
113
+ if leaf.reason == "A NULL literal is null":
114
+ return Step(f"{name} is NULL where it takes a NULL literal", False, place.origin, "sql", "null-literal")
115
+ if "grouped by nothing" in leaf.reason:
116
+ return Step(f"{name}: {leaf.reason}{written}", False, place.origin, "sql", "empty-aggregate")
117
+ return Step(f"{name}: {leaf.reason}{written}", False, place.origin, "sqlassert", "not-modelled")
118
+
119
+
120
+ def reading_alias(column: ir.OutputColumn, source: ir.OutputColumn) -> ir.Alias | None:
121
+ """The Alias through which `column`'s value reads the table column
122
+ `source`: following the columns it is computed from, and a set
123
+ operation's inputs, down to the first Alias column that reads `source`."""
124
+ program = current_arena().program
125
+ pending, seen = [column], set()
126
+ while pending:
127
+ current = pending.pop()
128
+ if current in seen:
129
+ continue
130
+ seen.add(current)
131
+ owner = program.column_to_parent_relation_index.get(current)
132
+ if isinstance(owner, ir.Alias) and isinstance(current.scalar_expr, ir.ColumnRef) and current.scalar_expr.column is source:
133
+ return owner
134
+ if isinstance(owner, ir.SetOperation) and (arms := owner.arms(current)) is not None:
135
+ pending.extend(arms)
136
+ pending.extend(_references(current.scalar_expr))
137
+ return None
138
+
139
+
140
+ def _references(expression: ir.ScalarExpr) -> Iterator[ir.OutputColumn]:
141
+ """Every column `expression` reads."""
142
+ pending: list[ir.Node] = [expression]
143
+ while pending:
144
+ node = pending.pop()
145
+ if isinstance(node, ir.ColumnRef):
146
+ yield node.column
147
+ pending.extend(child for child in ir.children(node) if isinstance(child, ir.ScalarExpr))
148
+
149
+
150
+ def _dedupe(steps: Iterator[Step]) -> list[Step]:
151
+ shown: dict[tuple[str, str | None], Step] = {}
152
+ for step in steps:
153
+ shown.setdefault((step.text, step.code), step)
154
+ return list(shown.values())