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
@@ -0,0 +1,523 @@
1
+ """Why a Unique Set assertion is UNKNOWN: the relations it passes through,
2
+ down to the Causes that lose it (CONTEXT.md, Cause).
3
+
4
+ The walk reads the closure `unique_set` took and the analyses that closure
5
+ ran; it proves nothing of its own, so it never changes an outcome. At each
6
+ relation it asks one question, whether the asserted columns reach its Row
7
+ Identity there, and follows the inputs that decide it:
8
+
9
+ - an Alias, projection, filter, LIMIT, semi or anti join passes the question
10
+ to its input; a CTE or view is a Step of its own, over its body; an
11
+ asserted column a projection computes without keeping its input's values
12
+ apart is a Cause there;
13
+ - a join must match each row of the input the columns fix at most once in
14
+ the other; a many-to-one join repeats no left row, so the walk follows its
15
+ left input (a one-to-many one, its right). A join that falls short is a
16
+ Cause, with its Unproved Join Reason for that direction and the key the
17
+ matched input misses;
18
+ - a UNION needs a column that separates its inputs and each input unique; an
19
+ EXCEPT ALL or INTERSECT ALL keeps its left input's rows;
20
+ - any other relation (a table, a GROUP BY, a DISTINCT) is a Cause when the
21
+ columns miss every key it has: its closest minimal keys, and what each lacks.
22
+
23
+ A relation where the question is answered PROVED is one line: its proof is
24
+ not repeated.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from collections.abc import Callable, Iterable
30
+ from dataclasses import dataclass
31
+
32
+ from sqlassert import ir
33
+ from sqlassert.diagnostics import quoted
34
+ from sqlassert.provenance import Origin
35
+ from sqlassert.python_engine import Result, current_arena
36
+ from sqlassert.reporting import CauseTag, Step
37
+ from sqlassert.rules.column_set import Attribute, Closure, RowIdentity
38
+ from sqlassert.rules.equality import _constant_value, _typed_arms
39
+ from sqlassert.rules.join_cardinality import Side, _unsupported_under, many_to_one_join, one_to_many_join, unproved_join
40
+ from sqlassert.rules.value_typing import untyped_source
41
+ from sqlassert.rules.uniqueness import _closure, _definite, _distinct_tags, _functional_dependencies, _one_to_one, _padded_with
42
+
43
+ # Who can act on each Unproved Join Reason. A cascade is no Cause of its own:
44
+ # the walk follows it to the join or relation below that is.
45
+ _JOIN_TAGS: dict[str, CauseTag] = {
46
+ "unsupported": "sqlassert", "unresolved-key": "sqlassert", "untyped-key": "sqlassert", "expression-key": "sqlassert",
47
+ "unconstrained": "sql", "partial-key": "sql", "undeclared-key": "declare",
48
+ # An untyped key from a table with no declared type: declaring the table fixes it.
49
+ "table": "declare",
50
+ }
51
+
52
+ # Codes of a relation's own key gap: folded into the join that matches it.
53
+ _KEY_GAPS = {"missing-key-columns", "no-unique-set", "nullable-key", "undeclared-table"}
54
+
55
+ # The longest relation text shown before it is shortened.
56
+ _WIDTH = 80
57
+
58
+ # Hidden outputs (a GROUP BY or PARTITION BY key not selected) are named so.
59
+ _HIDDEN = "\0"
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class _Place:
64
+ """How the relation being walked is named, and where it is written."""
65
+
66
+ subject: str
67
+ origin: Origin | None = None
68
+
69
+
70
+ def null_causes(columns: frozenset[ir.OutputColumn], place: _Place) -> tuple[Step, ...]:
71
+ from sqlassert.rules.causes.nulls import null_causes as causes # The null walk names places as this module does.
72
+
73
+ return causes(columns, place)
74
+
75
+
76
+ def explain_unique_set(columns: frozenset[ir.OutputColumn], non_null: bool) -> Step | None:
77
+ """Why `columns` is not proved a Unique Set (a Non-Null one when
78
+ `non_null`): a Step for the asserted relation over the relations the
79
+ explanation follows. None when no Cause is found, so the caller falls back
80
+ to the proof itself. Runs inside an analysis session."""
81
+ program = current_arena().program
82
+ relation = program.relation_of(columns)
83
+ if relation is None:
84
+ return None
85
+ place = asserted_place(relation)
86
+ closure = _closure(relation, frozenset(columns), frozenset(columns))
87
+ unique = RowIdentity(relation) in closure.value.columns
88
+ steps = () if unique else walk_unique(closure, place)
89
+ nullable = null_causes(columns, place) if non_null else ()
90
+ named = names(column for column in relation.output_columns if column in columns)
91
+ top = Step(f"{place.subject}: {'unique' if unique else 'not unique'} on {named}", unique, None, steps=(*steps, *nullable))
92
+ return top if top.causes() else None
93
+
94
+
95
+ def explain_dependency(determinant: frozenset[ir.OutputColumn], dependent: frozenset[ir.OutputColumn]) -> Step | None:
96
+ """Why `determinant` is not proved to determine `dependent`: for each
97
+ dependent column the closure misses, the walk down to where its value is
98
+ no longer fixed by the determinant's."""
99
+ program = current_arena().program
100
+ relation = program.relation_of(determinant | dependent)
101
+ if relation is None:
102
+ return None
103
+ place = asserted_place(relation)
104
+ closure = _closure(relation, frozenset(determinant), frozenset(determinant))
105
+ missed = [column for column in relation.output_columns if column in dependent and column not in closure.value.columns]
106
+ steps = tuple(step for column in missed for step in walk_dependent(closure, column, place))
107
+ top = Step(f"{place.subject}: {names(column for column in relation.output_columns if column in determinant)} does not determine "
108
+ f"{names(missed)}", False, None, steps=steps)
109
+ return top if top.causes() else None
110
+
111
+
112
+ def walk_dependent(closure: Result[Closure], target: ir.OutputColumn, place: _Place) -> tuple[Step, ...]:
113
+ """Why the closure does not reach `target`, a column of its relation: the
114
+ walk follows the input columns its value comes from, to the relation
115
+ whose rows the determinant does not fix (where the Unique Set walk takes
116
+ over) or the expression that loses it."""
117
+ relation = closure.value.relation.closed
118
+ place = own_place(relation, place)
119
+ if target in closure.value.columns:
120
+ return ()
121
+ match relation:
122
+ case ir.Alias(source=source) | ir.NamedRelation(body=ir.RelationExpr() as source) | ir.Filter(input=source) | ir.Limit(input=source) | ir.Join(kind="semi" | "anti", left=source):
123
+ return _follow_value(closure, target, source, place)
124
+ case ir.Project(input=source):
125
+ at = _Place(place.subject, _spanned(relation.origin, place))
126
+ if target not in _one_to_one(relation, source) and not isinstance(target.scalar_expr, ir.ColumnRef):
127
+ read = ir.determinants(target.scalar_expr)
128
+ if read is None:
129
+ return (computed_column(target, at),)
130
+ inner = _input(closure, source)
131
+ if inner is not None and all(column in inner.value.columns for column in read):
132
+ # Its inputs are fixed, yet two equal inputs may give it different values.
133
+ written = brief(target.origin.detail.rsplit(" AS ", 1)[0])
134
+ return (Step(f"{quoted(target.name)} = {written}: inputs that compare equal may give it different values", False, at.origin,
135
+ "sqlassert", "not-identity", ("only inputs compared by identity fix a computed value: -0.0 = 0.0 as a DOUBLE, but not as text",)),)
136
+ return _follow_value(closure, target, source, place)
137
+ case ir.Join():
138
+ side = join_side(relation, target)
139
+ if side is None:
140
+ return (_keys(closure, relation, place),)
141
+ matched, source = side
142
+ inner = _input(closure, source)
143
+ if inner is None or RowIdentity(source) in closure.value.columns:
144
+ return _follow_value(closure, target, source, place)
145
+ reads = _upstream(target, source)
146
+ below = tuple(step for column in reads for step in walk_dependent(inner, column, side_place(source, relation)))
147
+ if matched == "right" and not many_to_one_join(relation).value:
148
+ return (join_cause(relation, "right", below),)
149
+ return below
150
+ case _:
151
+ # A table, a GROUP BY, a DISTINCT, a set operation: the row decides the value.
152
+ return walk_unique(closure, place)
153
+
154
+
155
+ def join_side(join: ir.Join, column: ir.OutputColumn) -> tuple[Side, ir.RelationExpr] | None:
156
+ """The input a join's output column comes from."""
157
+ if not isinstance(column.scalar_expr, ir.ColumnRef):
158
+ return None
159
+ source = column.scalar_expr.column
160
+ if source in join.left.output_columns:
161
+ return "left", join.left
162
+ if source in join.right.output_columns:
163
+ return "right", join.right
164
+ return None
165
+
166
+
167
+ def _follow_value(closure: Result[Closure], target: ir.OutputColumn, source: ir.RelationExpr, place: _Place) -> tuple[Step, ...]:
168
+ inner = _input(closure, source)
169
+ if inner is None:
170
+ return (Step(f"{place.subject}: sqlassert does not follow {quoted(target.name)} into it", False, place.origin, "sqlassert", "not-followed"),)
171
+ return tuple(step for column in _upstream(target, source) for step in walk_dependent(inner, column, place))
172
+
173
+
174
+ def _upstream(target: ir.OutputColumn, source: ir.RelationExpr) -> tuple[ir.OutputColumn, ...]:
175
+ """The columns of `source` that `target`'s value is computed from."""
176
+ read = ir.determinants(target.scalar_expr) or ()
177
+ return tuple(column for column in read if column in source.output_columns)
178
+
179
+
180
+ def asserted_place(relation: ir.RelationExpr) -> _Place:
181
+ """The relation a marker asserts about, named by its Attachment Site."""
182
+ program = current_arena().program
183
+ label = next((site.label for site, node in program.attachment_sites if node is relation), None)
184
+ if label is None and isinstance(relation, ir.NamedRelation | ir.Alias):
185
+ return own_place(relation, _Place(relation.name))
186
+ return _Place("the final SELECT" if label in (None, "Root Select") else label, relation.origin if relation.origin.span else None)
187
+
188
+
189
+ def walk_unique(closure: Result[Closure], place: _Place) -> tuple[Step, ...]:
190
+ """Steps saying why the closure misses its relation's Row Identity, or one
191
+ PROVED Step when it reaches it."""
192
+ relation = closure.value.relation.closed
193
+ place = own_place(relation, place)
194
+ if RowIdentity(closure.value.relation) in closure.value.columns:
195
+ return (Step(f"{place.subject}: unique on {_requested(closure)}", True, place.origin),)
196
+ match relation:
197
+ case ir.Alias(source=source):
198
+ return _follow(closure, source, place)
199
+ case ir.NamedRelation(body=ir.RelationExpr() as body):
200
+ inner = _follow(closure, body, place)
201
+ return (Step(f"{place.subject}: not unique on {_requested(closure)}", False, place.origin, steps=inner),)
202
+ case ir.Project(input=source):
203
+ return _project(closure, relation, source, place)
204
+ case ir.Filter(input=source) | ir.Limit(input=source) | ir.Join(kind="semi" | "anti", left=source):
205
+ return _follow(closure, source, place)
206
+ case ir.Join():
207
+ return _join(closure, relation, place)
208
+ case ir.SetOperation(operator="union"):
209
+ return _union(closure, relation)
210
+ case ir.SetOperation(distinct=False, left=source):
211
+ # EXCEPT ALL and INTERSECT ALL keep left rows, as many as each input allows.
212
+ return _follow(closure, source, place)
213
+ case ir.OpaqueRelation():
214
+ return (_opaque(relation, place),)
215
+ case _:
216
+ return (_keys(closure, relation, place),)
217
+
218
+
219
+ def own_place(relation: ir.RelationExpr, place: _Place) -> _Place:
220
+ """How `relation` is named: an Alias or a CTE or view by itself, a clause
221
+ that keeps one row per key by that clause, anything else as the relation
222
+ that reads it names it."""
223
+ match relation.closed:
224
+ case ir.Alias() as alias:
225
+ return _alias_place(alias)
226
+ case ir.NamedRelation(body=ir.RelationExpr()) as named:
227
+ return _named_place(named)
228
+ case ir.Aggregate(grouping_outputs=grouping):
229
+ return _Place(f"GROUP BY {listed(grouping)}", _spanned(relation.origin, place))
230
+ case ir.Distinct():
231
+ return _Place("SELECT DISTINCT", _spanned(relation.origin, place))
232
+ case ir.QualifyByPartition(partition_outputs=partition):
233
+ return _Place(f"one row per {names(partition)}", _spanned(relation.origin, place))
234
+ case ir.SetOperation(operator=operator, distinct=distinct):
235
+ return _Place(f"{operator.upper()}{'' if distinct else ' ALL'}", _spanned(relation.origin, place))
236
+ case _:
237
+ return place
238
+
239
+
240
+ def _spanned(origin: Origin, place: _Place) -> Origin | None:
241
+ return origin if origin.span is not None else place.origin
242
+
243
+
244
+ def _follow(closure: Result[Closure], source: ir.RelationExpr, place: _Place) -> tuple[Step, ...]:
245
+ """The walk of the closure the relation took in `source`."""
246
+ inner = _input(closure, source)
247
+ if inner is None:
248
+ return (Step(f"{place.subject}: sqlassert does not follow the asserted columns into it", False, place.origin, "sqlassert", "not-followed"),)
249
+ return walk_unique(inner, place)
250
+
251
+
252
+ def _input(closure: Result[Closure], source: ir.RelationExpr) -> Result[Closure] | None:
253
+ return next((inner for inner in closure.value.inputs if inner.value.relation is source), None)
254
+
255
+
256
+ def _alias_place(alias: ir.Alias) -> _Place:
257
+ """A table is named as it is read (`accounts AS a`), a derived table by
258
+ its alias; a CTE or view names itself."""
259
+ match alias.source.closed:
260
+ case ir.NamedRelation(body=None):
261
+ return _Place(brief(alias.origin.detail), alias.origin)
262
+ case ir.NamedRelation() as named:
263
+ return _named_place(named)
264
+ case _:
265
+ return _Place(f"subquery {alias.name}", alias.origin)
266
+
267
+
268
+ def _named_place(relation: ir.NamedRelation) -> _Place:
269
+ """A CTE or view, named where it is defined."""
270
+ kind = "CTE" if relation.role is ir.RelationRole.CTE else relation.role.value
271
+ return _Place(f"{kind} {relation.name}", relation.origin)
272
+
273
+
274
+ def _project(closure: Result[Closure], project: ir.Project, source: ir.RelationExpr, place: _Place) -> tuple[Step, ...]:
275
+ """A projection passes the question to its input, except for an asserted
276
+ column it computes so that two input rows may give it one value."""
277
+ _, requested, _ = closure.subjects
278
+ assert isinstance(requested, frozenset)
279
+ kept = _one_to_one(project, source)
280
+ inner = _input(closure, source)
281
+ reached = inner.value.columns if inner is not None else set()
282
+
283
+ def loses(column: ir.OutputColumn) -> bool:
284
+ # A constant, or a function of input columns the walk fixes anyway, loses nothing.
285
+ read = ir.determinants(column.scalar_expr)
286
+ return read is None or not all(member in reached for member in read)
287
+
288
+ computed = [column for column in project.output_columns if column in requested and column not in kept and loses(column)]
289
+ at = _Place(place.subject, _spanned(project.origin, place))
290
+ causes = tuple(computed_column(column, at) for column in computed)
291
+ passed = any(column in kept for column in requested)
292
+ return (*(_follow(closure, source, place) if passed or not causes else ()), *causes)
293
+
294
+
295
+ def computed_column(column: ir.OutputColumn, place: _Place) -> Step:
296
+ """A column whose expression may give rows that differ one value."""
297
+ written = brief(column.origin.detail.rsplit(" AS ", 1)[0])
298
+ if isinstance(column.scalar_expr, ir.OpaqueExpression):
299
+ return Step(f"{quoted(column.name)} = {written}: sqlassert does not model its values", False, place.origin, "sqlassert", "opaque-column")
300
+ return Step(f"{quoted(column.name)} = {written} may give two rows one value", False, place.origin, "sql", "computed-column",
301
+ ("only a column itself, or an exact one-to-one function of one (x + 1), keeps rows apart",))
302
+
303
+
304
+ def _opaque(relation: ir.RelationExpr, place: _Place) -> Step:
305
+ construct = _unsupported_under(relation)
306
+ return Step(f"{place.subject}: its rows are not modelled", False, place.origin, "sqlassert", "unsupported",
307
+ (f"{construct} is not supported by sqlassert yet",) if construct else ())
308
+
309
+
310
+ def _join(closure: Result[Closure], join: ir.Join, place: _Place) -> tuple[Step, ...]:
311
+ """A join needs each row of the input the columns fix to match at most
312
+ once in the other input."""
313
+ reached = closure.value.columns
314
+ left, right = RowIdentity(join.left) in reached, RowIdentity(join.right) in reached
315
+ subject = brief(join.origin.detail)
316
+ if left and not right:
317
+ return _matched(closure, join, "right")
318
+ # A many-to-one join repeats no left row: the left input is what is not unique.
319
+ if many_to_one_join(join).value:
320
+ return (*_follow(closure, join.left, place), Step(f"{subject}: many-to-one", True, join.origin))
321
+ if right and not left:
322
+ return _matched(closure, join, "left")
323
+ # A table function's rows have no key: follow the left input, whose rows it repeats.
324
+ if one_to_many_join(join).value and not join.lateral:
325
+ return (*_follow(closure, join.right, place), Step(f"{subject}: one-to-many", True, join.origin))
326
+ return (*_follow(closure, join.left, place), *_matched(closure, join, "right"))
327
+
328
+
329
+ def _matched(closure: Result[Closure], join: ir.Join, matched: Side) -> tuple[Step, ...]:
330
+ """The join as a Cause: a row of the other input may match several rows
331
+ of `matched`, with what `matched` lacks."""
332
+ side = join.right if matched == "right" else join.left
333
+ inner = _input(closure, side)
334
+ if join.lateral and matched == "right":
335
+ return (Step(f"{brief(join.origin.detail)} repeats each row of its left input once per row it returns", False, join.origin, "sql", "table-function"),)
336
+ return (join_cause(join, matched, walk_unique(inner, side_place(side, join)) if inner is not None else ()),)
337
+
338
+
339
+ def join_cause(join: ir.Join, matched: Side, side: tuple[Step, ...]) -> Step:
340
+ """A join whose rows of the other input may each match several rows of
341
+ `matched`: its Unproved Join Reason in that direction; `side`, the walk
342
+ into `matched`, gives the detail (a table's key gap) or the Steps under it."""
343
+ subject = brief(join.origin.detail)
344
+ reason = unproved_join(join, matched)
345
+ if reason is None:
346
+ # Proved in this direction, yet the identity is not reached: a padded side.
347
+ return Step(f"{subject}: its padded rows cannot be told apart", False, join.origin, "sqlassert", "padded-rows", steps=side)
348
+ details: list[str] = []
349
+ nested: list[Step] = []
350
+ # An ON that binds no column of the input: its keys are beside the point.
351
+ binds = reason.reason not in {"unsupported", "unconstrained", "unresolved-key", "untyped-key", "expression-key"}
352
+ for step in side if binds else ():
353
+ if step.tag is not None and not step.steps and step.code in _KEY_GAPS:
354
+ details.extend((step.text, *step.details))
355
+ elif not step.proved:
356
+ nested.append(step)
357
+ if reason.construct is not None:
358
+ details.append(f"{reason.construct} is not supported by sqlassert yet")
359
+ if reason.untyped is not None:
360
+ details.append(_type_lost(reason.untyped, reason.detail))
361
+ code = reason.reason if reason.detail is None else f"{reason.reason} ({reason.detail})"
362
+ # A key the matched input lacks because of something below it: that is the Cause.
363
+ deferred = reason.reason == "no-unique-set" and any(step.causes() for step in nested)
364
+ tag = None if deferred else _JOIN_TAGS.get(reason.detail or "", _JOIN_TAGS.get(reason.reason, "sql"))
365
+ verb = "is not many-to-one" if matched == "right" else "is not one-to-many"
366
+ return Step(f"{subject} {verb}", False, join.origin, tag, code if tag is not None else None, tuple(details), tuple(nested))
367
+
368
+
369
+ def _type_lost(column: ir.OutputColumn, loss: str | None) -> str:
370
+ """Where a join key's type is lost, for an `untyped-key` join."""
371
+ owner = current_arena().program.column_to_parent_relation_index.get(column)
372
+ where = f" (line {column.origin.line})" if column.origin.line else ""
373
+ match loss:
374
+ case "table":
375
+ name = owner.name if isinstance(owner, ir.NamedRelation) else "its table"
376
+ return f"{quoted(column.name)} has no type: {name} is not declared with CREATE TABLE, or not in the catalog"
377
+ case "computed" | "opaque-relation" if not isinstance(owner, ir.OpaqueRelation):
378
+ computed = f"{quoted(column.name)} = {brief(column.origin.detail.rsplit(' AS ', 1)[0])}{where}"
379
+ if (source := untyped_source(column.scalar_expr)) is None:
380
+ return f"{computed} has a type whose equal values need not be identical"
381
+ return f"{computed} has no type sqlassert knows: {_untyped(source, column.scalar_expr.closed)}"
382
+ case "values":
383
+ return f"{quoted(column.name)} of a VALUES list{where} has no type that compares by identity"
384
+ case "set-operation":
385
+ return f"{quoted(column.name)} of a set operation{where} pairs inputs whose types are not known to agree"
386
+ case "opaque-relation":
387
+ return f"{quoted(column.name)} comes from a relation sqlassert does not model"
388
+ case _:
389
+ return f"{quoted(column.name)} does not compare with the other key without a lossy coercion"
390
+
391
+
392
+ def _untyped(source: Result, top: ir.ScalarExpr) -> str:
393
+ """Why a computed key has no type, from the expression in it that loses
394
+ the type (`untyped_source`): the key's own, or one nested in it, named."""
395
+ subject = source.subjects[0]
396
+ match subject:
397
+ case ir.Call() | ir.OpaquePureFunction():
398
+ why = ("no result type is known for its function", "has no result type sqlassert knows")
399
+ case ir.OpaqueExpression():
400
+ why = ("sqlassert does not model it", "is not modelled by sqlassert")
401
+ case ir.Constant():
402
+ why = ("no type is claimed for the literal in this dialect", "has no type claimed in this dialect")
403
+ case _:
404
+ reason = source.reason[0].lower() + source.reason[1:]
405
+ why = (reason, f"has no type: {reason}")
406
+ if subject is top or not isinstance(subject, ir.ScalarExpr):
407
+ return why[0]
408
+ return f"{brief(subject.origin.detail)} {why[1]}"
409
+
410
+
411
+ def side_place(side: ir.RelationExpr, join: ir.Join) -> _Place:
412
+ """An input of a join, named as it is read."""
413
+ if isinstance(source := side.closed, ir.Alias):
414
+ return _alias_place(source)
415
+ return _Place("its input", join.origin)
416
+
417
+
418
+ def _union(closure: Result[Closure], union: ir.SetOperation) -> tuple[Step, ...]:
419
+ reached = closure.value.columns
420
+ is_definite = _definiteness(closure)
421
+ arms = {column: pair for column in union.output_columns if (pair := _typed_arms(union, column)) is not None}
422
+ determined = [column for column in arms if column in reached]
423
+ separator = next((column for column in determined if _separates(arms[column])), None)
424
+ inputs: list[Step] = []
425
+ for side, source in enumerate((union.left, union.right)):
426
+ inner = _closure(
427
+ source, frozenset(arms[column][side] for column in determined),
428
+ frozenset(arms[column][side] for column in determined if is_definite(column)),
429
+ )
430
+ ordinal = "first" if side == 0 else "second"
431
+ inputs.extend(walk_unique(inner, _Place(f"its {ordinal} input", source.origin if source.origin.span else None)))
432
+ name = "UNION" if union.distinct else "UNION ALL"
433
+ origin = union.origin if union.origin.span else None
434
+ if separator is not None:
435
+ return (Step(f"{name}: inputs separated by {quoted(separator.name)}", True, origin, steps=tuple(inputs)),)
436
+ return (Step(
437
+ f"{name}: no asserted column separates its inputs", False, origin, "sql", "inputs-not-separated",
438
+ ("a column holding a different constant in each input, such as a literal tag, tells their rows apart",),
439
+ tuple(inputs),
440
+ ),)
441
+
442
+
443
+ def _separates(arms: tuple[ir.OutputColumn, ir.OutputColumn]) -> bool:
444
+ """Whether a UNION column is a constant different in each input, as
445
+ `_separated_inputs` requires."""
446
+ first, second = (_constant_value(arm) for arm in arms)
447
+ return first.value is not None and second.value is not None and _distinct_tags(arms, first.value[0], second.value[0])
448
+
449
+
450
+ def _keys(closure: Result[Closure], relation: ir.RelationExpr, place: _Place) -> Step:
451
+ """A relation whose keys the reached columns miss: each closest minimal
452
+ key, and what it lacks."""
453
+ reached = closure.value.columns
454
+ have = _requested(closure)
455
+ missed = f"{place.subject}: {have} is not a key" if have != "()" else f"{place.subject}: none of its columns is fixed"
456
+ if isinstance(relation, ir.NamedRelation) and relation.role is ir.RelationRole.TABLE and not relation.is_schema_complete:
457
+ return Step(f"{place.subject}: no CREATE TABLE declares it, so its keys are unknown", False, place.origin, "declare", "undeclared-table",
458
+ ("declare it with CREATE TABLE, or analyze with a database connection",))
459
+ keys = relation_keys(closure.value.relation)
460
+ if not keys:
461
+ hint = "declare one if it holds" if isinstance(relation, ir.NamedRelation) else "nothing below it keeps its rows apart"
462
+ return Step(missed, False, place.origin, "declare" if isinstance(relation, ir.NamedRelation) else "sql", "no-unique-set",
463
+ (f"it has no Unique Set: {hint}",))
464
+ gaps = [(key, [column for column in relation.output_columns if column in key and column not in reached]) for key in keys]
465
+ fewest = min(len(missing) for _, missing in gaps)
466
+ closest = [(key, missing) for key, missing in gaps if len(missing) == fewest]
467
+ if fewest == 0:
468
+ is_definite = _definiteness(closure)
469
+ nullable = [column for key, _ in closest for column in relation.output_columns if column in key and not is_definite(column)]
470
+ return Step(f"{place.subject}: {have} covers a key whose columns may be NULL", False, place.origin, "sql", "nullable-key",
471
+ (f"a key holds only where {listed(dict.fromkeys(nullable))} are non-null",))
472
+ return Step(missed, False, place.origin, "sql", "missing-key-columns", tuple(
473
+ f"closest minimal key {names(column for column in relation.output_columns if column in key)}, missing {listed(missing)}"
474
+ for key, missing in closest
475
+ ))
476
+
477
+
478
+ def relation_keys(relation: ir.RelationExpr) -> list[frozenset[ir.OutputColumn]]:
479
+ """The minimal keys a relation introduces itself, over its own columns."""
480
+ identity = RowIdentity(relation)
481
+ keys = [
482
+ frozenset(column for column in dependency.determinant if isinstance(column, ir.OutputColumn))
483
+ for dependency in _functional_dependencies(relation).value
484
+ if dependency.dependent == identity and all(isinstance(member, ir.OutputColumn) for member in dependency.determinant)
485
+ ]
486
+ return [key for key in dict.fromkeys(keys) if not any(other < key for other in keys)]
487
+
488
+
489
+ def _definiteness(closure: Result[Closure]) -> Callable[[Attribute], bool]:
490
+ """`_closure`'s own test of a non-null attribute, for the closure taken."""
491
+ relation, _, definite = closure.subjects
492
+ assert isinstance(relation, ir.RelationExpr) and isinstance(definite, frozenset)
493
+ return lambda attribute: attribute in definite or _definite(relation, attribute) or _padded_with(relation, attribute, definite)
494
+
495
+
496
+ def _requested(closure: Result[Closure]) -> str:
497
+ """The columns the closure was taken from: those the assertion fixes in this relation."""
498
+ _, columns, _ = closure.subjects
499
+ assert isinstance(columns, frozenset)
500
+ return names(column for column in closure.value.relation.output_columns if column in columns)
501
+
502
+
503
+ def names(columns: Iterable[ir.OutputColumn]) -> str:
504
+ return f"({listed(columns)})"
505
+
506
+
507
+ def listed(columns: Iterable[ir.OutputColumn]) -> str:
508
+ return ", ".join(shown(column) for column in columns)
509
+
510
+
511
+ def shown(column: ir.OutputColumn) -> str:
512
+ """A column's name, or for a hidden one the expression it holds."""
513
+ if column.name.startswith(_HIDDEN):
514
+ return " ".join(column.origin.detail.rsplit(" AS ", 1)[0].split())
515
+ return column.name
516
+
517
+
518
+ def brief(text: str) -> str:
519
+ """Relation SQL on one line, its ON condition left out when long."""
520
+ text = " ".join(text.split())
521
+ if len(text) > _WIDTH and " ON " in text:
522
+ text = text.split(" ON ")[0] + " ON …"
523
+ return text if len(text) <= _WIDTH else text[:_WIDTH - 1] + "…"
sqlassert/rules/domain.py CHANGED
@@ -37,9 +37,10 @@ from typing import assert_never
37
37
  from sqlassert.diagnostics import quoted
