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,470 @@
1
+ """Value typing: how the values of a scalar expression compare, and the one
2
+ question every equality asks of it.
3
+
4
+ `scalar_typing(expression)` is the one place that decides what type an
5
+ expression has, or that it has none known: a column's, a literal's, a call's
6
+ (its Builtin's `typing`, from the function table: a CAST's target, a fixed
7
+ result type, one that follows an argument's, integer arithmetic, a float
8
+ contaminating arithmetic, NULLIF's results' common type), a CASE or COALESCE's
9
+ results' common type. Convert records only what SQL says of one node (a
10
+ declared type, a literal's kind, a CAST's target); everything that follows
11
+ from those is derived here, so no two places can disagree about an expression.
12
+
13
+ Every equality asks one of two questions (ADR 0009):
14
+
15
+ - `exact_comparison(left, right)`: is `left = right` equal, so a TRUE
16
+ comparison means both sides are the same value? Both types are known, and
17
+ either both are text compared by identity, or both are of one type whose
18
+ equal values are identical, or both are exact numbers (integers of any
19
+ width, decimals of any scale, exact literals: the engine compares them by
20
+ value), or one is a string literal and the other a date, time or timestamp
21
+ compared by identity (the literal is read as that type). Equality Groups,
22
+ value domains and foreign-key coverage carry facts from one side to the
23
+ other, so they read this; so does the Hazard of a comparison that is not
24
+ exact.
25
+ - `fixes(bound, value)`: once `value` is known, is at most one value of
26
+ `bound` TRUE against it? An equal comparison fixes; so does one where the
27
+ engine casts a side into the other's type keeping different values
28
+ different (the dialect's cast table, `ir.CastTable.compared`: a DATE beside
29
+ a TIMESTAMP is its midnight). Join keys, Functional Dependencies and
30
+ pinning a column read this.
31
+
32
+ An unknown type gives no fact.
33
+
34
+ A Builtin's properties are a function of its arguments (ADR 0011):
35
+ `call_properties(call)` asks it with each argument's derived type, and
36
+ `reflected_operand(expression)` walks the calls that are one-to-one in their
37
+ one non-constant argument (`x + 1`, `-x`, `2 * x` over exact numbers), for
38
+ keys through a projection, an aggregate's picked value and join key binding.
39
+
40
+ Values are assumed to stay in range (ADR 0007): how a dialect overflows
41
+ changes no type here.
42
+ """
43
+
44
+ from __future__ import annotations
45
+
46
+ from collections.abc import Sequence
47
+ from dataclasses import replace
48
+ from typing import assert_never
49
+
50
+ from sqlassert import ir
51
+ from sqlassert.python_engine import Result, Stratum, analysis, current_arena
52
+
53
+ # What `count(...)` is: an integer, not claimed to be a width.
54
+ _BIGINT = ir.ValueTyping("BIGINT", False, True, True, integer=4, family="integer")
55
+
56
+ def _unknown(expression: object, why: str = "No type is known", premises: Sequence[Result] = ()) -> Result[ir.ValueTyping | None]:
57
+ return Result(None, why, (expression,), list(premises))
58
+
59
+
60
+ def untyped_source(expression: ir.ScalarExpr) -> Result[ir.ValueTyping | None] | None:
61
+ """Where `expression`'s unknown type comes from: the evidence of the
62
+ deepest expression in it with no known type (`scalar_typing`, followed
63
+ through each premise that is unknown too). None when its type is known."""
64
+ result = scalar_typing(expression)
65
+ if result.value is not None:
66
+ return None
67
+ while (unknown := next((premise for premise in result.premises if premise.value is None), None)) is not None:
68
+ result = unknown
69
+ return result
70
+
71
+
72
+ @analysis(Stratum.COMPARISON)
73
+ def scalar_typing(expression: ir.ScalarExpr) -> Result[ir.ValueTyping | None]:
74
+ """How the values of `expression` compare, or None when its type is not known."""
75
+ expression = expression.closed
76
+ match expression:
77
+ case ir.ColumnRef(column=column):
78
+ return _column_typing(column)
79
+ case ir.Constant(typing=ir.ValueTyping() as typing) | ir.OpaqueExpression(typing=ir.ValueTyping() as typing):
80
+ return Result(typing, "The type of a literal or a call the dialect types", (expression,))
81
+ case ir.Count():
82
+ return Result(_BIGINT, "count(...) is an integer", (expression,))
83
+ case ir.AnyAggregate(input=value):
84
+ # A picked value (min, max, any_value) is a value of its input.
85
+ return scalar_typing(value)
86
+ case ir.Call():
87
+ return _call_typing(expression)
88
+ case ir.OpaqueExpression():
89
+ return _unknown(expression, "sqlassert does not model it, so its type is not known")
90
+ case ir.Constant():
91
+ return _unknown(expression, "sqlassert claims no type for the literal in this dialect")
92
+ case ir.NullLiteral():
93
+ return _unknown(expression, "NULL has no type of its own")
94
+ case ir.Coalesce(arguments=arguments):
95
+ return _common_typing(expression, arguments)
96
+ case ir.SimpleCase(thens=thens, default=default):
97
+ return _common_typing(expression, [*thens, default])
98
+ case (
99
+ ir.Accumulation() | ir.Elements()
100
+ | ir.Equality() | ir.NullSafeEquality() | ir.InList() | ir.IsNull() | ir.IsNotNull() | ir.And() | ir.Or()
101
+ ):
102
+ return _unknown(expression)
103
+ case _:
104
+ assert_never(expression)
105
+
106
+
107
+ def _call_typing(call: ir.Call) -> Result[ir.ValueTyping | None]:
108
+ """The type of a call: its Builtin's `typing` (`functions/table.py`), asked
109
+ with the types and literals of the arguments it reads."""
110
+ reads = call.function.typing_reads
111
+ operands = {position: scalar_typing(call.arguments[position]) for position in reads if position < len(call.arguments)}
112
+ arguments = tuple(
113
+ ir.Argument(
114
+ operands[position].value if position in operands else None, argument.value if isinstance(argument, ir.Constant) else None,
115
+ isinstance(argument, ir.NullLiteral),
116
+ )
117
+ for position, argument in enumerate(call.arguments)
118
+ )
119
+ typing, why = call.function.typing(arguments)
120
+ return Result(typing, why, (call,), list(operands.values()))
121
+
122
+
123
+ @analysis(Stratum.COMPARISON)
124
+ def _column_typing(column: ir.OutputColumn) -> Result[ir.ValueTyping | None]:
125
+ """The type of a column: the one it is declared with, else its expression's.
126
+ A set operation's column has its inputs' when they share it, not the left
127
+ input's: the engine would cast one to the other; a recursive CTE's has its
128
+ base case's (the left input's) whatever the recursive arm computes, since
129
+ the engine casts the arm to it or rejects a mismatch. A recursive reference's
130
+ column has its base case's (`RecursiveRelation.typed_by`): the engine fixes
131
+ the type there, and nothing else about its values is known."""
132
+ relation = column.get_relation(current_arena().program)
133
+ if isinstance(relation, ir.RecursiveRelation):
134
+ base = relation.typed_by[relation.output_columns.index(column)] if relation.typed_by else None
135
+ if base is None:
136
+ return _unknown(column, "The base case of the recursion has no such column")
137
+ typing = _column_typing(base)
138
+ return Result(typing.value, "A recursive CTE's column has the type of its base case", (column,), [typing])
139
+ if isinstance(relation, ir.SetOperation):
140
+ if (arms := relation.arms(column)) is not None:
141
+ if relation.recursive:
142
+ base = _column_typing(arms[0])
143
+ return Result(base.value, "A recursive CTE's column has the type of its base case, whatever the recursive arm computes", (column,), [base])
144
+ left, right = (_column_typing(arm) for arm in arms)
145
+ first, second = left.value, right.value
146
+ if first is not None and second is not None and first.comparison_type == second.comparison_type:
147
+ shared = replace(
148
+ first, binary_text=first.binary_text and second.binary_text,
149
+ identity_comparison=first.identity_comparison and second.identity_comparison,
150
+ exact_numeric=first.exact_numeric and second.exact_numeric, floating=first.floating and second.floating,
151
+ integer=first.integer if first.integer == second.integer else None, text=first.text and second.text,
152
+ temporal=first.temporal and second.temporal, family=first.family if first.family == second.family else None,
153
+ length=first.length if first.length == second.length else None,
154
+ precision=first.precision if first.precision == second.precision else None,
155
+ scale=first.scale if first.scale == second.scale else None,
156
+ )
157
+ return Result(shared, "Both inputs of the set operation share the type", (column,), [left, right])
158
+ return _unknown(column, "The inputs of the set operation do not share a type", [left, right])
159
+ return _unknown(column, "The inputs of the set operation do not share a type")
160
+ if column.typing is not None:
161
+ return Result(column.typing, "Declared type", (column,))
162
+ return scalar_typing(column.scalar_expr)
163
+
164
+
165
+ def _common_typing(expression: ir.ScalarExpr, results: Sequence[ir.ScalarExpr]) -> Result[ir.ValueTyping | None]:
166
+ """The type of a COALESCE or simple CASE that returns one of `results` (or
167
+ NULL): the type they share (`ir.common_typing`, which a call's `common`
168
+ typing asks too)."""
169
+ typed = {id(value): scalar_typing(value) for value in results if not isinstance(value, ir.NullLiteral)}
170
+ arguments = [
171
+ ir.Argument(
172
+ typed[id(value)].value if id(value) in typed else None, value.value if isinstance(value, ir.Constant) else None,
173
+ isinstance(value, ir.NullLiteral),
174
+ )
175
+ for value in results
176
+ ]
177
+ typing, why = ir.common_typing(arguments)
178
+ literals = [value for value in results if isinstance(value, ir.Constant) and value.value is not None and value.value.type == "string"]
179
+ premises = [typed[id(value)] for value in results if id(value) in typed and not any(value is literal for literal in literals)]
180
+ if typing is None:
181
+ return _unknown(expression, why, premises if why == ir.NO_KNOWN_TYPE else ())
182
+ if not premises and literals:
183
+ first = typed[id(literals[0])]
184
+ return Result(first.value, why, (expression,), [first])
185
+ return Result(typing, why, (expression,), premises)
186
+
187
+
188
+ @analysis(Stratum.COMPARISON)
189
+ def exact_comparison(left: ir.ScalarExpr, right: ir.ScalarExpr) -> Result[bool]:
190
+ """Whether `left = right` compares their values without a lossy coercion."""
191
+ first, second = scalar_typing(left), scalar_typing(right)
192
+ premises = [first, second]
193
+ match left.closed, right.closed:
194
+ case ir.ColumnRef(column=one), ir.ColumnRef(column=other) if one is other:
195
+ return Result(True, "A column equals itself", (left, right))
196
+ case _:
197
+ pass
198
+ a, b = first.value, second.value
199
+ if a is None or b is None:
200
+ return Result(False, "A type is not known", (left, right), premises)
201
+ if a.binary_text and b.binary_text:
202
+ return Result(True, "Text compared by identity on both sides", (left, right), premises)
203
+ if a.identity_comparison and b.identity_comparison and a.comparison_type == b.comparison_type:
204
+ return Result(True, "Both sides have one type whose equal values are identical", (left, right), premises)
205
+ if a.exact_numeric and b.exact_numeric:
206
+ return Result(True, "Exact numbers compare by value whatever their width or scale", (left, right), premises)
207
+ if _string_literal(left) and b.temporal and b.identity_comparison or _string_literal(right) and a.temporal and a.identity_comparison:
208
+ return Result(True, "A string literal is read as the date or time it is compared with", (left, right), premises)
209
+ if a.identity_comparison and b.identity_comparison and (table := a.casts or b.casts) is not None:
210
+ kind, why = table.compared(a, b)
211
+ if kind == "widening":
212
+ return Result(True, f"The comparison widens a side: {why}", (left, right), premises)
213
+ return Result(False, "The comparison may coerce a side and lose what tells values apart", (left, right), premises)
214
+
215
+
216
+ @analysis(Stratum.COMPARISON)
217
+ def fixes(bound: ir.ScalarExpr, value: ir.ScalarExpr) -> Result[bool]:
218
+ """Whether `bound = value` fixes `bound`: once `value` is known, at most
219
+ one value of `bound` makes it TRUE (ADR 0009). An equal comparison
220
+ (`exact_comparison`) does. So does one where the engine casts one side
221
+ into the other's type, keeping different values different (the dialect's
222
+ cast table, `ir.CastTable.compared`), and both compare by identity:
223
+ `day = ts` compares the date's midnight, so a timestamp equals at most one
224
+ date and a date at most one timestamp. Each side fixes the other, though
225
+ they are not equal."""
226
+ exact = exact_comparison(bound, value)
227
+ if exact.value:
228
+ return Result(True, "An equal comparison fixes each side", (bound, value), [exact])
229
+ first, second = scalar_typing(bound), scalar_typing(value)
230
+ premises = [exact, first, second]
231
+ a, b = first.value, second.value
232
+ if a is not None and b is not None and a.identity_comparison and b.identity_comparison and (table := a.casts or b.casts) is not None:
233
+ kind, why = table.compared(a, b)
234
+ if kind != "lossy":
235
+ return Result(True, f"The comparison casts a side: {why}", (bound, value), premises)
236
+ return Result(False, "The comparison may coerce a side and lose what tells values apart", (bound, value), premises)
237
+
238
+
239
+ @analysis(Stratum.COMPARISON)
240
+ def call_properties(call: ir.Call) -> Result[ir.CallProperties]:
241
+ """`call`'s Builtin's properties, given each argument's derived type and
242
+ literal value and the call's own type (ADR 0011)."""
243
+ typed = [scalar_typing(argument) for argument in call.arguments]
244
+ result = scalar_typing(call)
245
+ summaries = tuple(
246
+ ir.Argument(typing.value, argument.value if isinstance(argument, ir.Constant) else None)
247
+ for argument, typing in zip(call.arguments, typed)
248
+ )
249
+ properties = call.function.properties(summaries, result.value)
250
+ return Result(properties, properties.reason, (call,), [*typed, result])
251
+
252
+
253
+ @analysis(Stratum.COMPARISON)
254
+ def reflected_operand(expression: ir.ScalarExpr) -> Result[ir.ScalarExpr]:
255
+ """The innermost expression `expression` is a one-to-one function of:
256
+ through each Builtin call whose arguments but one are constant and that
257
+ reflects equality in that one (`call_properties`: `x + 1`, `-x`, `2 * x`
258
+ over exact numbers), down to the first expression that is not such a
259
+ call; `expression` itself when it is not one."""
260
+ match expression.closed:
261
+ case ir.Call(arguments=arguments) as call:
262
+ varying = [position for position, argument in enumerate(arguments) if ir.determinants(argument) != ()]
263
+ if len(varying) != 1:
264
+ return Result(expression, "Not a function of one argument, the others constant", (expression,))
265
+ properties = call_properties(call)
266
+ if not properties.value.reflects[varying[0]]:
267
+ return Result(expression, properties.value.reason, (expression,), [properties])
268
+ inner = reflected_operand(arguments[varying[0]])
269
+ return Result(inner.value, properties.value.reason, (expression,), [properties, inner])
270
+ case _:
271
+ return Result(expression, "Not a call of a Builtin", (expression,))
272
+
273
+
274
+ def reflected_column(expression: ir.ScalarExpr) -> Result[ir.OutputColumn | None]:
275
+ """The one column `expression` is a one-to-one function of: the column
276
+ itself, or one reached through calls that reflect equality
277
+ (`reflected_operand`); None when there is none."""
278
+ operand = reflected_operand(expression)
279
+ match operand.value.closed:
280
+ case ir.ColumnRef(column=column):
281
+ return Result(column, "One-to-one in one column", (expression,), [operand])
282
+ case _:
283
+ return Result(None, "Not one-to-one in a column", (expression,), [operand])
284
+
285
+
286
+ def stopping_call(expression: ir.ScalarExpr) -> tuple[ir.Call, str] | None:
287
+ """Where the walk of `reflected_operand` stops short of a column, when it
288
+ stops at a call of one varying argument that does not reflect equality:
289
+ that call and its property function's reason. None when it reaches a
290
+ column, or stops at anything else."""
291
+ stop = reflected_operand(expression).value.closed
292
+ match stop:
293
+ case ir.Call(arguments=arguments):
294
+ if sum(ir.determinants(argument) != () for argument in arguments) != 1:
295
+ return None
296
+ return stop, call_properties(stop).value.reason
297
+ case _:
298
+ return None
299
+
300
+
301
+ @analysis(Stratum.COMPARISON)
302
+ def respects_equality(expression: ir.ScalarExpr, column: ir.OutputColumn) -> Result[bool]:
303
+ """Whether `expression` gives equal values for rows whose values of
304
+ `column` compare equal, its other columns fixed: whether its value is
305
+ determined by `column`'s, up to the equality its type compares by (ADR
306
+ 0011, "respects equality").
307
+
308
+ Any pure function of a column compared by identity does: equal values are
309
+ identical. Otherwise each call on the way to the column must respect
310
+ equality in the argument that leads there (`call_properties`), and the
311
+ nodes with no property function do where it is clear they do: IS NULL
312
+ and IS NOT NULL always (equal values are both NULL or both not); AND and
313
+ OR of booleans; a comparison or IN whose sides compare alike (`_alike`);
314
+ COALESCE and a simple CASE when each value they may return compares as
315
+ their result does, and a CASE's operand alike with its WHEN values. An
316
+ unmodelled function, or composite elements, need not."""
317
+ inputs = ir.determinants(expression)
318
+ if inputs is None:
319
+ return Result(False, "Not a function of the columns it reads", (expression,))
320
+ if column not in inputs:
321
+ return Result(True, "Does not read the column", (expression, column))
322
+ typing = _column_typing(column)
323
+ if typing.value is not None and typing.value.identity_comparison:
324
+ return Result(True, "A pure function of a column compared by identity: equal values are identical", (expression, column), [typing])
325
+ expression = expression.closed
326
+ match expression:
327
+ case ir.ColumnRef() | ir.Constant() | ir.NullLiteral():
328
+ return Result(True, "The column itself", (expression, column))
329
+ case ir.Call(function=ir.Builtin(modelled=False), description=description):
330
+ why = f"{description} may tell apart values that compare equal: sqlassert does not model it"
331
+ return Result(False, why, (expression, column), [typing])
332
+ case ir.Call(arguments=arguments):
333
+ properties = call_properties(expression)
334
+ parts: list[Result[bool]] = []
335
+ for argument, respects in zip(arguments, properties.value.respects):
336
+ if column not in (ir.determinants(argument) or ()):
337
+ continue
338
+ if not respects:
339
+ why = f"{expression.description} may tell apart values that compare equal"
340
+ return Result(False, why, (expression, column), [properties, typing])
341
+ parts.append(respects_equality(argument, column))
342
+ return _respected(expression, column, parts, "Each call on the way respects equality", [properties])
343
+ case ir.IsNull(operand=operand) | ir.IsNotNull(operand=operand):
344
+ return _respected(expression, column, [respects_equality(operand, column)], "Equal values are both NULL or both not")
345
+ case ir.And(parts=operands) | ir.Or(parts=operands):
346
+ return _respected(expression, column, [respects_equality(part, column) for part in operands], "A function of booleans")
347
+ case ir.Equality(left=left, right=right) | ir.NullSafeEquality(left=left, right=right):
348
+ return _compared(expression, column, (left, right))
349
+ case ir.InList(operand=operand, values=values):
350
+ return _compared(expression, column, (operand, *values))
351
+ case ir.Coalesce(arguments=arguments):
352
+ return _returned(expression, column, (), arguments)
353
+ case ir.SimpleCase(operand=operand, whens=whens, thens=thens, default=default):
354
+ return _returned(expression, column, (operand, *whens), (*thens, default))
355
+ case ir.Elements() | ir.OpaqueExpression() | ir.Count() | ir.AnyAggregate() | ir.Accumulation():
356
+ return Result(False, "Its value is not known to follow the column's", (expression, column), [typing])
357
+ case _:
358
+ assert_never(expression)
359
+
360
+
361
+ def _respected(
362
+ expression: ir.ScalarExpr, column: ir.OutputColumn, parts: Sequence[Result[bool]], reason: str, premises: Sequence[Result] = (),
363
+ ) -> Result[bool]:
364
+ failed = next((part for part in parts if not part.value), None)
365
+ if failed is not None:
366
+ return Result(False, _why(failed), (expression, column), [*premises, failed])
367
+ return Result(True, reason, (expression, column), [*premises, *parts])
368
+
369
+
370
+ def _why(result: Result) -> str:
371
+ """A result's own reason, under the claim an analysis wraps it in."""
372
+ while result.kind == "claim" and result.premises:
373
+ result = result.premises[0]
374
+ return result.reason
375
+
376
+
377
+ def _alike(a: ir.ValueTyping | None, b: ir.ValueTyping | None) -> bool:
378
+ """Whether values of `a`, compared with or turned into values of `b`,
379
+ keep the equality they compare by: `a` compares by identity, or both are
380
+ text (of the one default collation), both floats, or one type."""
381
+ if a is None or b is None:
382
+ return False
383
+ return a.identity_comparison or a.text and b.text or a.floating and b.floating or a.comparison_type == b.comparison_type
384
+
385
+
386
+ def _compared(expression: ir.ScalarExpr, column: ir.OutputColumn, operands: Sequence[ir.ScalarExpr]) -> Result[bool]:
387
+ """A comparison of `operands` respects equality in `column` when each
388
+ operand that reads it does, and compares alike with every other operand."""
389
+ typings = [scalar_typing(operand).value for operand in operands]
390
+ for operand, typing in zip(operands, typings):
391
+ if column in (ir.determinants(operand) or ()) and not all(_alike(typing, other) for other in typings):
392
+ why = f"{expression.origin.detail or 'A comparison'} may compare its sides differently from how they compare alone"
393
+ return Result(False, why, (expression, column))
394
+ parts = [respects_equality(operand, column) for operand in operands]
395
+ return _respected(expression, column, parts, "A comparison of sides that compare alike")
396
+
397
+
398
+ def _returned(
399
+ expression: ir.ScalarExpr, column: ir.OutputColumn, compared: Sequence[ir.ScalarExpr], results: Sequence[ir.ScalarExpr],
400
+ ) -> Result[bool]:
401
+ """COALESCE or a simple CASE: the `compared` operands (a CASE's operand
402
+ and WHEN values) compare alike, and each of `results` compares as the
403
+ expression's own result does."""
404
+ typings = [scalar_typing(operand).value for operand in compared]
405
+ result = scalar_typing(expression).value
406
+ alike = all(
407
+ all(_alike(typing, other) for other in typings) for operand, typing in zip(compared, typings) if column in (ir.determinants(operand) or ())
408
+ ) and all(_alike(scalar_typing(value).value, result) for value in results if column in (ir.determinants(value) or ()))
409
+ if not alike:
410
+ why = f"{expression.origin.detail or 'A COALESCE or CASE'} may turn values that compare equal into ones that do not"
411
+ return Result(False, why, (expression, column))
412
+ parts = [respects_equality(operand, column) for operand in (*compared, *results)]
413
+ return _respected(expression, column, parts, "Each value it returns respects equality")
414
+
415
+
416
+ def respected_inputs(expression: ir.ScalarExpr) -> Result[tuple[ir.OutputColumn, ...] | None]:
417
+ """The columns `expression` is determined by (`ir.determinants`), when it
418
+ respects equality in each (`respects_equality`); None when it does not, or
419
+ is not a function of its columns."""
420
+ inputs = ir.determinants(expression)
421
+ if inputs is None:
422
+ return Result(None, "Not a function of the columns it reads", (expression,))
423
+ parts = [respects_equality(expression, column) for column in inputs]
424
+ failed = next((part for part in parts if not part.value), None)
425
+ if failed is not None:
426
+ return Result(None, _why(failed), (expression,), [failed])
427
+ return Result(inputs, "Determined by the columns it reads", (expression,), parts)
428
+
429
+
430
+ def _string_literal(expression: ir.ScalarExpr) -> bool:
431
+ match expression.closed:
432
+ case ir.Constant(value=ir.LiteralValue(type="string")):
433
+ return True
434
+ case _:
435
+ return False
436
+
437
+
438
+ def column_ref(column: ir.OutputColumn) -> ir.ColumnRef:
439
+ """A reference to `column`, to ask `exact_comparison` of it."""
440
+ return ir.ColumnRef(origin=column.origin, column=column)
441
+
442
+
443
+ # Questions about one column's type -------------------------------------------
444
+
445
+
446
+ def _comparison_type(column: ir.OutputColumn) -> Result[str | None]:
447
+ typing = _column_typing(column)
448
+ return Result(None if typing.value is None else typing.value.comparison_type, "Comparison type", (column,), [typing])
449
+
450
+
451
+ def _identity_comparison(column: ir.OutputColumn) -> Result[bool]:
452
+ """Whether equal values of `column` are identical."""
453
+ typing = _column_typing(column)
454
+ return Result(typing.value is not None and typing.value.identity_comparison, "Type compares by identity", (column,), [typing])
455
+
456
+
457
+ def _binary_text(column: ir.OutputColumn) -> Result[bool]:
458
+ """Whether `column` is text compared by identity."""
459
+ typing = _column_typing(column)
460
+ return Result(typing.value is not None and typing.value.binary_text, "Text compared by identity", (column,), [typing])
461
+
462
+
463
+ def _boolean(column: ir.OutputColumn) -> bool:
464
+ typing = _column_typing(column).value
465
+ return typing is not None and typing.comparison_type == "BOOLEAN"
466
+
467
+
468
+ def _signed_integer(column: ir.OutputColumn) -> bool:
469
+ typing = _column_typing(column).value
470
+ return typing is not None and typing.integer is not None
sqlassert/sql_parse.py CHANGED
@@ -265,6 +265,7 @@ _MARKER_POSITION = "sqlassert.marker_position"
265
265
  # `(start, start)`: its end is its marker position). Rewrites place their
