sqlassert 0.4.1__py3-none-any.whl → 0.4.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sqlassert/declared_types.py +158 -0
- sqlassert/diagnostics.py +1 -4
- sqlassert/dialects.py +118 -396
- sqlassert/discovery/bigquery.py +2 -2
- sqlassert/discovery/databricks.py +4 -6
- sqlassert/discovery/fetcher.py +22 -52
- sqlassert/discovery/information_schema.py +7 -10
- sqlassert/discovery/mysql.py +4 -8
- sqlassert/discovery/postgres.py +17 -26
- sqlassert/discovery/redshift.py +2 -2
- sqlassert/discovery/snowflake.py +2 -2
- sqlassert/functions/__init__.py +10 -0
- sqlassert/functions/load.py +375 -0
- sqlassert/functions/table.py +2721 -0
- sqlassert/hazards.py +1 -1
- sqlassert/ir/__init__.py +13 -5
- sqlassert/ir/convert/aggregation.py +2 -3
- sqlassert/ir/convert/expressions.py +76 -67
- sqlassert/ir/convert/parser.py +0 -4
- sqlassert/ir/convert/schema.py +11 -80
- sqlassert/ir/convert/selects.py +30 -15
- sqlassert/ir/convert/shared.py +2 -3
- sqlassert/ir/convert/sources.py +2 -1
- sqlassert/ir/convert/value_types.py +12 -157
- sqlassert/ir/model.py +331 -138
- sqlassert/main.py +7 -10
- sqlassert/rules/causes/domain.py +1 -1
- sqlassert/rules/causes/unique.py +46 -5
- sqlassert/rules/domain.py +1 -1
- sqlassert/rules/join_cardinality.py +14 -21
- sqlassert/rules/nullability.py +3 -3
- sqlassert/rules/uniqueness.py +42 -41
- sqlassert/rules/value_typing.py +266 -133
- sqlassert/suggest.py +2 -2
- {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/METADATA +18 -14
- sqlassert-0.4.2.dist-info/RECORD +72 -0
- sqlassert/ir/convert/builtins.py +0 -140
- sqlassert-0.4.1.dist-info/RECORD +0 -69
- {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/WHEEL +0 -0
- {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/entry_points.txt +0 -0
- {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/licenses/LICENSE +0 -0
- {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/top_level.txt +0 -0
sqlassert/rules/value_typing.py
CHANGED
|
@@ -2,12 +2,13 @@
|
|
|
2
2
|
question every equality asks of it.
|
|
3
3
|
|
|
4
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
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
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.
|
|
11
12
|
|
|
12
13
|
Every equality asks one of two questions (ADR 0009):
|
|
13
14
|
|
|
@@ -24,11 +25,18 @@ Every equality asks one of two questions (ADR 0009):
|
|
|
24
25
|
- `fixes(bound, value)`: once `value` is known, is at most one value of
|
|
25
26
|
`bound` TRUE against it? An equal comparison fixes; so does one where the
|
|
26
27
|
engine casts a side into the other's type keeping different values
|
|
27
|
-
different (`
|
|
28
|
-
midnight). Join keys, Functional Dependencies and
|
|
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.
|
|
29
31
|
|
|
30
32
|
An unknown type gives no fact.
|
|
31
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
|
+
|
|
32
40
|
Values are assumed to stay in range (ADR 0007): how a dialect overflows
|
|
33
41
|
changes no type here.
|
|
34
42
|
"""
|
|
@@ -36,19 +44,14 @@ changes no type here.
|
|
|
36
44
|
from __future__ import annotations
|
|
37
45
|
|
|
38
46
|
from collections.abc import Sequence
|
|
47
|
+
from dataclasses import replace
|
|
39
48
|
from typing import assert_never
|
|
40
49
|
|
|
41
50
|
from sqlassert import ir
|
|
42
51
|
from sqlassert.python_engine import Result, Stratum, analysis, current_arena
|
|
43
52
|
|
|
44
53
|
# What `count(...)` is: an integer, not claimed to be a width.
|
|
45
|
-
_BIGINT = ir.ValueTyping("BIGINT", False, True, True, integer=4)
|
|
46
|
-
# What exact arithmetic over a decimal is: no precision or scale is claimed, so no
|
|
47
|
-
# type but another computed decimal's is the same.
|
|
48
|
-
_DECIMAL_EXPRESSION = ir.ValueTyping("DECIMAL EXPRESSION", False, True, True)
|
|
49
|
-
|
|
50
|
-
_ARITHMETIC = {"+", "-", "*", "unary -"}
|
|
51
|
-
|
|
54
|
+
_BIGINT = ir.ValueTyping("BIGINT", False, True, True, integer=4, family="integer")
|
|
52
55
|
|
|
53
56
|
def _unknown(expression: object, why: str = "No type is known", premises: Sequence[Result] = ()) -> Result[ir.ValueTyping | None]:
|
|
54
57
|
return Result(None, why, (expression,), list(premises))
|
|
@@ -66,14 +69,6 @@ def untyped_source(expression: ir.ScalarExpr) -> Result[ir.ValueTyping | None] |
|
|
|
66
69
|
return result
|
|
67
70
|
|
|
68
71
|
|
|
69
|
-
def _untyped_call(expression: ir.Call | ir.OpaquePureFunction | ir.OpaqueExpression) -> Result[ir.ValueTyping | None]:
|
|
70
|
-
"""A call with no known type: sqlassert knows no result type for it (the
|
|
71
|
-
Diagnostic `unknown-function` says where), or does not model it."""
|
|
72
|
-
if isinstance(expression, ir.OpaqueExpression):
|
|
73
|
-
return _unknown(expression, "sqlassert does not model it, so its type is not known")
|
|
74
|
-
return _unknown(expression, "sqlassert knows no result type for the function in this dialect")
|
|
75
|
-
|
|
76
|
-
|
|
77
72
|
@analysis(Stratum.COMPARISON)
|
|
78
73
|
def scalar_typing(expression: ir.ScalarExpr) -> Result[ir.ValueTyping | None]:
|
|
79
74
|
"""How the values of `expression` compare, or None when its type is not known."""
|
|
@@ -88,20 +83,10 @@ def scalar_typing(expression: ir.ScalarExpr) -> Result[ir.ValueTyping | None]:
|
|
|
88
83
|
case ir.AnyAggregate(input=value):
|
|
89
84
|
# A picked value (min, max, any_value) is a value of its input.
|
|
90
85
|
return scalar_typing(value)
|
|
91
|
-
case ir.Call(typing=ir.ValueTyping() as typing) | ir.OpaquePureFunction(typing=ir.ValueTyping() as typing):
|
|
92
|
-
return Result(typing, "The type of a CAST or of a function the dialect gives a fixed result type", (expression,))
|
|
93
|
-
case ir.Call(typed_by=ir.ArgumentTyping() as by, arguments=arguments) | ir.OpaquePureFunction(typed_by=ir.ArgumentTyping() as by, arguments=arguments):
|
|
94
|
-
return _argument_typing(expression, by, arguments[by.argument])
|
|
95
|
-
case ir.Call(function=ir.Builtin(name="nullif"), arguments=arguments):
|
|
96
|
-
return _common_typing(expression, arguments)
|
|
97
|
-
case ir.Call(function=function) if function.name in _ARITHMETIC:
|
|
98
|
-
return _arithmetic_typing(expression)
|
|
99
86
|
case ir.Call():
|
|
100
|
-
return
|
|
101
|
-
case ir.
|
|
102
|
-
return
|
|
103
|
-
case ir.OpaquePureFunction() | ir.OpaqueExpression():
|
|
104
|
-
return _untyped_call(expression)
|
|
87
|
+
return _call_typing(expression)
|
|
88
|
+
case ir.OpaqueExpression():
|
|
89
|
+
return _unknown(expression, "sqlassert does not model it, so its type is not known")
|
|
105
90
|
case ir.Constant():
|
|
106
91
|
return _unknown(expression, "sqlassert claims no type for the literal in this dialect")
|
|
107
92
|
case ir.NullLiteral():
|
|
@@ -119,19 +104,20 @@ def scalar_typing(expression: ir.ScalarExpr) -> Result[ir.ValueTyping | None]:
|
|
|
119
104
|
assert_never(expression)
|
|
120
105
|
|
|
121
106
|
|
|
122
|
-
def
|
|
123
|
-
"""The type of a call
|
|
124
|
-
the
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
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()))
|
|
135
121
|
|
|
136
122
|
|
|
137
123
|
@analysis(Stratum.COMPARISON)
|
|
@@ -158,11 +144,15 @@ def _column_typing(column: ir.OutputColumn) -> Result[ir.ValueTyping | None]:
|
|
|
158
144
|
left, right = (_column_typing(arm) for arm in arms)
|
|
159
145
|
first, second = left.value, right.value
|
|
160
146
|
if first is not None and second is not None and first.comparison_type == second.comparison_type:
|
|
161
|
-
shared =
|
|
162
|
-
first
|
|
163
|
-
first.identity_comparison and second.identity_comparison,
|
|
164
|
-
first.
|
|
165
|
-
first.
|
|
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,
|
|
166
156
|
)
|
|
167
157
|
return Result(shared, "Both inputs of the set operation share the type", (column,), [left, right])
|
|
168
158
|
return _unknown(column, "The inputs of the set operation do not share a type", [left, right])
|
|
@@ -173,64 +163,26 @@ def _column_typing(column: ir.OutputColumn) -> Result[ir.ValueTyping | None]:
|
|
|
173
163
|
|
|
174
164
|
|
|
175
165
|
def _common_typing(expression: ir.ScalarExpr, results: Sequence[ir.ScalarExpr]) -> Result[ir.ValueTyping | None]:
|
|
176
|
-
"""The type of
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
if not
|
|
190
|
-
|
|
191
|
-
if
|
|
192
|
-
|
|
193
|
-
first =
|
|
194
|
-
return Result(first.value,
|
|
195
|
-
|
|
196
|
-
if literals:
|
|
197
|
-
if not all(typing.binary_text or typing.temporal for typing in known):
|
|
198
|
-
return _unknown(expression, "A string literal beside a type that is not text compared by identity, nor a date or time")
|
|
199
|
-
if len(set(known)) == 1:
|
|
200
|
-
return Result(known[0], "The results share a type", (expression,), premises)
|
|
201
|
-
if (widest := _widest_integer(known)) is not None:
|
|
202
|
-
return Result(widest, "The results are integers: the widest", (expression,), premises)
|
|
203
|
-
return _unknown(expression, "The results have different types")
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
def _arithmetic_typing(call: ir.Call) -> Result[ir.ValueTyping | None]:
|
|
207
|
-
"""The type of `+`, `-`, `*` or negation over typed operands, in every
|
|
208
|
-
dialect: values are assumed to stay in range (ADR 0007), so overflow does
|
|
209
|
-
not change it.
|
|
210
|
-
|
|
211
|
-
A float operand makes the result a float. Integers give the widest
|
|
212
|
-
integer; the negation of an exact number has its type; any other
|
|
213
|
-
arithmetic over exact numbers is a decimal, whose precision is not
|
|
214
|
-
claimed. Any other call has no known type.
|
|
215
|
-
|
|
216
|
-
Provenance: DuckDB 2.0.0 `typeof` (`-x` is `x`'s type; `x + 1`, `x * 2` of an
|
|
217
|
-
integer type keep it; `DECIMAL(10,2) + 1` is `DECIMAL(13,2)`); other engines
|
|
218
|
-
from memory (docs/dialects.md, "Types of computed expressions")."""
|
|
219
|
-
operands = [scalar_typing(argument) for argument in call.arguments]
|
|
220
|
-
typings = [operand.value for operand in operands]
|
|
221
|
-
if any(typing is None for typing in typings):
|
|
222
|
-
return _unknown(call, "An operand has no known type", operands)
|
|
223
|
-
known = [typing for typing in typings if typing is not None]
|
|
224
|
-
floats = [typing for typing in known if typing.floating]
|
|
225
|
-
if floats:
|
|
226
|
-
return Result(floats[0], "A float operand makes the arithmetic a float", (call,), operands)
|
|
227
|
-
if (widest := _widest_integer(known)) is not None:
|
|
228
|
-
return Result(widest, "Integer arithmetic over integers is an integer", (call,), operands)
|
|
229
|
-
if not all(typing.exact_numeric for typing in known):
|
|
230
|
-
return _unknown(call, "An operand is not a number")
|
|
231
|
-
if len(known) == 1:
|
|
232
|
-
return Result(known[0], "Negation keeps the type of an exact number", (call,), operands)
|
|
233
|
-
return Result(_DECIMAL_EXPRESSION, "Arithmetic over exact numbers is a decimal", (call,), operands)
|
|
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)
|
|
234
186
|
|
|
235
187
|
|
|
236
188
|
@analysis(Stratum.COMPARISON)
|
|
@@ -254,6 +206,10 @@ def exact_comparison(left: ir.ScalarExpr, right: ir.ScalarExpr) -> Result[bool]:
|
|
|
254
206
|
return Result(True, "Exact numbers compare by value whatever their width or scale", (left, right), premises)
|
|
255
207
|
if _string_literal(left) and b.temporal and b.identity_comparison or _string_literal(right) and a.temporal and a.identity_comparison:
|
|
256
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)
|
|
257
213
|
return Result(False, "The comparison may coerce a side and lose what tells values apart", (left, right), premises)
|
|
258
214
|
|
|
259
215
|
|
|
@@ -262,30 +218,213 @@ def fixes(bound: ir.ScalarExpr, value: ir.ScalarExpr) -> Result[bool]:
|
|
|
262
218
|
"""Whether `bound = value` fixes `bound`: once `value` is known, at most
|
|
263
219
|
one value of `bound` makes it TRUE (ADR 0009). An equal comparison
|
|
264
220
|
(`exact_comparison`) does. So does one where the engine casts one side
|
|
265
|
-
into the other's type, keeping different values different
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
side fixes the other, though
|
|
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."""
|
|
269
226
|
exact = exact_comparison(bound, value)
|
|
270
227
|
if exact.value:
|
|
271
228
|
return Result(True, "An equal comparison fixes each side", (bound, value), [exact])
|
|
272
229
|
first, second = scalar_typing(bound), scalar_typing(value)
|
|
273
230
|
premises = [exact, first, second]
|
|
274
231
|
a, b = first.value, second.value
|
|
275
|
-
if a is not None and b is not None and a.identity_comparison and b.identity_comparison:
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
return Result(True, why, (bound, value), premises)
|
|
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)
|
|
280
236
|
return Result(False, "The comparison may coerce a side and lose what tells values apart", (bound, value), premises)
|
|
281
237
|
|
|
282
238
|
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
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)
|
|
289
428
|
|
|
290
429
|
|
|
291
430
|
def _string_literal(expression: ir.ScalarExpr) -> bool:
|
|
@@ -321,12 +460,6 @@ def _binary_text(column: ir.OutputColumn) -> Result[bool]:
|
|
|
321
460
|
return Result(typing.value is not None and typing.value.binary_text, "Text compared by identity", (column,), [typing])
|
|
322
461
|
|
|
323
462
|
|
|
324
|
-
def exact_numeric(column: ir.OutputColumn) -> Result[bool]:
|
|
325
|
-
"""Whether `column` is an integer or decimal."""
|
|
326
|
-
typing = _column_typing(column)
|
|
327
|
-
return Result(typing.value is not None and typing.value.exact_numeric, "An integer or decimal", (column,), [typing])
|
|
328
|
-
|
|
329
|
-
|
|
330
463
|
def _boolean(column: ir.OutputColumn) -> bool:
|
|
331
464
|
typing = _column_typing(column).value
|
|
332
465
|
return typing is not None and typing.comparison_type == "BOOLEAN"
|
sqlassert/suggest.py
CHANGED
|
@@ -114,7 +114,7 @@ def annotate(sql: str, items: Iterable[Candidate | Suggestion]) -> str:
|
|
|
114
114
|
|
|
115
115
|
|
|
116
116
|
def suggest(
|
|
117
|
-
sql: str, *, dialect: str = DEFAULT_DIALECT, max_size: int = DEFAULT_MAX_SIZE,
|
|
117
|
+
sql: str, *, dialect: str = DEFAULT_DIALECT, max_size: int = DEFAULT_MAX_SIZE,
|
|
118
118
|
) -> SuggestionReport:
|
|
119
119
|
"""Every Property sqlassert can prove about `sql`, as markers to paste,
|
|
120
120
|
and every Rewrite a proof justifies.
|
|
@@ -129,7 +129,7 @@ def suggest(
|
|
|
129
129
|
Properties the SQL already asserts or declares are left out.
|
|
130
130
|
"""
|
|
131
131
|
ast = SqlParser(dialect).parse(sql)
|
|
132
|
-
return suggest_parsed(sql, ast, IrParser(dialect
|
|
132
|
+
return suggest_parsed(sql, ast, IrParser(dialect).parse(ast), dialect=dialect, max_size=max_size)
|
|
133
133
|
|
|
134
134
|
|
|
135
135
|
def suggest_parsed(
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: sqlassert
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.2
|
|
4
4
|
Summary: Asserts and static proofs for your SQL, without touching your data.
|
|
5
5
|
Author: Fred Israel
|
|
6
6
|
License-Expression: MIT
|
|
@@ -19,10 +19,12 @@ Requires-Python: >=3.13
|
|
|
19
19
|
Description-Content-Type: text/markdown
|
|
20
20
|
License-File: LICENSE
|
|
21
21
|
Requires-Dist: case-conversion>=3.0.2
|
|
22
|
-
Requires-Dist: sqlglot<
|
|
22
|
+
Requires-Dist: sqlglot<30.34,>=30.33
|
|
23
23
|
Provides-Extra: test
|
|
24
24
|
Requires-Dist: duckdb>=2.0; extra == "test"
|
|
25
25
|
Requires-Dist: hypothesis; extra == "test"
|
|
26
|
+
Requires-Dist: markdown-it-py; extra == "test"
|
|
27
|
+
Requires-Dist: pyyaml; extra == "test"
|
|
26
28
|
Requires-Dist: pytest; extra == "test"
|
|
27
29
|
Requires-Dist: pytest-xdist; extra == "test"
|
|
28
30
|
Provides-Extra: dev
|
|
@@ -31,6 +33,8 @@ Provides-Extra: docs
|
|
|
31
33
|
Requires-Dist: zensical>=0.1.4; extra == "docs"
|
|
32
34
|
Dynamic: license-file
|
|
33
35
|
|
|
36
|
+
<img src="https://raw.githubusercontent.com/polvoazul/sqlassert/main/docs/site/assets/favicon.svg" width="72" alt="sqlassert logo">
|
|
37
|
+
|
|
34
38
|
# sqlassert
|
|
35
39
|
|
|
36
40
|
[](https://pypi.org/project/sqlassert/)
|
|
@@ -173,7 +177,7 @@ Proved tests are passed to `dbt build` as `--exclude`, so they never run. See [s
|
|
|
173
177
|
## What it proves
|
|
174
178
|
|
|
175
179
|
| Assertion | Marker | Guards against | `DECLARE` form |
|
|
176
|
-
|
|
180
|
+
|---|---|---|
|
|
177
181
|
| [Join cardinality](https://polvoazul.github.io/sqlassert/markers/#join-cardinality) | `UNIQUE`, `MANY TO ONE`, `ONE TO MANY`, `ONE TO ONE` before a join | row multiplication | – |
|
|
178
182
|
| [Exactly One Join](https://polvoazul.github.io/sqlassert/markers/#exactly-one-join) | `EXACTLY ONE` before a join | rows multiplied *or dropped*; a LEFT JOIN that pads | – |
|
|
179
183
|
| [Unique Set](https://polvoazul.github.io/sqlassert/markers/#unique-set-and-non-null-unique-set) | `UNIQUE(cols)`, `NOT NULL UNIQUE(cols)`, `PRIMARY KEY(cols)` | duplicate keys, wrong grain | yes |
|
|
@@ -194,23 +198,23 @@ Every marker is a SQL comment (`/**ASSERT ...**/`), so annotated SQL still runs
|
|
|
194
198
|
| [`sqlassert suggest`](https://polvoazul.github.io/sqlassert/cli/#sqlassert-suggest) | Lists provable markers, proved rewrites, and hazards (fan traps, chasm traps, arbitrary LIMIT, ...). |
|
|
195
199
|
| [`sqlassert-dbt`](https://github.com/polvoazul/sqlassert/tree/main/integrations/dbt#readme) | Checks a dbt project from its manifest and skips the tests the SQL proves. |
|
|
196
200
|
|
|
197
|
-
| Dialect |
|
|
198
|
-
|
|
199
|
-
| DuckDB |
|
|
200
|
-
| PostgreSQL |
|
|
201
|
-
| MySQL 8.4+ (strict `sql_mode`) |
|
|
202
|
-
| Snowflake |
|
|
203
|
-
| BigQuery |
|
|
204
|
-
| Databricks / Spark |
|
|
205
|
-
| Redshift |
|
|
206
|
-
| Trino |
|
|
201
|
+
| Dialect | Catalog fetcher | Support |
|
|
202
|
+
|---|---|---|
|
|
203
|
+
| DuckDB | yes | high, plus the soundness oracle |
|
|
204
|
+
| PostgreSQL | yes | low |
|
|
205
|
+
| MySQL 8.4+ (strict `sql_mode`) | yes | low |
|
|
206
|
+
| Snowflake | yes | low |
|
|
207
|
+
| BigQuery | yes | low |
|
|
208
|
+
| Databricks / Spark | yes | low |
|
|
209
|
+
| Redshift | yes | low |
|
|
210
|
+
| Trino | yes (NOT NULL only) | low |
|
|
207
211
|
|
|
208
212
|
A low-support dialect has dialect facts written from memory and not yet
|
|
209
213
|
probed on the engine, so its analysis can contain mistakes: a PROVED
|
|
210
214
|
assertion there can be wrong. A dialect with no such fact is high support
|
|
211
215
|
(DuckDB, SQLite); see [Support levels](https://github.com/polvoazul/sqlassert/blob/main/docs/dialects.md#support-levels).
|
|
212
216
|
|
|
213
|
-
|
|
217
|
+
Every declared key, foreign key and CHECK is trusted, whether or not the engine enforces it: Snowflake, BigQuery, Databricks and Redshift keys prove what they state (see [Dialects](https://polvoazul.github.io/sqlassert/dialects/)).
|
|
214
218
|
|
|
215
219
|
## Documentation
|
|
216
220
|
|