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.
Files changed (65) hide show
  1. sqlassert/__init__.py +1 -2
  2. sqlassert/check.py +88 -13
  3. sqlassert/diagnostics.py +17 -6
  4. sqlassert/dialects.py +437 -7
  5. sqlassert/discovery/bigquery.py +3 -1
  6. sqlassert/discovery/databricks.py +25 -2
  7. sqlassert/discovery/duckdb.py +49 -7
  8. sqlassert/discovery/fetcher.py +130 -21
  9. sqlassert/discovery/information_schema.py +30 -2
  10. sqlassert/discovery/mysql.py +22 -1
  11. sqlassert/discovery/postgres.py +22 -5
  12. sqlassert/discovery/redshift.py +3 -2
  13. sqlassert/discovery/snowflake.py +3 -0
  14. sqlassert/discovery/trino.py +2 -2
  15. sqlassert/hazards.py +248 -87
  16. sqlassert/ir/__init__.py +4 -1
  17. sqlassert/ir/convert/__init__.py +13 -0
  18. sqlassert/ir/convert/aggregation.py +439 -0
  19. sqlassert/ir/convert/builtins.py +140 -0
  20. sqlassert/ir/convert/expressions.py +572 -0
  21. sqlassert/ir/convert/joins.py +264 -0
  22. sqlassert/ir/convert/markers.py +249 -0
  23. sqlassert/ir/convert/parser.py +253 -0
  24. sqlassert/ir/convert/queries.py +259 -0
  25. sqlassert/ir/convert/schema.py +606 -0
  26. sqlassert/ir/convert/scopes.py +205 -0
  27. sqlassert/ir/convert/selects.py +337 -0
  28. sqlassert/ir/convert/shared.py +429 -0
  29. sqlassert/ir/convert/sources.py +432 -0
  30. sqlassert/ir/convert/subqueries.py +364 -0
  31. sqlassert/ir/convert/value_types.py +223 -0
  32. sqlassert/ir/convert/windows.py +275 -0
  33. sqlassert/ir/model.py +125 -47
  34. sqlassert/ir/names.py +63 -0
  35. sqlassert/properties.py +12 -1
  36. sqlassert/provenance.py +5 -1
  37. sqlassert/python_engine.py +104 -44
  38. sqlassert/reporting.py +33 -32
  39. sqlassert/rewrites.py +111 -61
  40. sqlassert/rules/STYLEGUIDE.md +3 -2
  41. sqlassert/rules/causes/__init__.py +41 -0
  42. sqlassert/rules/causes/coverage.py +113 -0
  43. sqlassert/rules/causes/domain.py +123 -0
  44. sqlassert/rules/causes/joins.py +73 -0
  45. sqlassert/rules/causes/nulls.py +154 -0
  46. sqlassert/rules/causes/unique.py +523 -0
  47. sqlassert/rules/domain.py +8 -7
  48. sqlassert/rules/equality.py +6 -147
  49. sqlassert/rules/exactly_one.py +2 -1
  50. sqlassert/rules/foreign_key.py +8 -9
  51. sqlassert/rules/join_cardinality.py +282 -41
  52. sqlassert/rules/nullability.py +5 -5
  53. sqlassert/rules/uniqueness.py +171 -47
  54. sqlassert/rules/value_typing.py +337 -0
  55. sqlassert/sql_parse.py +28 -1
  56. sqlassert/suggest.py +11 -15
  57. sqlassert-0.4.1.dist-info/METADATA +235 -0
  58. sqlassert-0.4.1.dist-info/RECORD +69 -0
  59. sqlassert/ir/convert.py +0 -3509
  60. sqlassert-0.3.3.dist-info/METADATA +0 -807
  61. sqlassert-0.3.3.dist-info/RECORD +0 -46
  62. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/WHEEL +0 -0
  63. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/entry_points.txt +0 -0
  64. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/licenses/LICENSE +0 -0
  65. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/top_level.txt +0 -0
sqlassert/rewrites.py CHANGED
@@ -50,9 +50,11 @@ from sqlassert.diagnostics import quoted, quoted_all
50
50
  from sqlassert.edits import Edit, Source, apply_edits, unified_diff
51
51
  from sqlassert import ir
52
52
  from sqlassert.dialects import semantics
53
+ from sqlassert.ir.convert import IrConversionResult
53
54
  from sqlassert.properties import ExactlyOneJoin, ManyToOneJoin, NonNullColumn, NonNullColumns, NonNullUniqueSet
54
55
  from sqlassert.rules.domain import _domain
55
- from sqlassert.rules.equality import _comparison_type, _identity_comparison, _pins, _same_set_types, _same_type
56
+ from sqlassert.rules.equality import _same_set_types
57
+ from sqlassert.rules.value_typing import _comparison_type, column_ref, exact_comparison
56
58
  from sqlassert.rules.exactly_one import _cross_equalities