266
266
  # edits from these and the token stream (`edits.py`).
267
267
  _SPAN = "sqlassert.span"
268
+ _WRITTEN_AT = "sqlassert.written_at"
268
269
 
269
270
  # Tokens that end a set operation's operand but not the query: another
270
271
  # operator, or the parenthesis around the operand.
@@ -520,6 +521,7 @@ def sqlassert_dialect(base: str) -> type[Dialect]:
520
521
  join.meta[_MARKER_POSITION] = (start.start, start.line)
521
522
  if self._prev is not None:
522
523
  join.meta[_SPAN] = (start.start, self._prev.end + 1)
524
+ join.meta[_WRITTEN_AT] = Span.of(self.sql, start.start, self._prev.end + 1)
523
525
  return join
524
526
 
525
527
  kind = JOIN_MARKER_KINDS[self._curr.token_type]
@@ -536,11 +538,14 @@ def sqlassert_dialect(base: str) -> type[Dialect]:
536
538
  if self._curr is not None and self._curr.token_type is TokenType.COMMA:
537
539
  raise unattached
538
540
 
541
+ start = self._curr
539
542
  join = super()._parse_join(*args, **kwargs)
540
543
  if join is None:
541
544
  raise unattached
542
545
 
543
546
  join.meta[_ASSERTED_AT] = span