38
38
  from sqlassert import ir
39
39
  from sqlassert import properties as props
40
- from sqlassert.properties import EnumeratedDomain
40
+ from sqlassert.properties import EnumeratedDomain, ExhaustiveCase
41
41
  from sqlassert.python_engine import Result, Stratum, analysis, any_of, current_arena, unknown
42
- from sqlassert.rules.equality import _equal_columns, _lax_equalities, _same_type
42
+ from sqlassert.rules.equality import _equal_columns, _lax_equalities
43
+ from sqlassert.rules.value_typing import _binary_text as _typed_binary_text, column_ref, exact_comparison
43
44
  from sqlassert.rules.nullability import _non_null_expression, non_null_column
44
45
 
45
46
  # A finite set of possible non-null values, or None when any value is possible.
@@ -49,7 +50,7 @@ _TRUE = ir.LiteralValue(type="boolean", text="TRUE")
49
50
  _FALSE = ir.LiteralValue(type="boolean", text="FALSE")
50
51
 
51
52
 
52
- @analysis(Stratum.DOMAIN)
53
+ @analysis(Stratum.DOMAIN, evaluates=EnumeratedDomain)
53
54
  def enumerated_domain(column: ir.OutputColumn, values: frozenset[ir.LiteralValue]) -> Result[bool]:
54
55
  domain = _domain(column)
55
56
  if domain.value is None:
@@ -63,7 +64,7 @@ def enumerated_domain(column: ir.OutputColumn, values: frozenset[ir.LiteralValue
63
64
  return Result(True, "Every possible value is listed", (column,), [domain])
64
65
 
65
66
 
66
- @analysis(Stratum.DOMAIN)
67
+ @analysis(Stratum.DOMAIN, evaluates=ExhaustiveCase)
67
68
  def exhaustive_case(case: ir.SimpleCase) -> Result[bool]:
68
69
  operand = _operand_name(case.operand)
69
70
  domain = _expression_domain(case.operand)
@@ -317,7 +318,7 @@ def _matched_narrowings(join: ir.Join, column: ir.OutputColumn, source: ir.Outpu
317
318
  other = second if first is source else first
318
319
  case _:
319
320
  continue
320
- if other not in join.right.output_columns or not _same_type(source, other):
321
+ if other not in join.right.output_columns or not exact_comparison(column_ref(source), column_ref(other)).value:
321
322
  continue
322
323
  bounds = [bound for part in join.conjuncts if part is not conjunct and (bound := _conjunct_bound(part, other)) is not None]
323
324
  if bounds:
@@ -366,7 +367,7 @@ def _bound_domain(column: ir.OutputColumn, expression: ir.ScalarExpr) -> Result[
366
367
  return Result(None, "An approximate numeric comparison may collapse distinct values", (expression,))
367
368
  case ir.Constant() | ir.NullLiteral():
368
369
  return _expression_domain(expression)
369
- case ir.ColumnRef(column=source) if _same_type(column, source):
370
+ case ir.ColumnRef(column=source) if exact_comparison(column_ref(column), expression).value:
370
371
  return _expression_domain(expression)
371
372
  case _:
372
373
  return Result(None, "The comparison may cast its operands, so no value domain is transferred", (expression,))
@@ -406,7 +407,7 @@ def _binary_text(column: ir.OutputColumn) -> bool:
406
407
  if not _binary_text(source):
407
408
  return False
408
409
  case _:
409
- if not member.binary_text:
410
+ if not _typed_binary_text(member).value:
410
411
  return False
411
412
  return True
412
413