57
59
  from sqlassert.provenance import AttachmentSite
58
60
  from sqlassert.python_engine import Arena, Result
@@ -93,27 +95,61 @@ class RewriteKind(Enum):
93
95
  UNUSED_CTE = "Unused CTE"
94
96
 
95
97
 
98
+ class CaveatKind(Enum):
99
+ """What a Caveat says may change in its column: its output `NAME`; its
100
+ `TYPE`; its arithmetic, run in a narrower type that may overflow or, for
101
+ a float, round (`OVERFLOW`); or its precision, the exact value where
102
+ avg's DOUBLE may round (`PRECISION`). All but `NAME` come with a change
103
+ of the column's type."""
104
+
105
+ NAME = "name"
106
+ TYPE = "type"
107
+ OVERFLOW = "overflow"
108
+ PRECISION = "precision"
109
+
110
+
111
+ @dataclass(frozen=True)
112
+ class Caveat:
113
+ """What a Rewrite may change in one place: `column`, a quoted output
114
+ name (or `HAVING`, a condition), at `position` among its Select
115
+ Expression's items (None for HAVING); `text` names it for the message."""
116
+
117
+ column: str
118
+ position: int | None
119
+ kind: CaveatKind
120
+ text: str
121
+
122
+ @property
123
+ def castable(self) -> bool:
124
+ """A cast of the column to the aggregate's wider type restores it."""
125
+ return self.position is not None and self.kind in {CaveatKind.TYPE, CaveatKind.OVERFLOW}
126
+
127
+
96
128
  @dataclass(frozen=True)
97
129
  class Rewrite:
98
130
  """A result-preserving rewrite of the SQL at one site, with its proof.
99
131
  `edits` make it, on the SQL it was found in (one is offered only with
100
132
  them: where its syntax cannot be placed from the tokens, there is none);
101
- `message` says why, and what to do in a word. Its `suggest_type` is REWRITE_WITH_CAVEAT when a
102
- column's type or precision may change, which the message names;
103
- sqlassert has no result-type model per dialect, so such a change is
104
- caveated."""
133
+ `message` says why, and what to do in a word. `caveats` name what it may
134
+ change in a column (its name, type or precision), which the message
135
+ says too; sqlassert has no result-type model per dialect, so such a
136
+ change is caveated, and makes it a Rewrite with Caveat."""
105
137
 
106
138
  site: AttachmentSite
107
139
  kind: RewriteKind
108
140
  message: str
109
141
  edits: tuple[Edit, ...]
110
142
  evidence: Result[bool]
111
- suggest_type: SuggestType = SuggestType.REWRITE
143
+ caveats: tuple[Caveat, ...] = ()
112
144
 
113
145
  def __post_init__(self) -> None:
114
146
  if not self.edits:
115
147
  raise ValueError(f"a {self.kind.value} Rewrite without edits")
116
148
 
149
+ @property
150
+ def suggest_type(self) -> SuggestType:
151
+ return SuggestType.REWRITE_WITH_CAVEAT if self.caveats else SuggestType.REWRITE
152
+
117
153
  def rewritten(self, sql: str) -> str:
118
154
  """`sql`, the SQL this Rewrite was found in, rewritten."""
119
155
  return apply_edits(sql, self.edits)
@@ -125,12 +161,12 @@ class Rewrite:
125
161
 
126
162
 
127
163
  def rewrites(
128
- ast: ParsedProgram, program: ir.Program, arena: Arena, dialect: str,
164
+ ast: ParsedProgram, conversion: IrConversionResult, arena: Arena, dialect: str,
129
165
  wanted: Callable[[AttachmentSite], bool] = lambda site: True,
130
166
  ) -> list[Rewrite]:
131
- """Every Rewrite for `program` at a site `wanted` accepts, in source
132
- order. `arena` must be active."""
133
- syntax = _syntax_at_sites(ast)
167
+ """Every Rewrite for `conversion`'s Program, lowered from `ast`, at a
168
+ site `wanted` accepts, in source order. `arena` must be active."""
169
+ program = conversion.program
134
170
  source = Source(ast.sql, ast.tokens)
135
171
  parents: dict[ir.RelationExpr, list[ir.RelationExpr]] = {}
136
172
  for relation in program.relations():
@@ -138,7 +174,6 @@ def rewrites(
138
174
  if isinstance(child, ir.RelationExpr):
139
175
  parents.setdefault(child, []).append(relation)
140
176
  found: list[Rewrite] = []
141
- sort_keys = dict(program.sort_keys)
142
177
  for site, relation in program.attachment_sites:
143
178
  if isinstance(relation, ir.SimpleCase) or not wanted(site):
144
179
  continue # A CASE has nothing to rewrite yet.
@@ -146,7 +181,7 @@ def rewrites(
146
181
  # Unreachable: lowered inside a Select that is opaque as a whole.
147
182
  # (Every reachable relation but the root is some relation's input.)
148
183
  continue
149
- node = syntax.get((site.offset, site.trailing))
184
+ node = conversion.syntax.get(site)
150
185
  limit = relation if isinstance(relation, ir.Limit) else None
151
186
  if isinstance(relation, ir.Limit):
152
187
  relation = relation.input
@@ -155,7 +190,7 @@ def rewrites(
155
190
  found.extend(_implied_where(arena, site, relation, program, node, source, dialect))
156
191
  if site.trailing and isinstance(node, exp.Select):
157
192
  one_row = _one_row_tail(site, relation, limit, node, source)
158
- found.extend(one_row or _redundant_sort_keys(site, relation, node, sort_keys.get(site), dialect, source))
193
+ found.extend(one_row or _redundant_sort_keys(site, relation, node, conversion.sort_keys.get(site), dialect, source))
159
194
  match relation:
160
195
  case ir.Join() if isinstance(node, exp.Join):
161
196
  same = _self_join(arena, site, relation, node, program, dialect, source)
@@ -174,7 +209,7 @@ def rewrites(
174
209
  found.extend(item for item in _unused_ctes(ast, source) if wanted(item.site))
175
210
  if semantics(dialect).set_operations_all:
176
211
  found.extend(
177
- item for site, operation in program.set_operations
212
+ item for site, operation in conversion.set_operations
178
213
  if wanted(site) and (item := _set_operation_all(site, operation, source)) is not None
179
214
  )
180
215
  return sorted(found, key=lambda item: item.site.offset)
@@ -186,6 +221,9 @@ def _grouped(relation: ir.RelationExpr, node: exp.Select) -> ir.Aggregate | None
186
221
  (`_lower_aggregate`), and the Filter that is its HAVING, all under the
187
222
  Filter of a DISTINCT ON, which keeps one group per key."""