547
+ if start is not None and self._prev is not None:
548
+ join.meta[_WRITTEN_AT] = Span.of(self.sql, start.start, self._prev.end + 1)
544
549
  join.meta[_JOIN_MARKER_KIND] = kind
545
550
  return join
546
551
 
@@ -1047,6 +1052,22 @@ def span(node: Expr) -> tuple[int, int] | None:
1047
1052
  return node.meta.get(_SPAN)
1048
1053
 
1049
1054
 
1055
+ def written_at(node: Expr) -> Span | None:
1056
+ """Where `node` is written: a Join from its first keyword to its last
1057
+ token; any other node from its first identifier or literal to its last,
1058
+ the positions SQLGlot keeps (keywords and parentheses around them are left
1059
+ out). None when it carries no position."""
1060
+ if (at := node.meta.get(_WRITTEN_AT)) is not None:
1061
+ return at
1062
+ tokens = [descendant.meta for descendant in node.walk() if "start" in descendant.meta and "col" in descendant.meta]
1063
+ if not tokens:
1064
+ return None
1065
+ first = min(tokens, key=lambda meta: meta["start"])
1066
+ last = max(tokens, key=lambda meta: meta["end"])
1067
+ # SQLGlot's `col` is the column of a token's last character.
1068
+ return Span(first["line"], first["col"] - (first["end"] - first["start"]), last["line"], last["col"] + 1)
1069
+
1070
+
1050
1071
  def column_markers(query: exp.Query) -> tuple[ColumnMarker, ...]:
