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.
- sqlassert/__init__.py +1 -2
- sqlassert/check.py +88 -13
- sqlassert/diagnostics.py +17 -6
- sqlassert/dialects.py +437 -7
- sqlassert/discovery/bigquery.py +3 -1
- sqlassert/discovery/databricks.py +25 -2
- sqlassert/discovery/duckdb.py +49 -7
- sqlassert/discovery/fetcher.py +130 -21
- sqlassert/discovery/information_schema.py +30 -2
- sqlassert/discovery/mysql.py +22 -1
- sqlassert/discovery/postgres.py +22 -5
- sqlassert/discovery/redshift.py +3 -2
- sqlassert/discovery/snowflake.py +3 -0
- sqlassert/discovery/trino.py +2 -2
- sqlassert/hazards.py +248 -87
- sqlassert/ir/__init__.py +4 -1
- sqlassert/ir/convert/__init__.py +13 -0
- sqlassert/ir/convert/aggregation.py +439 -0
- sqlassert/ir/convert/builtins.py +140 -0
- sqlassert/ir/convert/expressions.py +572 -0
- sqlassert/ir/convert/joins.py +264 -0
- sqlassert/ir/convert/markers.py +249 -0
- sqlassert/ir/convert/parser.py +253 -0
- sqlassert/ir/convert/queries.py +259 -0
- sqlassert/ir/convert/schema.py +606 -0
- sqlassert/ir/convert/scopes.py +205 -0
- sqlassert/ir/convert/selects.py +337 -0
- sqlassert/ir/convert/shared.py +429 -0
- sqlassert/ir/convert/sources.py +432 -0
- sqlassert/ir/convert/subqueries.py +364 -0
- sqlassert/ir/convert/value_types.py +223 -0
- sqlassert/ir/convert/windows.py +275 -0
- sqlassert/ir/model.py +125 -47
- sqlassert/ir/names.py +63 -0
- sqlassert/properties.py +12 -1
- sqlassert/provenance.py +5 -1
- sqlassert/python_engine.py +104 -44
- sqlassert/reporting.py +33 -32
- sqlassert/rewrites.py +111 -61
- sqlassert/rules/STYLEGUIDE.md +3 -2
- sqlassert/rules/causes/__init__.py +41 -0
- sqlassert/rules/causes/coverage.py +113 -0
- sqlassert/rules/causes/domain.py +123 -0
- sqlassert/rules/causes/joins.py +73 -0
- sqlassert/rules/causes/nulls.py +154 -0
- sqlassert/rules/causes/unique.py +523 -0
- sqlassert/rules/domain.py +8 -7
- sqlassert/rules/equality.py +6 -147
- sqlassert/rules/exactly_one.py +2 -1
- sqlassert/rules/foreign_key.py +8 -9
- sqlassert/rules/join_cardinality.py +282 -41
- sqlassert/rules/nullability.py +5 -5
- sqlassert/rules/uniqueness.py +171 -47
- sqlassert/rules/value_typing.py +337 -0
- sqlassert/sql_parse.py +28 -1
- sqlassert/suggest.py +11 -15
- sqlassert-0.4.1.dist-info/METADATA +235 -0
- sqlassert-0.4.1.dist-info/RECORD +69 -0
- sqlassert/ir/convert.py +0 -3509
- sqlassert-0.3.3.dist-info/METADATA +0 -807
- sqlassert-0.3.3.dist-info/RECORD +0 -46
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/WHEEL +0 -0
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/entry_points.txt +0 -0
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/licenses/LICENSE +0 -0
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,337 @@
|
|
|
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 CAST's,
|
|
6
|
+
a function the dialect gives a fixed result type, integer arithmetic, a float
|
|
7
|
+
contaminating arithmetic, a CASE, COALESCE or NULLIF's results' common type.
|
|
8
|
+
Convert records only what SQL says of one node (a declared type, a literal's
|
|
9
|
+
kind, a CAST's target, a fixed result type); everything that follows from
|
|
10
|
+
those is derived here, so no two places can disagree about an expression.
|
|
11
|
+
|
|
12
|
+
Every equality asks one of two questions (ADR 0009):
|
|
13
|
+
|
|
14
|
+
- `exact_comparison(left, right)`: is `left = right` equal, so a TRUE
|
|
15
|
+
comparison means both sides are the same value? Both types are known, and
|
|
16
|
+
either both are text compared by identity, or both are of one type whose
|
|
17
|
+
equal values are identical, or both are exact numbers (integers of any
|
|
18
|
+
width, decimals of any scale, exact literals: the engine compares them by
|
|
19
|
+
value), or one is a string literal and the other a date, time or timestamp
|
|
20
|
+
compared by identity (the literal is read as that type). Equality Groups,
|
|
21
|
+
value domains and foreign-key coverage carry facts from one side to the
|
|
22
|
+
other, so they read this; so does the Hazard of a comparison that is not
|
|
23
|
+
exact.
|
|
24
|
+
- `fixes(bound, value)`: once `value` is known, is at most one value of
|
|
25
|
+
`bound` TRUE against it? An equal comparison fixes; so does one where the
|
|
26
|
+
engine casts a side into the other's type keeping different values
|
|
27
|
+
different (`ValueTyping.casts_to`: a DATE beside a TIMESTAMP is its
|
|
28
|
+
midnight). Join keys, Functional Dependencies and pinning a column read this.
|
|
29
|
+
|
|
30
|
+
An unknown type gives no fact.
|
|
31
|
+
|
|
32
|
+
Values are assumed to stay in range (ADR 0007): how a dialect overflows
|
|
33
|
+
changes no type here.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
from __future__ import annotations
|
|
37
|
+
|
|
38
|
+
from collections.abc import Sequence
|
|
39
|
+
from typing import assert_never
|
|
40
|
+
|
|
41
|
+
from sqlassert import ir
|
|
42
|
+
from sqlassert.python_engine import Result, Stratum, analysis, current_arena
|
|
43
|
+
|
|
44
|
+
# 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
|
+
|
|
52
|
+
|
|
53
|
+
def _unknown(expression: object, why: str = "No type is known", premises: Sequence[Result] = ()) -> Result[ir.ValueTyping | None]:
|
|
54
|
+
return Result(None, why, (expression,), list(premises))
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def untyped_source(expression: ir.ScalarExpr) -> Result[ir.ValueTyping | None] | None:
|
|
58
|
+
"""Where `expression`'s unknown type comes from: the evidence of the
|
|
59
|
+
deepest expression in it with no known type (`scalar_typing`, followed
|
|
60
|
+
through each premise that is unknown too). None when its type is known."""
|
|
61
|
+
result = scalar_typing(expression)
|
|
62
|
+
if result.value is not None:
|
|
63
|
+
return None
|
|
64
|
+
while (unknown := next((premise for premise in result.premises if premise.value is None), None)) is not None:
|
|
65
|
+
result = unknown
|
|
66
|
+
return result
|
|
67
|
+
|
|
68
|
+
|
|
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
|
+
@analysis(Stratum.COMPARISON)
|
|
78
|
+
def scalar_typing(expression: ir.ScalarExpr) -> Result[ir.ValueTyping | None]:
|
|
79
|
+
"""How the values of `expression` compare, or None when its type is not known."""
|
|
80
|
+
expression = expression.closed
|
|
81
|
+
match expression:
|
|
82
|
+
case ir.ColumnRef(column=column):
|
|
83
|
+
return _column_typing(column)
|
|
84
|
+
case ir.Constant(typing=ir.ValueTyping() as typing) | ir.OpaqueExpression(typing=ir.ValueTyping() as typing):
|
|
85
|
+
return Result(typing, "The type of a literal or a call the dialect types", (expression,))
|
|
86
|
+
case ir.Count():
|
|
87
|
+
return Result(_BIGINT, "count(...) is an integer", (expression,))
|
|
88
|
+
case ir.AnyAggregate(input=value):
|
|
89
|
+
# A picked value (min, max, any_value) is a value of its input.
|
|
90
|
+
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
|
+
case ir.Call():
|
|
100
|
+
return _untyped_call(expression)
|
|
101
|
+
case ir.OpaquePureFunction(arguments=arguments, results=tuple() as results):
|
|
102
|
+
return _common_typing(expression, [arguments[position] for position in results])
|
|
103
|
+
case ir.OpaquePureFunction() | ir.OpaqueExpression():
|
|
104
|
+
return _untyped_call(expression)
|
|
105
|
+
case ir.Constant():
|
|
106
|
+
return _unknown(expression, "sqlassert claims no type for the literal in this dialect")
|
|
107
|
+
case ir.NullLiteral():
|
|
108
|
+
return _unknown(expression, "NULL has no type of its own")
|
|
109
|
+
case ir.Coalesce(arguments=arguments):
|
|
110
|
+
return _common_typing(expression, arguments)
|
|
111
|
+
case ir.SimpleCase(thens=thens, default=default):
|
|
112
|
+
return _common_typing(expression, [*thens, default])
|
|
113
|
+
case (
|
|
114
|
+
ir.Accumulation() | ir.Elements()
|
|
115
|
+
| ir.Equality() | ir.NullSafeEquality() | ir.InList() | ir.IsNull() | ir.IsNotNull() | ir.And() | ir.Or()
|
|
116
|
+
):
|
|
117
|
+
return _unknown(expression)
|
|
118
|
+
case _:
|
|
119
|
+
assert_never(expression)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _argument_typing(expression: ir.ScalarExpr, by: ir.ArgumentTyping, argument: ir.ScalarExpr) -> Result[ir.ValueTyping | None]:
|
|
123
|
+
"""The type of a call that follows its argument's (`ir.ArgumentTyping`):
|
|
124
|
+
the one the dialect gives for the argument's type, or the argument's own
|
|
125
|
+
where it keeps it; unknown for any other type."""
|
|
126
|
+
typed = scalar_typing(argument)
|
|
127
|
+
if typed.value is None:
|
|
128
|
+
return _unknown(expression, "The argument its type follows has no known type", [typed])
|
|
129
|
+
result = dict(by.results).get(typed.value.comparison_type)
|
|
130
|
+
if result is not None:
|
|
131
|
+
return Result(result, "The type the dialect gives for its argument's type", (expression,), [typed])
|
|
132
|
+
if by.keeps:
|
|
133
|
+
return Result(typed.value, "The type of its argument", (expression,), [typed])
|
|
134
|
+
return _unknown(expression, "The dialect gives no type for its argument's type")
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@analysis(Stratum.COMPARISON)
|
|
138
|
+
def _column_typing(column: ir.OutputColumn) -> Result[ir.ValueTyping | None]:
|
|
139
|
+
"""The type of a column: the one it is declared with, else its expression's.
|
|
140
|
+
A set operation's column has its inputs' when they share it, not the left
|
|
141
|
+
input's: the engine would cast one to the other; a recursive CTE's has its
|
|
142
|
+
base case's (the left input's) whatever the recursive arm computes, since
|
|
143
|
+
the engine casts the arm to it or rejects a mismatch. A recursive reference's
|
|
144
|
+
column has its base case's (`RecursiveRelation.typed_by`): the engine fixes
|
|
145
|
+
the type there, and nothing else about its values is known."""
|
|
146
|
+
relation = column.get_relation(current_arena().program)
|
|
147
|
+
if isinstance(relation, ir.RecursiveRelation):
|
|
148
|
+
base = relation.typed_by[relation.output_columns.index(column)] if relation.typed_by else None
|
|
149
|
+
if base is None:
|
|
150
|
+
return _unknown(column, "The base case of the recursion has no such column")
|
|
151
|
+
typing = _column_typing(base)
|
|
152
|
+
return Result(typing.value, "A recursive CTE's column has the type of its base case", (column,), [typing])
|
|
153
|
+
if isinstance(relation, ir.SetOperation):
|
|
154
|
+
if (arms := relation.arms(column)) is not None:
|
|
155
|
+
if relation.recursive:
|
|
156
|
+
base = _column_typing(arms[0])
|
|
157
|
+
return Result(base.value, "A recursive CTE's column has the type of its base case, whatever the recursive arm computes", (column,), [base])
|
|
158
|
+
left, right = (_column_typing(arm) for arm in arms)
|
|
159
|
+
first, second = left.value, right.value
|
|
160
|
+
if first is not None and second is not None and first.comparison_type == second.comparison_type:
|
|
161
|
+
shared = ir.ValueTyping(
|
|
162
|
+
first.comparison_type, first.binary_text and second.binary_text,
|
|
163
|
+
first.identity_comparison and second.identity_comparison, first.exact_numeric and second.exact_numeric,
|
|
164
|
+
first.floating and second.floating, first.integer if first.integer == second.integer else None,
|
|
165
|
+
first.text and second.text, first.temporal and second.temporal, first.casts_to & second.casts_to,
|
|
166
|
+
)
|
|
167
|
+
return Result(shared, "Both inputs of the set operation share the type", (column,), [left, right])
|
|
168
|
+
return _unknown(column, "The inputs of the set operation do not share a type", [left, right])
|
|
169
|
+
return _unknown(column, "The inputs of the set operation do not share a type")
|
|
170
|
+
if column.typing is not None:
|
|
171
|
+
return Result(column.typing, "Declared type", (column,))
|
|
172
|
+
return scalar_typing(column.scalar_expr)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _common_typing(expression: ir.ScalarExpr, results: Sequence[ir.ScalarExpr]) -> Result[ir.ValueTyping | None]:
|
|
176
|
+
"""The type of an expression that returns one of `results` (or NULL): the
|
|
177
|
+
one they share (the NULLs take it); among integer types the widest, an
|
|
178
|
+
integer type being all that every engine promotes them to; a string
|
|
179
|
+
literal beside text compared by identity, or beside a date, time or
|
|
180
|
+
timestamp, is that type. None when a result has no known type, or the
|
|
181
|
+
types differ (the Hazard `Mixed CASE types`)."""
|
|
182
|
+
values = [result for result in results if not isinstance(result, ir.NullLiteral)]
|
|
183
|
+
literals = [value for value in values if isinstance(value, ir.Constant) and value.value is not None and value.value.type == "string"]
|
|
184
|
+
typed = [scalar_typing(value) for value in values if not any(value is literal for literal in literals)]
|
|
185
|
+
typings = [result.value for result in typed]
|
|
186
|
+
if None in typings:
|
|
187
|
+
return _unknown(expression, "A result has no known type", typed)
|
|
188
|
+
known = [typing for typing in typings if typing is not None]
|
|
189
|
+
if not known:
|
|
190
|
+
# Only NULLs and string literals: the literals' type.
|
|
191
|
+
if not literals:
|
|
192
|
+
return _unknown(expression, "Every result is NULL")
|
|
193
|
+
first = scalar_typing(literals[0])
|
|
194
|
+
return Result(first.value, "Every result is a string literal", (expression,), [first])
|
|
195
|
+
premises = typed
|
|
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)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
@analysis(Stratum.COMPARISON)
|
|
237
|
+
def exact_comparison(left: ir.ScalarExpr, right: ir.ScalarExpr) -> Result[bool]:
|
|
238
|
+
"""Whether `left = right` compares their values without a lossy coercion."""
|
|
239
|
+
first, second = scalar_typing(left), scalar_typing(right)
|
|
240
|
+
premises = [first, second]
|
|
241
|
+
match left.closed, right.closed:
|
|
242
|
+
case ir.ColumnRef(column=one), ir.ColumnRef(column=other) if one is other:
|
|
243
|
+
return Result(True, "A column equals itself", (left, right))
|
|
244
|
+
case _:
|
|
245
|
+
pass
|
|
246
|
+
a, b = first.value, second.value
|
|
247
|
+
if a is None or b is None:
|
|
248
|
+
return Result(False, "A type is not known", (left, right), premises)
|
|
249
|
+
if a.binary_text and b.binary_text:
|
|
250
|
+
return Result(True, "Text compared by identity on both sides", (left, right), premises)
|
|
251
|
+
if a.identity_comparison and b.identity_comparison and a.comparison_type == b.comparison_type:
|
|
252
|
+
return Result(True, "Both sides have one type whose equal values are identical", (left, right), premises)
|
|
253
|
+
if a.exact_numeric and b.exact_numeric:
|
|
254
|
+
return Result(True, "Exact numbers compare by value whatever their width or scale", (left, right), premises)
|
|
255
|
+
if _string_literal(left) and b.temporal and b.identity_comparison or _string_literal(right) and a.temporal and a.identity_comparison:
|
|
256
|
+
return Result(True, "A string literal is read as the date or time it is compared with", (left, right), premises)
|
|
257
|
+
return Result(False, "The comparison may coerce a side and lose what tells values apart", (left, right), premises)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
@analysis(Stratum.COMPARISON)
|
|
261
|
+
def fixes(bound: ir.ScalarExpr, value: ir.ScalarExpr) -> Result[bool]:
|
|
262
|
+
"""Whether `bound = value` fixes `bound`: once `value` is known, at most
|
|
263
|
+
one value of `bound` makes it TRUE (ADR 0009). An equal comparison
|
|
264
|
+
(`exact_comparison`) does. So does one where the engine casts one side
|
|
265
|
+
into the other's type, keeping different values different, and both
|
|
266
|
+
compare by identity: `day = ts` compares the date's midnight, so a
|
|
267
|
+
timestamp equals at most one date and a date at most one timestamp. Each
|
|
268
|
+
side fixes the other, though they are not equal."""
|
|
269
|
+
exact = exact_comparison(bound, value)
|
|
270
|
+
if exact.value:
|
|
271
|
+
return Result(True, "An equal comparison fixes each side", (bound, value), [exact])
|
|
272
|
+
first, second = scalar_typing(bound), scalar_typing(value)
|
|
273
|
+
premises = [exact, first, second]
|
|
274
|
+
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
|
+
for source, target in ((a, b), (b, a)):
|
|
277
|
+
if target.comparison_type in source.casts_to:
|
|
278
|
+
why = f"The engine casts {source.comparison_type} to {target.comparison_type}, keeping different values different"
|
|
279
|
+
return Result(True, why, (bound, value), premises)
|
|
280
|
+
return Result(False, "The comparison may coerce a side and lose what tells values apart", (bound, value), premises)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _widest_integer(typings: Sequence[ir.ValueTyping]) -> ir.ValueTyping | None:
|
|
284
|
+
"""The widest of `typings`, when each is a signed integer type: an integer
|
|
285
|
+
type is all that every engine promotes them to."""
|
|
286
|
+
if not typings or any(typing.integer is None for typing in typings):
|
|
287
|
+
return None
|
|
288
|
+
return max(typings, key=lambda typing: typing.integer or 0)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _string_literal(expression: ir.ScalarExpr) -> bool:
|
|
292
|
+
match expression.closed:
|
|
293
|
+
case ir.Constant(value=ir.LiteralValue(type="string")):
|
|
294
|
+
return True
|
|
295
|
+
case _:
|
|
296
|
+
return False
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def column_ref(column: ir.OutputColumn) -> ir.ColumnRef:
|
|
300
|
+
"""A reference to `column`, to ask `exact_comparison` of it."""
|
|
301
|
+
return ir.ColumnRef(origin=column.origin, column=column)
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
# Questions about one column's type -------------------------------------------
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _comparison_type(column: ir.OutputColumn) -> Result[str | None]:
|
|
308
|
+
typing = _column_typing(column)
|
|
309
|
+
return Result(None if typing.value is None else typing.value.comparison_type, "Comparison type", (column,), [typing])
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _identity_comparison(column: ir.OutputColumn) -> Result[bool]:
|
|
313
|
+
"""Whether equal values of `column` are identical."""
|
|
314
|
+
typing = _column_typing(column)
|
|
315
|
+
return Result(typing.value is not None and typing.value.identity_comparison, "Type compares by identity", (column,), [typing])
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _binary_text(column: ir.OutputColumn) -> Result[bool]:
|
|
319
|
+
"""Whether `column` is text compared by identity."""
|
|
320
|
+
typing = _column_typing(column)
|
|
321
|
+
return Result(typing.value is not None and typing.value.binary_text, "Text compared by identity", (column,), [typing])
|
|
322
|
+
|
|
323
|
+
|
|
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
|
+
def _boolean(column: ir.OutputColumn) -> bool:
|
|
331
|
+
typing = _column_typing(column).value
|
|
332
|
+
return typing is not None and typing.comparison_type == "BOOLEAN"
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _signed_integer(column: ir.OutputColumn) -> bool:
|
|
336
|
+
typing = _column_typing(column).value
|
|
337
|
+
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
|
|
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
|
|
|
@@ -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 =
|
|
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.
|
|
183
|
-
self._hazards = hazards(self.
|
|
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
|
|
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,
|
|
370
|
-
|
|
371
|
-
return
|
|
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:
|