188
223
  distinct = node.args.get("distinct")
224
+ group = node.args.get("group")
225
+ if isinstance(group, exp.Group) and group.args.get("all"):
226
+ return None # Its keys are written nowhere: no edit can place a rewrite.
189
227
  if isinstance(relation, ir.Filter) and distinct is not None and distinct.args.get("on") is not None:
190
228
  relation = relation.input
191
229
  if isinstance(relation, ir.Project):
@@ -252,7 +290,7 @@ def _on_conjuncts(node: exp.Join, source: Source) -> tuple[list[tuple[Expr, int,
252
290
 
253
291
  def _conjunct_tokens(condition: Expr, first: int, last: int, source: Source) -> list[tuple[Expr, int, int]] | None:
254
292
  """Each conjunct of `condition`, written from token `first` to `last`,
255
- as the IR reads them (`ir.convert._conjuncts`: top-level ANDs, parentheses
293
+ as the IR reads them (`ir.convert.shared._conjuncts`: top-level ANDs, parentheses
256
294
  removed), with its first and last token, parentheses around it included.
257
295
  None when the tokens do not line up with the AST."""
258
296
  found: list[tuple[Expr, int, int]] = []
@@ -289,16 +327,6 @@ def _deleted_conjunct(
289
327
  return source.deletions([(preceding, last)])
290
328
 
291
329
 
292
- def _syntax_at_sites(ast: ParsedProgram) -> dict[tuple[int, bool], exp.Join | exp.Select]:
293
- """Each Join and Select by its Attachment Site's (offset, trailing)."""
294
- index: dict[tuple[int, bool], exp.Join | exp.Select] = {}
295
- for node in _nodes(ast, exp.Join, exp.Select):
296
- position = marker_position(node)
297
- if position is not None:
298
- index[(position[0], isinstance(node, exp.Select))] = node
299
- return index
300
-
301
-
302
330
  def _join_start(node: exp.Join, source: Source) -> int | None:
303
331
  """The join's first token."""
304
332
  position = marker_position(node)
@@ -419,8 +447,8 @@ def _redundant_sort_keys(
419
447
  edit deletes the key and the comma before it."""
420
448
  from sqlassert.hazards import _ties_identical
421
449
 
422
- if not keys:
423
- return []
450
+ if not keys or select.args.get("order") is None:
451
+ return [] # A set operation's site maps to its last operand, whose ORDER BY is the whole's.
424
452
  items = select.args["order"].expressions
425
453
  clause = source.tokens_of(span(select.args["order"]))
426
454
  parts = source.split(clause[0] + 1, clause[1], TokenType.COMMA) if clause is not None else []
@@ -673,7 +701,7 @@ def _grouping_is_projection(
673
701
  clause = source.tokens_of(span(node.args["group"])) if node.args.get("group") is not None else None
674
702
  if clause is None:
675
703
  return None
676
- caveats: list[_Caveat] = []
704
+ caveats: list[Caveat] = []
677
705
  if having is None:
678
706
  edits = list(source.deletions([clause]))
679
707
  else:
@@ -683,9 +711,9 @@ def _grouping_is_projection(
683
711
  having_edits, having_caveats = moved
684
712
  edits = list(having_edits)
685
713
  caveats.extend(having_caveats)
686
- for item in node.expressions:
687
- name = quoted(item.alias if isinstance(item, exp.Alias) else written_sql(item, dialect))
688
- rewritten = _one_row(item, name, dialect, types)
714
+ for position, item in enumerate(node.expressions):
715
+ name = quoted(item.alias if isinstance(item, exp.Alias) else _written(item, source, dialect))
716
+ rewritten = _one_row(item, name, position, dialect, types)
689
717
  if rewritten is None:
690
718
  return None
691
719
  replacements, item_caveats = rewritten
@@ -695,29 +723,51 @@ def _grouping_is_projection(
695
723
  return None
696
724
  edits.append(edit)
697
725
  caveats.extend(item_caveats)
726
+ if replacements and not isinstance(item, exp.Alias):
727
+ caveats.append(_renamed(name, position))
698
728
  names = quoted_all(written_sql(expression, dialect) for expression in expressions)
699
729
  message = (
700
730
  f"no two rows agree on ({names}), NULL equal to NULL, so every group is one row: "
701
731
  "drop GROUP BY and write each aggregate as its value over that row"
702
732
  ) + (", and move HAVING into WHERE" if having is not None else "")
733
+ return Rewrite(site, RewriteKind.GROUPING_PROJECTION, _caveated(message, caveats), tuple(edits), evidence, tuple(caveats))
734
+
735
+
736
+ def _written(item: Expr, source: Source, dialect: str) -> str:
737
+ """`item` as written in the SQL, or else as SQLGlot writes it."""
738
+ tokens = source.tokens_of(span(item))
739
+ return source.text(*tokens) if tokens else written_sql(item, dialect)
740
+
741
+
742
+ def _renamed(name: str, position: int) -> Caveat:
743
+ """The caveat of an unaliased item `name`, at `position`, whose text
744
+ changes: the engine names it after its text, and sqlassert does not
745
+ model those names (ADR 0010), so it cannot alias it to keep its name."""
746
+ return Caveat(name, position, CaveatKind.NAME, (
747
+ f"{name} has no alias, so its output name changes: rename by hand whatever reads it by that name"
748
+ ))
749
+
750
+
751
+ def _caveated(message: str, caveats: list[Caveat]) -> str:
752
+ """`message`, followed by what `caveats` say may change, if any."""
703
753
  if not caveats:
704
- return Rewrite(site, RewriteKind.GROUPING_PROJECTION, message, tuple(edits), evidence)
754
+ return message
705
755
  message += f". Caveat: {'; '.join(caveat.text for caveat in caveats)}"
706
756
  castable = len({caveat.column for caveat in caveats if caveat.castable})
707
757
  if castable:
708
758
  message += "; cast it if later arithmetic needs the wider type" if castable == 1 else "; cast them if later arithmetic needs the wider types"
709
- return Rewrite(site, RewriteKind.GROUPING_PROJECTION, message, tuple(edits), evidence, SuggestType.REWRITE_WITH_CAVEAT)
759
+ return message
710
760
 
711
761
 
712
762
  def _having_into_where(
713
763
  node: exp.Select, having: exp.Having, group: tuple[int, int], source: Source, dialect: str, types: dict[str, str | None],
714
- ) -> tuple[tuple[Edit, ...], list[_Caveat]] | None:
764
+ ) -> tuple[tuple[Edit, ...], list[Caveat]] | None:
715
765
  """GROUP BY (tokens `group`) and HAVING deleted, HAVING's condition, each
716
766
  aggregate call in it written as its one-row value as an item's is,
717
767
  ANDed into WHERE or written as a WHERE in GROUP BY's place; and what the
718
768
  replacements may change, as for an item (no column to cast)."""
719
769
  clause = source.tokens_of(span(having))
720
- rewritten = _one_row(having.this, "HAVING", dialect, types)
770
+ rewritten = _one_row(having.this, "HAVING", None, dialect, types)
721
771
  if clause is None or rewritten is None or clause[0] + 1 > clause[1]:
722
772
  return None
723
773
  replacements, caveats = rewritten
@@ -730,7 +780,8 @@ def _having_into_where(
730
780
  return None
731
781
  inner.append(Edit(edit.start - start, edit.end - start, edit.replacement))
732
782
  condition = apply_edits(source.sql[start:source.end(last)], inner)
733
- caveats = [replace(caveat, castable=False) for caveat in caveats]
783
+ # In WHERE, a changed value decides which rows pass: rare, and caveated.
784
+ caveats = [replace(caveat, text=f"{caveat.text}, so WHERE may keep other rows or fail") for caveat in caveats]
734
785
  moved = [(first, last)]
735
786
  where = node.args.get("where")
736
787
  adjacent = clause[0] == group[1] + 1
@@ -808,17 +859,6 @@ def _one_row_edit(value: _OneRowValue, source: Source, dialect: str) -> Edit | N
808
859
  return source.replace(first, last, argument if value.whole or atomic else f"({argument})", moved)
809
860
 
810
861
 
811
- @dataclass(frozen=True)
812
- class _Caveat:
813
- """What a one-row replacement may change in `column`, a quoted output
814
- name: its type or overflow (`castable`: a cast to the aggregate's wider
815
- type restores it), or avg's precision."""
816
-
817
- column: str
818
- text: str
819
- castable: bool
820
-
821
-
822
862
  # Argument types whose sum and average over one row are the argument's value,
823
863
  # and whose average, a DOUBLE in some dialects, holds it exactly (at most
824
864
  # 32-bit integers and floats): a BIGINT, HUGEINT, UBIGINT or DECIMAL average
@@ -834,8 +874,10 @@ _AVERAGED_EXACTLY = {
834
874
  }
835
875
 
836
876
 
837
- def _one_row(item: Expr, name: str, dialect: str, types: dict[str, str | None]) -> tuple[list[_OneRowValue], list[_Caveat]] | None:
838
- """Each aggregate call in `item`, output as `name`, and its value over
877
+ def _one_row(
878
+ item: Expr, name: str, position: int | None, dialect: str, types: dict[str, str | None],
879
+ ) -> tuple[list[_OneRowValue], list[Caveat]] | None:
880
+ """Each aggregate call in `item`, output as `name` at `position`, and its value over
839
881
  one row, and what each replacement may change in its type, overflow or
840
882
  precision; None when an aggregate has no such form here.
841
883
 
@@ -859,7 +901,7 @@ def _one_row(item: Expr, name: str, dialect: str, types: dict[str, str | None])
859
901
  columns, the outer query's."""
860
902
  if any(_within(call.find_ancestor(exp.Select), item) for call in item.find_all(exp.AggFunc)):
861
903
  return None
862
- caveats: list[_Caveat] = []
904
+ caveats: list[Caveat] = []
863
905
  values: list[_OneRowValue] = []
864
906
  for call in list(item.find_all(exp.AggFunc)):
865
907
  target: Expr = call
@@ -895,10 +937,10 @@ def _one_row(item: Expr, name: str, dialect: str, types: dict[str, str | None])
895
937
  return None
896
938
  written = written_sql(argument, dialect)
897
939
  if isinstance(call, exp.Avg) and kind not in _AVERAGED_EXACTLY:
898
- caveats.append(_Caveat(name, (
940
+ caveats.append(Caveat(name, position, CaveatKind.PRECISION, (
899
941
  f"{name} takes {written}'s exact value and type, where avg converts to DOUBLE in some dialects "
900
942
  "and may lose precision (avg(9007199254740993) is 9007199254740992.0)"
901
- ), castable=False))
943
+ )))
902
944
  if whole:
903
945
  narrowed_to = ""
904
946
  if kind is not exp.DataType.Type.DOUBLE and narrowed_to is None:
@@ -911,13 +953,13 @@ def _one_row(item: Expr, name: str, dialect: str, types: dict[str, str | None])
911
953
  return None
912
954
  aggregate = "count" if isinstance(call, exp.Count) else "sum" if isinstance(call, exp.Sum) else "avg"
913
955
  if narrowed_to and whole:
914
- caveats.append(_Caveat(name, f"{name} changes from {aggregate}'s result type to {narrowed_to}", castable=True))
956
+ caveats.append(Caveat(name, position, CaveatKind.TYPE, f"{name} changes from {aggregate}'s result type to {narrowed_to}"))
915
957
  elif narrowed_to:
916
958
  risk = "lose precision" if kind in _FLOATS else "overflow"
917
- caveats.append(_Caveat(name, (
959
+ caveats.append(Caveat(name, position, CaveatKind.OVERFLOW, (
918
960
  f"{name} runs its arithmetic in {narrowed_to}, not {aggregate}'s result type, "
919
961
  f"and may {risk} where the aggregate's did not"
920
- ), castable=True))
962
+ )))
921
963
  values.append(_OneRowValue(target, call, form, whole, argument if form != "one" else None))
922
964
  return values, caveats
923
965
 
@@ -1148,7 +1190,7 @@ def _self_join(
1148
1190
  tokens = source.tokens_of(span(node))
1149
1191
  if written is None or tokens is None:
1150
1192
  return None
1151
- columns = {column.name.lower(): column for column in relation.output_columns}
1193
+ columns = {column.name.lower(): column for column in reversed(relation.output_columns)} # A repeated name reads its first.
1152
1194
  extra = [(conjunct, first, last) for conjunct, first, last in written if not _key_equality(conjunct, mine, theirs, names)]
1153
1195
  if extra and join.kind == "inner" and _right_or_full_join_follows(node):
1154
1196
  return None
@@ -1160,6 +1202,7 @@ def _self_join(
1160
1202
  return None
1161
1203
  guard = " AND ".join(part for part in parts if part is not None) or None
1162
1204
  edits: list[Edit] = []
1205
+ read_through: list[exp.Column] = []
1163
1206
  for column in select.find_all(exp.Column):
1164
1207
  if _within(column, node):
1165
1208
  continue
@@ -1177,6 +1220,7 @@ def _self_join(
1177
1220
  qualifier, name = _identifier_token(column.args.get("table"), source), _identifier_token(column.this, source)
1178
1221
  if read is None or not _pure(read, program) or qualifier is None or name is None:
1179
1222
  return None
1223
+ read_through.append(column)
1180
1224
  if guard is not None and join.kind == "left":
1181
1225
  written_name = source.text(name, name)
1182
1226
  value = f"CASE WHEN {guard} THEN {reader}.{written_name} END"
@@ -1196,7 +1240,13 @@ def _self_join(
1196
1240
  f"each {mine} row matches itself on the key ({quoted_all(sorted(column.name for column in keys.values()))}), "
1197
1241
  f"so {theirs} is {mine}: delete the join and read {mine}'s columns"
1198
1242
  )
1199
- return Rewrite(site, RewriteKind.SELF_JOIN, message, tuple(edits), key)
1243
+ # An unaliased item other than a column is named after its text, which changes.
1244
+ caveats = [
1245
+ _renamed(quoted(_written(item, source, dialect)), position)
1246
+ for position, item in enumerate(select.expressions)
1247
+ if not isinstance(item, exp.Alias | exp.Column) and any(_within(column, item) for column in read_through)
1248
+ ]
1249
+ return Rewrite(site, RewriteKind.SELF_JOIN, _caveated(message, caveats), tuple(edits), key, tuple(caveats))
1200
1250
 
1201
1251
 
1202
1252
  def _identifier_token(identifier: Expr | None, source: Source) -> int | None:
@@ -1369,7 +1419,7 @@ def _implication(
1369
1419
  if _chained(first, second, others):
1370
1420
  return "the other equalities chain its sides", False
1371
1421
  pinned = _pinned(first, others), _pinned(second, others)
1372
- comparable = _same_type(first, second) and _identity_comparison(first).value and _identity_comparison(second).value
1422
+ comparable = exact_comparison(column_ref(first), column_ref(second)).value
1373
1423
  if comparable and pinned[0] is not None and pinned[0] == pinned[1]:
1374
1424
  return f"both sides are {pinned[0].text}", False
1375
1425
  if isinstance(relation, ir.Join) and _same_row_column(first, second, others, relation, program, arena):
@@ -1393,8 +1443,8 @@ def _chained(first: ir.OutputColumn, second: ir.OutputColumn, others: list[ir.Sc
1393
1443
  edges = []
1394
1444
  for other in others:
1395
1445
  match other:
1396
- case ir.Equality(left=ir.ColumnRef(column=left), right=ir.ColumnRef(column=right)) if (
1397
- _same_type(left, right) and _identity_comparison(left).value and _identity_comparison(right).value
1446
+ case ir.Equality(left=ir.ColumnRef(column=left) as left_ref, right=ir.ColumnRef(column=right) as right_ref) if (
1447
+ exact_comparison(left_ref, right_ref).value
1398
1448
  ):
1399
1449
  edges.append((left, right))
1400
1450
  case _:
@@ -1414,7 +1464,7 @@ def _pinned(column: ir.OutputColumn, others: list[ir.ScalarExpr]) -> ir.LiteralV
1414
1464
  """The one value another conjunct, or the column's domain, holds it to."""
1415
1465
  for other in others:
1416
1466
  match other:
1417
- case ir.Equality(left=ir.ColumnRef(column=pinned), right=ir.Constant(value=value) as literal) | ir.Equality(left=ir.Constant(value=value) as literal, right=ir.ColumnRef(column=pinned)) if pinned is column and value is not None and _pins(column, literal):
1467
+ case ir.Equality(left=ir.ColumnRef(column=pinned) as operand, right=ir.Constant(value=value) as literal) | ir.Equality(left=ir.Constant(value=value) as literal, right=ir.ColumnRef(column=pinned) as operand) if pinned is column and value is not None and exact_comparison(operand, literal).value:
1418
1468
  return value
1419
1469
  case _:
1420
1470
  pass
@@ -5,8 +5,9 @@ is the computed Value and the remaining fields directly represent its evidence.
5
5
  `@analysis(stratum)` provides declaration lookup and analysis-scoped caching for public and
6
6
  internal analysis functions. Its `Stratum` orders facts about one relation: an analysis may
7
7
  use facts about the same relation only at its own or a lower stratum, which keeps the
8
- call graph acyclic; the decorator asserts this on every call. Every concrete public `Property` class has one
9
- snake-case public analysis function whose parameters match its fields. Internal
8
+ call graph acyclic; the decorator asserts this on every call. Every concrete `Property` class has one
9
+ snake-case public analysis function, decorated `@analysis(stratum, evaluates=TheProperty)`,
10
+ whose parameters match its fields. Internal
10
11
  analysis functions start with `_`. `ColumnSet`, `Closure`, and `RowIdentity` are
11
12
  ordinary derived values defined in these rules. Uniqueness is a closure question:
12
13
  derive dependencies a relation introduces in `_functional_dependencies`, and let
@@ -0,0 +1,41 @@
1
+ """Why an assertion is UNKNOWN: the relations its Property passes through,
2
+ down to the Causes that lose it (CONTEXT.md, Cause).
3
+
4
+ One walk per question an assertion asks, each reading the analyses its proof
5
+ ran, so none changes an outcome: `unique` (a Unique Set, and what joins and
6
+ DETERMINES ask of one), `joins` (Join Cardinality and Exactly One Joins),
7
+ `nulls` (non-null columns and elements), `coverage` (Referential Coverage,
8
+ Foreign Keys), `domain` (Enumerated Domains, exhaustive CASEs).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from sqlassert import properties as props
14
+ from sqlassert.reporting import Step
15
+
16
+
17
+ def explain(property: props.Property) -> Step | None:
18
+ """Why `property` is not proved, down to its Causes; None when no walk
19
+ finds one, so the caller falls back to the proof. Runs inside an analysis
20
+ session."""
21
+ from sqlassert.rules.causes import coverage, domain, joins, nulls, unique
22
+
23
+ match property:
24
+ case props.NonNullUniqueSet(columns=columns):
25
+ return unique.explain_unique_set(columns, non_null=True)
26
+ case props.UniqueSet(columns=columns):
27
+ return unique.explain_unique_set(columns, non_null=False)
28
+ case props.FunctionalDependency(determinant=determinant, dependent=dependent):
29
+ return unique.explain_dependency(determinant, dependent)
30
+ case props.ManyToOneJoin() | props.OneToManyJoin() | props.OneToOneJoin() | props.UniqueJoin() | props.ExactlyOneJoin():
31
+ return joins.explain_join(property)
32
+ case props.NonNullColumns(columns=columns):
33
+ return nulls.explain_non_null(columns)
34
+ case props.NonNullElements(columns=columns):
35
+ return nulls.explain_elements(columns)
36
+ case props.ForeignKey() | props.ReferentialCoverage():
37
+ return coverage.explain_coverage(property)
38
+ case props.EnumeratedDomain() | props.ExhaustiveCase():
39
+ return domain.explain_domain(property)
40
+ case _:
41
+ return None
@@ -0,0 +1,113 @@
1
+ """Why Referential Coverage (and so a Foreign Key) is not proved: where the
2
+ referencing columns lose it on the way down to a table.
3
+
4
+ The walk reads the evidence `referential_coverage` left, down to the leaves
5
+ that are not proved: a table with no Foreign Key from those columns (named by
6
+ the FROM item that reads them), a relation that may drop the referenced rows,
7
+ a column that is not passed through from one input row, a relation sqlassert
8
+ does not model. The referenced side of a Foreign Key must be a Unique Set:
9
+ the Unique Set walk says why it is not.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Iterator
15
+
16
+ from sqlassert import ir
17
+ from sqlassert import properties as props
18
+ from sqlassert.diagnostics import quoted
19
+ from sqlassert.python_engine import Result, current_arena
20
+ from sqlassert.reporting import Step
21
+ from sqlassert.rules.causes.nulls import reading_alias
22
+ from sqlassert.rules.causes.unique import _Place, asserted_place, brief, explain_unique_set, names
23
+ from sqlassert.rules.foreign_key import _describe, referential_coverage
24
+ from sqlassert.rules.uniqueness import unique_set
25
+
26
+
27
+ def explain_coverage(property: props.ReferentialCoverage) -> Step | None:
28
+ program = current_arena().program
29
+ relation = program.relation_of(frozenset(property.columns))
30
+ if relation is None:
31
+ return None
32
+ place = asserted_place(relation)
33
+ steps = list(coverage_causes(referential_coverage(property.columns, property.referenced_columns), property.columns, place))
34
+ if isinstance(property, props.ForeignKey) and not unique_set(frozenset(property.referenced_columns)).value:
35
+ referenced = explain_unique_set(frozenset(property.referenced_columns), non_null=False)
36
+ steps.append(Step(f"the referenced columns {_describe(property.referenced_columns)} are not a Unique Set", False, None,
37
+ steps=referenced.steps if referenced is not None else ()))
38
+ top = Step(f"{place.subject}: {names(property.columns)} is not proved to reference {_describe(property.referenced_columns)}", False, None, steps=tuple(steps))
39
+ return top if top.causes() else None
40
+
41
+
42
+ def at_least_one(join: ir.Join) -> tuple[Step, ...]:
43
+ """Why an Exactly One Join's left rows may match no right row."""
44
+ from sqlassert.rules.exactly_one import _cross_equalities, _has_a_row, _is_true
45
+
46
+ subject = brief(join.origin.detail)
47
+ if all(_is_true(conjunct) for conjunct in join.conjuncts):
48
+ if _has_a_row(join.right).value:
49
+ return ()
50
+ return (Step(f"{subject}: its right input may have no rows", False, join.origin, "sql", "empty-input"),)
51
+ pairs, others = _cross_equalities(join)
52
+ if not pairs:
53
+ return (Step(f"{subject}: at least one match needs an equality between a left and a right column", False, join.origin, "sql", "no-equality"),)
54
+ lefts = tuple(left for left, _ in pairs)
55
+ rights = tuple(right for _, right in pairs)
56
+ steps = list(coverage_causes(referential_coverage(lefts, rights), lefts, _Place(subject, join.origin)))
57
+ steps.extend(
58
+ Step(f"{brief(conjunct.origin.detail)}: only column-to-column equalities between the inputs are known to keep a covering row",
59
+ False, join.origin, "sqlassert", "other-conjunct")
60
+ for conjunct in others
61
+ )
62
+ if not steps:
63
+ return ()
64
+ return (Step(f"{subject}: a left row may match no right row", False, None, steps=tuple(steps)),)
65
+
66
+
67
+ def coverage_causes(evidence: Result[bool], columns: tuple[ir.OutputColumn, ...], place: _Place) -> tuple[Step, ...]:
68
+ """A Cause for each unproved leaf of coverage evidence for `columns`."""
69
+ if evidence.value:
70
+ return ()
71
+ shown: dict[tuple[str, str | None], Step] = {}
72
+ for leaf in _leaves(evidence):
73
+ step = _cause(leaf, columns, place)
74
+ shown.setdefault((step.text, step.code), step)
75
+ return tuple(shown.values())
76
+
77
+
78
+ def _leaves(result: Result, seen: set[int] | None = None) -> Iterator[Result]:
79
+ seen = set() if seen is None else seen
80
+ if id(result) in seen or result.value is not False:
81
+ return
82
+ seen.add(id(result))
83
+ if not result.premises:
84
+ yield result
85
+ return
86
+ for premise in result.premises:
87
+ yield from _leaves(premise, seen)
88
+
89
+
90
+ def _cause(leaf: Result, columns: tuple[ir.OutputColumn, ...], place: _Place) -> Step:
91
+ reason = leaf.reason
92
+ relation = next((subject for subject in leaf.subjects if isinstance(subject, ir.RelationExpr)), None)
93
+ at = relation.origin if relation is not None and relation.origin.span is not None else place.origin
94
+ if reason.startswith("No known Foreign Key"):
95
+ source = next((subject for subject in leaf.subjects if isinstance(subject, ir.OutputColumn)), None)
96
+ reader = reading_alias(columns[0], source) if source is not None else None
97
+ read = _Place(brief(reader.origin.detail), reader.origin) if reader is not None else place
98
+ return Step(f"{read.subject}: {reason[0].lower()}{reason[1:]}", False, read.origin, "declare", "no-foreign-key",
99
+ ("declare it with REFERENCES or DECLARE FOREIGN KEY if it holds",))
100
+ if "may drop rows of its input" in reason and relation is not None:
101
+ return Step(f"{brief(relation.origin.detail)} may drop referenced rows", False, at, "sql", "narrowed-reference",
102
+ ("coverage of its input does not carry over: a row it drops may be the one a referencing row needs",))
103
+ if "are not passed through" in reason:
104
+ computed = [subject for subject in leaf.subjects if isinstance(subject, ir.OutputColumn) and not isinstance(subject.scalar_expr, ir.ColumnRef)]
105
+ if computed:
106
+ written = ", ".join(f"{quoted(column.name)} = {brief(column.origin.detail.rsplit(' AS ', 1)[0])}" for column in computed)
107
+ return Step(f"{written} is computed, so no Foreign Key carries over to it", False, at, "sql", "not-passed-through")
108
+ return Step(reason, False, at, "sql", "not-passed-through")
109
+ if "unanalyzed relation" in reason or "not paired by position" in reason:
110
+ return Step(reason, False, at, "sqlassert", "not-modelled")
111
+ if "no complete declared schema" in reason:
112
+ return Step(reason, False, at, "declare", "undeclared-table")
113
+ return Step(reason, False, at, "sql", "coverage")