1051
1072
  """Every column marker written on `query` -- a Select, or a set operation
1052
1073
  when written after its last token. Those whose kind is in
@@ -1061,9 +1082,15 @@ def grouping(select: exp.Select) -> list[Expr] | None:
1061
1082
  window, with no GROUP BY) or `GROUP BY ()`. The empty grouping set groups
1062
1083
  by nothing, so `GROUP BY (), a` is `GROUP BY a`. GROUPING SETS, ROLLUP and
1063
1084
  CUBE are not in the list: the caller checks the Group for them. An
1064
- aggregate under QUALIFY is None: QUALIFY lowers it.
1085
+ aggregate under QUALIFY is None: QUALIFY lowers it. `GROUP BY ALL` groups
1086
+ by the select items that contain no aggregate or window.
1065
1087
  """
1066
1088
  group = select.args.get("group")
1089
+ if isinstance(group, exp.Group) and group.args.get("all"):
1090
+ return [
1091
+ item.this if isinstance(item, exp.Alias) else item for item in select.expressions
1092
+ if item.find(exp.AggFunc, exp.Window) is None
1093
+ ]
1067
1094
  if isinstance(group, exp.Group):
1068
1095
  return [expression for expression in group.expressions if not (isinstance(expression, exp.Tuple) and not expression.expressions)]
1069
1096
  if select.args.get("qualify") is None and any(
sqlassert/suggest.py CHANGED
@@ -19,7 +19,7 @@ from __future__ import annotations
19
19
 
20
20
  from collections.abc import Callable, Iterable, Iterator
21
21
  from contextlib import AbstractContextManager
22
- from dataclasses import dataclass, fields
22
+ from dataclasses import dataclass
23
23
  from decimal import Decimal
24
24
  from itertools import combinations
25
25
  from typing import ClassVar
@@ -30,8 +30,9 @@ from sqlassert import diagnostics as diag
30
30
  from sqlassert import ir
31
31
  from sqlassert.diagnostics import Diagnostic
32
32
  from sqlassert.edits import Edit
33
- from sqlassert.rewrites import Rewrite, SuggestType, RewriteKind, rewrites
33
+ from sqlassert.rewrites import Caveat, CaveatKind, Rewrite, SuggestType, RewriteKind, rewrites
34
34
  from sqlassert.ir.convert import IrConversionResult, IrParser
35
+ from sqlassert.ir.names import nameable
35
36
  from sqlassert.hazards import Concern, Hazard, hazards
36
37
  from sqlassert.main import DEFAULT_DIALECT
37
38
  from sqlassert.properties import (
@@ -51,7 +52,7 @@ DEFAULT_MAX_SIZE = 3
51
52
  MAX_ENUM_VALUES = 10
52
53
 
53
54
  __all__ = [
54
- "Candidate", "Concern", "Edit", "Rewrite", "SuggestType", "RewriteKind", "Hazard", "Suggester", "Suggestion", "SuggestionReport",
55
+ "Candidate", "Caveat", "CaveatKind", "Concern", "Edit", "Rewrite", "SuggestType", "RewriteKind", "Hazard", "Suggester", "Suggestion", "SuggestionReport",
55
56
  "annotate", "candidates", "suggest", "suggest_parsed",
56
57
  ]
57
58
 
@@ -113,7 +114,7 @@ def annotate(sql: str, items: Iterable[Candidate | Suggestion]) -> str:
113
114
 
114
115
 
115
116
  def suggest(
116
- sql: str, *, dialect: str = DEFAULT_DIALECT, max_size: int = DEFAULT_MAX_SIZE, trust_unenforced_keys: bool = True,
117
+ sql: str, *, dialect: str = DEFAULT_DIALECT, max_size: int = DEFAULT_MAX_SIZE,
117
118
  ) -> SuggestionReport:
118
119
  """Every Property sqlassert can prove about `sql`, as markers to paste,
119
120
  and every Rewrite a proof justifies.
@@ -128,7 +129,7 @@ def suggest(
128
129
  Properties the SQL already asserts or declares are left out.
129
130
  """
130
131
  ast = SqlParser(dialect).parse(sql)
131
- return suggest_parsed(sql, ast, IrParser(dialect, trust_unenforced_keys).parse(ast), dialect=dialect, max_size=max_size)
132
+ return suggest_parsed(sql, ast, IrParser(dialect).parse(ast), dialect=dialect, max_size=max_size)
132
133
 
133
134
 
134
135
  def suggest_parsed(
@@ -158,7 +159,7 @@ class Suggester:
158
159
  self.diagnostics = ast.diagnostics + conversion.diagnostics
159
160
  self.blocked = any(diagnostic.code in _BLOCKING for diagnostic in self.diagnostics)
160
161
  present = (*self.program.declarations, *(assertion.property for assertion in self.program.assertions))
161
- self.marked = {_identity(item) for item in present}
162
+ self.marked = set(present)
162
163
  self.marked_non_null = {
163
164
  column
164
165
  for item in present
@@ -179,8 +180,8 @@ class Suggester:
179
180
  self._arena = self._session.__enter__()
180
181
  try:
181
182
  if not self.blocked:
182
- self._rewrites = rewrites(self.ast, self.program, self._arena, self.dialect, wanted=self.sites)
183
- self._hazards = hazards(self.ast, self.program, self._arena, self.dialect, wanted=self.sites)
183
+ self._rewrites = rewrites(self.ast, self.conversion, self._arena, self.dialect, wanted=self.sites)
184
+ self._hazards = hazards(self.conversion, self._arena, wanted=self.sites)
184
185
  except BaseException as error:
185
186
  self.__exit__(type(error), error, error.__traceback__)
186
187
  raise
@@ -224,7 +225,7 @@ class Suggester:
224
225
  suggestions.extend(_select_suggestions(arena, site, relation, self.max_size, self.marked_non_null, dialect))
225
226
  kept = tuple(
226
227
  sorted(
227
- (suggestion for suggestion in suggestions if _identity(suggestion.property) not in self.marked),
228
+ (suggestion for suggestion in suggestions if suggestion.property not in self.marked),
228
229
  key=lambda suggestion: suggestion.site.offset,
229
230
  )
230
231
  )
@@ -366,14 +367,9 @@ def _column_sets(columns: tuple[ir.OutputColumn, ...], max_size: int) -> Iterato
366
367
 
367
368
 
368
369
  def _nameable_columns(relation: ir.RelationExpr) -> tuple[ir.OutputColumn, ...]:
369
- """Output columns a marker names unambiguously: named, and named once."""
370
- names = [column.name.lower() for column in relation.output_columns]
371
- return tuple(column for column in relation.output_columns if column.name and names.count(column.name.lower()) == 1)
372
-
373
-
374
- def _identity(item: Property) -> tuple:
375
- """Properties compare by identity; this compares them by kind and fields."""
376
- return (type(item), tuple(getattr(item, field.name) for field in fields(item)))
370
+ """Output columns a marker names unambiguously: named, named once, and not
371
+ a name an engine may give a repeated column (`ir/names.py`)."""
372
+ return nameable(relation.output_columns)
377
373
 
378
374
 
379
375
  def _value_order(value: ir.LiteralValue) -> tuple: