sqlassert 0.3.1__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/__main__.py +2 -131
- sqlassert/check.py +98 -16
- sqlassert/diagnostics.py +31 -7
- sqlassert/dialects.py +504 -27
- sqlassert/discovery/bigquery.py +3 -1
- sqlassert/discovery/databricks.py +25 -2
- sqlassert/discovery/duckdb.py +61 -23
- sqlassert/discovery/fetcher.py +170 -45
- sqlassert/discovery/information_schema.py +34 -5
- sqlassert/discovery/mysql.py +22 -1
- sqlassert/discovery/postgres.py +28 -12
- sqlassert/discovery/redshift.py +3 -2
- sqlassert/discovery/snowflake.py +3 -0
- sqlassert/discovery/trino.py +2 -2
- sqlassert/edits.py +240 -0
- sqlassert/hazards.py +735 -0
- sqlassert/ir/__init__.py +6 -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 +247 -66
- sqlassert/ir/names.py +63 -0
- sqlassert/main.py +3 -9
- sqlassert/properties.py +12 -1
- sqlassert/provenance.py +5 -1
- sqlassert/python_engine.py +167 -50
- sqlassert/reporting.py +36 -32
- sqlassert/rewrites.py +1591 -0
- 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 +123 -26
- sqlassert/rules/equality.py +153 -85
- sqlassert/rules/exactly_one.py +42 -2
- sqlassert/rules/foreign_key.py +15 -13
- sqlassert/rules/join_cardinality.py +302 -39
- sqlassert/rules/nullability.py +244 -35
- sqlassert/rules/uniqueness.py +513 -86
- sqlassert/rules/value_typing.py +337 -0
- sqlassert/sql_parse.py +224 -90
- sqlassert/suggest.py +132 -57
- sqlassert-0.4.1.dist-info/METADATA +235 -0
- sqlassert-0.4.1.dist-info/RECORD +69 -0
- sqlassert-0.4.1.dist-info/entry_points.txt +2 -0
- sqlassert-0.4.1.dist-info/top_level.txt +2 -0
- sqlassert_cli.py +130 -0
- sqlassert/improvements.py +0 -528
- sqlassert/ir/convert.py +0 -2377
- sqlassert/smells.py +0 -306
- sqlassert-0.3.1.dist-info/METADATA +0 -725
- sqlassert-0.3.1.dist-info/RECORD +0 -44
- sqlassert-0.3.1.dist-info/entry_points.txt +0 -2
- sqlassert-0.3.1.dist-info/top_level.txt +0 -1
- {sqlassert-0.3.1.dist-info → sqlassert-0.4.1.dist-info}/WHEEL +0 -0
- {sqlassert-0.3.1.dist-info → sqlassert-0.4.1.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,572 @@
|
|
|
1
|
+
"""Scalar expressions: columns resolved through bindings, functions and
|
|
2
|
+
operators, comparisons, CASE, and the warnings an expression earns."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import re
|
|
7
|
+
from collections.abc import Callable, Iterable
|
|
8
|
+
from dataclasses import replace
|
|
9
|
+
from functools import cache
|
|
10
|
+
from typing import TYPE_CHECKING, assert_never
|
|
11
|
+
|
|
12
|
+
from sqlglot import Expr, exp
|
|
13
|
+
|
|
14
|
+
from sqlassert import diagnostics as diag
|
|
15
|
+
from sqlassert import ir
|
|
16
|
+
from sqlassert.diagnostics import Diagnostic, quoted
|
|
17
|
+
from sqlassert.properties import ExhaustiveCase, NonNullElements
|
|
18
|
+
from sqlassert.provenance import AttachmentSite, Origin
|
|
19
|
+
from sqlassert.sql_parse import exhaustive_span, literal_value, marker_position, written_sql
|
|
20
|
+
from sqlassert.ir.convert.builtins import dialect_builtins
|
|
21
|
+
from sqlassert.ir.convert.shared import (
|
|
22
|
+
_Binding, _source_line, _conjuncts, _TEXT_TYPES, _USING_QUALIFIER, _SCALAR_QUALIFIER, _schema_path, _Carried, _renamed, _row_number_window,
|
|
23
|
+
_NOT_A_FUNCTION_OF_ITS_COLUMNS, _select_label, _placed,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
if TYPE_CHECKING:
|
|
27
|
+
from sqlassert.ir.convert.parser import IrParser
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class _Expressions:
|
|
31
|
+
def _reads_renamed(self: IrParser, column: exp.Column, bindings: Iterable[_Binding], qualifier: str, schema: str, origin: Origin) -> bool:
|
|
32
|
+
"""Whether `column` may name a column the engine renamed, one of a
|
|
33
|
+
derived table that repeats a name (`_renamed`): it then binds nothing,
|
|
34
|
+
and warns, since which column it is depends on the engine. A name the
|
|
35
|
+
derived table repeats binds its first column, best effort (ADR 0008),
|
|
36
|
+
and warns too."""
|
|
37
|
+
if column.meta.get("star"):
|
|
38
|
+
return False # A star's expansion carries each column itself.
|
|
39
|
+
bindings = tuple(bindings)
|
|
40
|
+
name = column.name.lower()
|
|
41
|
+
at = origin if origin.line is not None else replace(origin, line=_source_line(column))
|
|
42
|
+
found = _renamed(bindings, qualifier, schema, name)
|
|
43
|
+
if found is None:
|
|
44
|
+
first = next((
|
|
45
|
+
binding for binding in bindings
|
|
46
|
+
if binding.name == name and name in binding.repeated and not binding.shadowed
|
|
47
|
+
and (not qualifier or (binding.qualifier == qualifier and (not schema or binding.schema == schema)))
|
|
48
|
+
), None)
|
|
49
|
+
if first is not None:
|
|
50
|
+
self._warnings.append(Diagnostic(
|
|
51
|
+
diag.AMBIGUOUS_DUPLICATE_COLUMN,
|
|
52
|
+
f"column {quoted(column.name)} is ambiguous: {first.qualifier} outputs the name {quoted(column.name)} more than once, "
|
|
53
|
+
"and sqlassert reads the first, as DuckDB does (another engine rejects the reference): "
|
|
54
|
+
"give the repeated columns distinct aliases",
|
|
55
|
+
at,
|
|
56
|
+
))
|
|
57
|
+
return False
|
|
58
|
+
table, repeated = found
|
|
59
|
+
self._warnings.append(Diagnostic(
|
|
60
|
+
diag.AMBIGUOUS_DUPLICATE_COLUMN,
|
|
61
|
+
f"column {quoted(column.name)} may be one the engine renamed: {table} outputs the name {quoted(repeated)} more than once, "
|
|
62
|
+
f"and DuckDB names the repeats {quoted(repeated + '_1')}, {quoted(repeated + '_2')}, ... (another engine rejects them or names them otherwise), "
|
|
63
|
+
"so which column it reads depends on the engine: give the repeated columns distinct aliases",
|
|
64
|
+
at,
|
|
65
|
+
))
|
|
66
|
+
return True
|
|
67
|
+
|
|
68
|
+
def _lower_expression(
|
|
69
|
+
self: IrParser, expression: Expr, bindings: tuple[_Binding, ...], *, schema_complete: bool = False, line: int | None = None
|
|
70
|
+
) -> ir.ScalarExpr:
|
|
71
|
+
"""An unqualified column resolves by name across several sources only
|
|
72
|
+
when every source's schema is complete: otherwise the one visible match
|
|
73
|
+
might be shadowed by a column of a source whose columns are unknown.
|
|
74
|
+
|
|
75
|
+
A Builtin becomes a Call; any other function or operator an
|
|
76
|
+
OpaquePureFunction of its lowered arguments, unless its value is not a
|
|
77
|
+
function of them (`_NOT_A_FUNCTION_OF_ITS_COLUMNS`)."""
|
|
78
|
+
origin = self._origin(expression, line)
|
|
79
|
+
if (grouped := self._grouped_values.get(id(expression))) is not None:
|
|
80
|
+
return grouped
|
|
81
|
+
|
|
82
|
+
def lower(node: Expr) -> ir.ScalarExpr:
|
|
83
|
+
return self._lower_expression(node, bindings, schema_complete=schema_complete)
|
|
84
|
+
|
|
85
|
+
if isinstance(expression, exp.Case | exp.If) and id(expression) not in self._mixed_checked:
|
|
86
|
+
self._mixed_checked.add(id(expression))
|
|
87
|
+
self._mixed_results(expression, lower)
|
|
88
|
+
if isinstance(expression, exp.Subquery) and id(expression) in self._scalar_values:
|
|
89
|
+
qualifier = self._scalar_values[id(expression)]
|
|
90
|
+
value = next((binding.column for binding in bindings if binding.qualifier == qualifier), None)
|
|
91
|
+
if value is not None:
|
|
92
|
+
return ir.ColumnRef(origin=origin, column=value)
|
|
93
|
+
if id(expression) in self._set_returning_values:
|
|
94
|
+
qualifier = self._set_returning_values[id(expression)]
|
|
95
|
+
value = next((binding.column for binding in bindings if binding.qualifier == qualifier), None)
|
|
96
|
+
if value is not None:
|
|
97
|
+
return ir.ColumnRef(origin=origin, column=value)
|
|
98
|
+
if isinstance(expression, exp.Column) and id(expression) in self._scoped_columns:
|
|
99
|
+
column = self._scoped_columns[id(expression)]
|
|
100
|
+
if any(binding.column is column for binding in bindings):
|
|
101
|
+
return ir.ColumnRef(origin=origin, column=column)
|
|
102
|
+
if isinstance(expression, exp.Column) and isinstance(carried := expression.meta.get("star"), _Carried):
|
|
103
|
+
if any(binding.column is carried.column for binding in bindings):
|
|
104
|
+
return ir.ColumnRef(origin=origin, column=carried.column)
|
|
105
|
+
if isinstance(expression, exp.Column):
|
|
106
|
+
if expression.table:
|
|
107
|
+
schema = _schema_path(expression)
|
|
108
|
+
matches = [
|
|
109
|
+
binding for binding in bindings
|
|
110
|
+
if binding.qualifier == expression.table.lower() and binding.name == expression.name.lower() and (not schema or binding.schema == schema)
|
|
111
|
+
]
|
|
112
|
+
if self._reads_renamed(expression, bindings, expression.table.lower(), schema, origin):
|
|
113
|
+
matches = []
|
|
114
|
+
elif schema_complete or len({
|
|
115
|
+
binding.qualifier for binding in bindings if not binding.qualifier.startswith((_SCALAR_QUALIFIER, _USING_QUALIFIER))
|
|
116
|
+
}) == 1:
|
|
117
|
+
matches = [binding for binding in bindings if binding.name == expression.name.lower() and not binding.shadowed]
|
|
118
|
+
if self._reads_renamed(expression, bindings, "", "", origin):
|
|
119
|
+
matches = []
|
|
120
|
+
else:
|
|
121
|
+
matches = []
|
|
122
|
+
sources = ", ".join(dict.fromkeys(binding.qualifier for binding in bindings))
|
|
123
|
+
self._warnings.append(Diagnostic(
|
|
124
|
+
diag.AMBIGUOUS_COLUMN,
|
|
125
|
+
f"column {quoted(expression.name)} is unqualified and more than one source may own it ({sources}), "
|
|
126
|
+
"since some have no declared columns: qualify it, declare those tables with CREATE TABLE, "
|
|
127
|
+
"or analyze with a database connection (analyze_database)",
|
|
128
|
+
origin if origin.line is not None else replace(origin, line=_source_line(expression)),
|
|
129
|
+
))
|
|
130
|
+
if len(matches) == 1:
|
|
131
|
+
return ir.ColumnRef(origin=origin, column=matches[0].column)
|
|
132
|
+
return ir.OpaqueExpression(origin=origin, description=expression.sql(dialect=self.dialect))
|
|
133
|
+
if isinstance(expression, _COMPARISONS):
|
|
134
|
+
self._check_zoned_text(expression, lower, self._origin(expression, line or _source_line(expression)))
|
|
135
|
+
description = expression.sql(dialect=self.dialect)
|
|
136
|
+
quantified = isinstance(expression, exp.Binary) and any(
|
|
137
|
+
isinstance(operand, (exp.Any, exp.All)) for operand in (expression.this, expression.expression)
|
|
138
|
+
) # `n > ANY (...)` is FALSE over no rows, even for a NULL `n`.
|
|
139
|
+
match expression:
|
|
140
|
+
case exp.Paren():
|
|
141
|
+
return self._lower_expression(expression.this, bindings, schema_complete=schema_complete, line=line)
|
|
142
|
+
case exp.Collate():
|
|
143
|
+
return ir.OpaqueExpression(origin=origin, description=description) # `parse` warns.
|
|
144
|
+
case exp.Null():
|
|
145
|
+
return ir.NullLiteral(origin=origin)
|
|
146
|
+
case exp.Count():
|
|
147
|
+
return ir.Count(origin=origin, description=description)
|
|
148
|
+
case exp.Coalesce():
|
|
149
|
+
return ir.Coalesce(origin=origin, arguments=tuple(lower(argument) for argument in (expression.this, *expression.expressions)))
|
|
150
|
+
case exp.Case() if expression.this is not None:
|
|
151
|
+
return self._lower_case(expression, bindings, schema_complete=schema_complete)
|
|
152
|
+
case exp.And():
|
|
153
|
+
return self._lower_condition(expression, _conjuncts(expression), bindings, schema_complete=schema_complete)
|
|
154
|
+
case exp.Or():
|
|
155
|
+
return ir.Or(origin=origin, parts=tuple(
|
|
156
|
+
self._lower_condition(branch, _conjuncts(branch), bindings, schema_complete=schema_complete)
|
|
157
|
+
for branch in _disjuncts(expression)
|
|
158
|
+
))
|
|
159
|
+
case exp.EQ() if not quantified:
|
|
160
|
+
return ir.Equality(
|
|
161
|
+
origin=origin, left=lower(expression.this), right=lower(expression.expression),
|
|
162
|
+
total=self._checked_comparison(expression, lower),
|
|
163
|
+
)
|
|
164
|
+
case exp.NullSafeEQ() if not quantified:
|
|
165
|
+
return ir.NullSafeEquality(
|
|
166
|
+
origin=origin, left=lower(expression.this), right=lower(expression.expression),
|
|
167
|
+
rejects=self._checked_comparison(expression, lower),
|
|
168
|
+
)
|
|
169
|
+
case exp.NullSafeNEQ() if not quantified:
|
|
170
|
+
return ir.Call(origin=origin, function=_IS_DISTINCT_FROM, arguments=(lower(expression.this), lower(expression.expression)), description=description)
|
|
171
|
+
case exp.EQ() | exp.NEQ() | exp.GT() | exp.GTE() | exp.LT() | exp.LTE() if isinstance(expression.expression, exp.Any) and not isinstance(expression.this, (exp.Any, exp.All)):
|
|
172
|
+
function = _any_comparison(type(expression))
|
|
173
|
+
arguments = (lower(expression.this), lower(expression.expression))
|
|
174
|
+
return ir.Call(origin=origin, function=function, arguments=arguments, description=description)
|
|
175
|
+
case exp.Exists():
|
|
176
|
+
subquery = ir.OpaqueExpression(origin=origin, description=description)
|
|
177
|
+
return ir.Call(origin=origin, function=_EXISTS, arguments=(subquery,), description=description)
|
|
178
|
+
case exp.Is(expression=exp.Null()):
|
|
179
|
+
return ir.IsNull(origin=origin, operand=lower(expression.this))
|
|
180
|
+
case exp.Is(expression=exp.Boolean() as truth):
|
|
181
|
+
function = _IS_TRUE if truth.this else _IS_FALSE
|
|
182
|
+
return ir.Call(origin=origin, function=function, arguments=(lower(expression.this),), description=description)
|
|
183
|
+
case exp.Not(this=exp.Is(expression=exp.Null()) as test):
|
|
184
|
+
return ir.IsNotNull(origin=origin, operand=lower(test.this))
|
|
185
|
+
case exp.In() if expression.expressions and not any(expression.args.get(key) for key in ("query", "unnest", "field")):
|
|
186
|
+
return ir.InList(origin=origin, operand=lower(expression.this), values=tuple(lower(value) for value in expression.expressions))
|
|
187
|
+
case _:
|
|
188
|
+
pass
|
|
189
|
+
value = literal_value(expression) or _cast_integer_literal(expression)
|
|
190
|
+
if value == ir.LiteralValue(type="string", text="") and self.semantics.empty_string_is_null:
|
|
191
|
+
return ir.NullLiteral(origin=origin)
|
|
192
|
+
if value is not None or isinstance(expression, exp.Literal):
|
|
193
|
+
return self._constant(origin, value)
|
|
194
|
+
builtin = dialect_builtins(self.semantics).get(type(expression))
|
|
195
|
+
if builtin is not None and not quantified:
|
|
196
|
+
function, keys = builtin
|
|
197
|
+
if type(expression) is exp.Cast and function.total is not None and self._is_json(expression.this, lower):
|
|
198
|
+
# `CAST(JSON 'null' AS BIGINT)` is NULL.
|
|
199
|
+
function = replace(function, total=None)
|
|
200
|
+
values = [value for key in keys for value in _as_list(expression.args[key])]
|
|
201
|
+
# `trim(x, chars)` and `floor(x, 2)` read more than their Builtin's arguments.
|
|
202
|
+
extra = type(expression) in _ONE_ARGUMENT_BUILTINS and any(
|
|
203
|
+
value for key, value in expression.args.items() if key not in keys
|
|
204
|
+
)
|
|
205
|
+
if function.accepts(len(values)) and not extra:
|
|
206
|
+
arguments = tuple(lower(value) for value in values)
|
|
207
|
+
if (
|
|
208
|
+
type(expression) is exp.Like and self.semantics.text_is_binary
|
|
209
|
+
and isinstance(arguments[1], ir.Constant)
|
|
210
|
+
and (pattern := arguments[1].value) is not None and pattern.type == "string"
|
|
211
|
+
and not any(character in pattern.text for character in "%_\\")
|
|
212
|
+
and expression.find_ancestor(exp.Escape) is None
|
|
213
|
+
and (kind := self._declared_type(arguments[0], through_sets=False)) is not None
|
|
214
|
+
and kind.this in _TEXT_TYPES
|
|
215
|
+
):
|
|
216
|
+
return ir.Equality(origin=origin, left=arguments[0], right=arguments[1], total=True)
|
|
217
|
+
composites = [
|
|
218
|
+
(value, argument) for value, argument in zip(values, arguments)
|
|
219
|
+
if function.name in _ORDER_COMPARISONS and function.total is not None and self._is_composite(value, lower)
|
|
220
|
+
]
|
|
221
|
+
if composites:
|
|
222
|
+
function, arguments = self._composite_comparison(expression, function, arguments, composites, self._origin(expression, line or _source_line(expression)))
|
|
223
|
+
call = ir.Call(origin=origin, function=function, arguments=arguments, description=description)
|
|
224
|
+
if type(expression) is exp.Cast:
|
|
225
|
+
return replace(call, typing=self._cast_typing(expression))
|
|
226
|
+
return self._typed_call(expression, replace(call, typing=self._fixed_typing(expression), typed_by=self._argument_typing(expression, values)))
|
|
227
|
+
if isinstance(expression, _NOT_A_FUNCTION_OF_ITS_COLUMNS):
|
|
228
|
+
# A function SQLGlot does not know has the type the dialect gives it, if any.
|
|
229
|
+
opaque = ir.OpaqueExpression(origin=origin, description=description, typing=self._fixed_typing(expression) if isinstance(expression, exp.Anonymous) else None)
|
|
230
|
+
if isinstance(expression, exp.Anonymous):
|
|
231
|
+
self._typed_call(expression, opaque)
|
|
232
|
+
if isinstance(expression, exp.Window):
|
|
233
|
+
if _row_number_window(expression) is not None:
|
|
234
|
+
# An integer type in every engine, whichever (docs/dialects.md).
|
|
235
|
+
opaque = replace(opaque, typing=self._declared_typing(exp.DataType.build("BIGINT", dialect=self.dialect)))
|
|
236
|
+
self._unsupported.append((opaque, "a window function (other than a row_number() select item or QUALIFY row_number() ... = 1)"))
|
|
237
|
+
return opaque
|
|
238
|
+
if isinstance(expression, exp.Case) or isinstance(expression, exp.If):
|
|
239
|
+
# A searched CASE (a simple one is a SimpleCase) or IF: conditions and results, flat.
|
|
240
|
+
parts = _selection_parts(expression)
|
|
241
|
+
return ir.OpaquePureFunction(
|
|
242
|
+
origin=origin, arguments=tuple(lower(part) for part, _ in parts), description=description,
|
|
243
|
+
results=tuple(index for index, (_, is_result) in enumerate(parts) if is_result),
|
|
244
|
+
)
|
|
245
|
+
children = list(expression.iter_expressions())
|
|
246
|
+
opaque_call = ir.OpaquePureFunction(origin=origin, arguments=tuple(lower(child) for child in children), description=description)
|
|
247
|
+
if isinstance(expression, exp.Cast):
|
|
248
|
+
return replace(opaque_call, typing=self._cast_typing(expression)) # TRY_CAST.
|
|
249
|
+
return self._typed_call(expression, replace(opaque_call, typing=self._fixed_typing(expression), typed_by=self._argument_typing(expression, children)))
|
|
250
|
+
|
|
251
|
+
def _typed_call[T: ir.Call | ir.OpaquePureFunction | ir.OpaqueExpression](self: IrParser, expression: Expr, call: T) -> T:
|
|
252
|
+
"""`call`, warning `unknown-function` once when it is a function call
|
|
253
|
+
whose result type sqlassert does not know for the dialect: neither one
|
|
254
|
+
the dialect fixes (`_result_type`) nor one that follows an argument's
|
|
255
|
+
(`_argument_typing`). Its value then has no known type, so an equality
|
|
256
|
+
over it binds nothing; the warning names the gap where it is written,
|
|
257
|
+
not as an unknown type further down. Operators, CASE, NULLIF and
|
|
258
|
+
arithmetic are typed by their operands (`rules/value_typing.py`) and
|
|
259
|
+
are not function calls here."""
|
|
260
|
+
untyped = call.typing is None and getattr(call, "typed_by", None) is None
|
|
261
|
+
if not untyped or not isinstance(expression, exp.Func) or isinstance(expression, _OPERAND_TYPED) or id(expression) in self._untyped_calls:
|
|
262
|
+
return call
|
|
263
|
+
self._untyped_calls.add(id(expression))
|
|
264
|
+
name = expression.name if isinstance(expression, exp.Anonymous) else expression.sql_name()
|
|
265
|
+
self._warnings.append(Diagnostic(
|
|
266
|
+
diag.UNKNOWN_FUNCTION,
|
|
267
|
+
f"{name.lower()}() has no result type sqlassert knows in {self.dialect}, so its value has no known type and "
|
|
268
|
+
"an equality on it proves nothing; CAST it to the type it returns",
|
|
269
|
+
_placed(call.origin, expression),
|
|
270
|
+
))
|
|
271
|
+
return call
|
|
272
|
+
|
|
273
|
+
def _checked_comparison(self: IrParser, comparison: exp.Binary, lower: Callable[[Expr], ir.ScalarExpr]) -> bool:
|
|
274
|
+
"""Whether `comparison` compares its operands' values as they are:
|
|
275
|
+
where a failed implicit cast raises, and neither is a composite, which
|
|
276
|
+
may hold a NULL element."""
|
|
277
|
+
return self.semantics.casts_raise and not any(
|
|
278
|
+
self._is_composite(operand, lower) for operand in (comparison.this, comparison.expression)
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
def _check_zoned_text(self: IrParser, comparison: Expr, lower: Callable[[Expr], ir.ScalarExpr], origin: Origin) -> None:
|
|
282
|
+
"""Warn of a comparison with a CAST of a zoned timestamp, where it keeps
|
|
283
|
+
its zone: equal instants cast to different text (or dates, or local
|
|
284
|
+
times), so the comparison depends on the zone each value was given."""
|
|
285
|
+
if self.semantics.zoned_timestamp_is_instant or id(comparison) in self._zone_checked:
|
|
286
|
+
return
|
|
287
|
+
self._zone_checked.add(id(comparison))
|
|
288
|
+
operands = [comparison.this, *_as_list(comparison.args.get("expression") or []), *comparison.expressions]
|
|
289
|
+
operands += [comparison.args[key] for key in ("low", "high") if comparison.args.get(key) is not None]
|
|
290
|
+
for operand in operands:
|
|
291
|
+
while isinstance(operand, exp.Paren):
|
|
292
|
+
operand = operand.this
|
|
293
|
+
if not isinstance(operand, exp.Cast) or operand.to.this in _ZONED_TYPES or not isinstance(operand.this, exp.Column):
|
|
294
|
+
continue
|
|
295
|
+
kind = self._declared_type(lower(operand.this))
|
|
296
|
+
if kind is None or kind.this not in _ZONED_TYPES:
|
|
297
|
+
continue
|
|
298
|
+
cast = operand.sql(dialect=self.dialect)
|
|
299
|
+
self._warnings.append(Diagnostic(
|
|
300
|
+
diag.ZONED_TIMESTAMP_CAST,
|
|
301
|
+
f"{cast} is compared, but a {kind.sql(dialect=self.dialect)} keeps the zone it was given in {self.dialect}, "
|
|
302
|
+
"so equal instants cast to different values and the comparison depends on each value's zone: "
|
|
303
|
+
"compare the timestamps themselves, or convert to one zone first (AT TIME ZONE 'UTC')",
|
|
304
|
+
origin,
|
|
305
|
+
))
|
|
306
|
+
|
|
307
|
+
def _composite_comparison(
|
|
308
|
+
self: IrParser, comparison: Expr, function: ir.Builtin, arguments: tuple[ir.ScalarExpr, ...],
|
|
309
|
+
composites: list[tuple[Expr, ir.ScalarExpr]], origin: Origin,
|
|
310
|
+
) -> tuple[ir.Builtin, tuple[ir.ScalarExpr, ...]]:
|
|
311
|
+
"""A comparison of composites (ARRAYs, ROWs, MAPs), non-null only when
|
|
312
|
+
no element is NULL either: `ARRAY[1, NULL] <> ARRAY[1, NULL]` is NULL in
|
|
313
|
+
Trino. So it also takes each composite operand's Elements, as a
|
|
314
|
+
non-strict, total argument. A composite column or CAST, whose elements
|
|
315
|
+
the SQL does not show, is noted for a warning."""
|
|
316
|
+
assert function.total is not None
|
|
317
|
+
extra = len(composites)
|
|
318
|
+
widened = ir.Builtin(
|
|
319
|
+
name=function.name, strict=function.strict + (False,) * extra, total=function.total + (True,) * extra, injective=False,
|
|
320
|
+
)
|
|
321
|
+
elements = tuple(ir.Elements(origin=argument.origin, operand=argument) for _, argument in composites)
|
|
322
|
+
for value, argument in composites:
|
|
323
|
+
while isinstance(value, exp.Paren):
|
|
324
|
+
value = value.this
|
|
325
|
+
if isinstance(value, (exp.Column, exp.Cast)) and id(value) not in self._composite_comparisons:
|
|
326
|
+
self._composite_comparisons[id(value)] = (origin, comparison.sql(dialect=self.dialect), value.sql(dialect=self.dialect), argument)
|
|
327
|
+
return widened, arguments + elements
|
|
328
|
+
|
|
329
|
+
def _composite_warnings(self: IrParser) -> list[Diagnostic]:
|
|
330
|
+
"""A warning for each composite operand whose elements no NOT NULL
|
|
331
|
+
ELEMENTS declaration covers, on it or on a column it passes on from."""
|
|
332
|
+
declared = {column for item in self._declarations if isinstance(item, NonNullElements) for column in item.columns}
|
|
333
|
+
warnings = []
|
|
334
|
+
for origin, comparison, operand, argument in self._composite_comparisons.values():
|
|
335
|
+
expression, covered = argument, False
|
|
336
|
+
while isinstance(expression, ir.ColumnRef) and not covered:
|
|
337
|
+
covered = expression.column in declared
|
|
338
|
+
expression = expression.column.scalar_expr
|
|
339
|
+
if not covered:
|
|
340
|
+
warnings.append(Diagnostic(
|
|
341
|
+
diag.COMPOSITE_COMPARISON,
|
|
342
|
+
f"{comparison} compares {operand}, which may hold a NULL element, and a comparison of composites with "
|
|
343
|
+
"a NULL element may be NULL (it is in Trino), so it is not taken to be non-null: if its elements are "
|
|
344
|
+
"never NULL, say so with /**DECLARE NOT NULL ELEMENTS(...)**/ on a Select Expression that outputs it",
|
|
345
|
+
origin,
|
|
346
|
+
))
|
|
347
|
+
return warnings
|
|
348
|
+
|
|
349
|
+
def _is_composite(self: IrParser, node: Expr, lower: Callable[[Expr], ir.ScalarExpr]) -> bool:
|
|
350
|
+
"""Whether the operand may be composite, including unknown column types."""
|
|
351
|
+
match node:
|
|
352
|
+
case exp.Paren() | exp.Nullif():
|
|
353
|
+
return self._is_composite(node.this, lower)
|
|
354
|
+
case exp.Cast():
|
|
355
|
+
return node.to.this in _COMPOSITE_TYPES
|
|
356
|
+
case exp.Column():
|
|
357
|
+
kind = self._declared_type(lower(node))
|
|
358
|
+
return self.dialect in {"trino", "postgres"} if kind is None else kind.this in _COMPOSITE_TYPES
|
|
359
|
+
case exp.Array() | exp.Struct() | exp.Map() | exp.VarMap():
|
|
360
|
+
return True
|
|
361
|
+
case exp.Coalesce():
|
|
362
|
+
return any(self._is_composite(each, lower) for each in (node.this, *node.expressions))
|
|
363
|
+
case exp.Case():
|
|
364
|
+
arms = [arm.args["true"] for arm in node.args.get("ifs") or ()]
|
|
365
|
+
default = node.args.get("default")
|
|
366
|
+
return any(self._is_composite(each, lower) for each in (*arms, *([default] if default is not None else [])))
|
|
367
|
+
case exp.If():
|
|
368
|
+
false = node.args.get("false")
|
|
369
|
+
return any(self._is_composite(each, lower) for each in (node.args["true"], *([false] if false is not None else [])))
|
|
370
|
+
case _:
|
|
371
|
+
return False
|
|
372
|
+
|
|
373
|
+
def _is_json(self: IrParser, node: Expr, lower: Callable[[Expr], ir.ScalarExpr]) -> bool:
|
|
374
|
+
"""Whether the operand may be JSON or VARIANT, whose null can cast to SQL NULL."""
|
|
375
|
+
match node:
|
|
376
|
+
case exp.Paren() | exp.Nullif():
|
|
377
|
+
return self._is_json(node.this, lower)
|
|
378
|
+
case exp.Cast():
|
|
379
|
+
return node.to.this in _JSON_TYPES
|
|
380
|
+
case exp.Column():
|
|
381
|
+
kind = self._declared_type(lower(node))
|
|
382
|
+
return kind is None or kind.this in _JSON_TYPES
|
|
383
|
+
case exp.ParseJSON() | exp.JSONExtract() | exp.JSONBExtract() | exp.JSONObject() | exp.JSONArray() | exp.JSONObjectAgg() | exp.JSONArrayAgg():
|
|
384
|
+
return True
|
|
385
|
+
case exp.Coalesce():
|
|
386
|
+
return any(self._is_json(each, lower) for each in (node.this, *node.expressions))
|
|
387
|
+
case exp.Case():
|
|
388
|
+
arms = [arm.args["true"] for arm in node.args.get("ifs") or ()]
|
|
389
|
+
default = node.args.get("default")
|
|
390
|
+
return any(self._is_json(each, lower) for each in (*arms, *([default] if default is not None else [])))
|
|
391
|
+
case exp.If():
|
|
392
|
+
false = node.args.get("false")
|
|
393
|
+
return any(self._is_json(each, lower) for each in (node.args["true"], *([false] if false is not None else [])))
|
|
394
|
+
case _:
|
|
395
|
+
return False
|
|
396
|
+
|
|
397
|
+
def _mixed_results(self: IrParser, expression: exp.Case | exp.If, lower: Callable[[Expr], ir.ScalarExpr]) -> None:
|
|
398
|
+
"""Read the results of a CASE or IF (the values it may return, no
|
|
399
|
+
condition) for a Hazard: when they have different declared types the
|
|
400
|
+
engine casts them to a common type (or rejects the query), and a cast
|
|
401
|
+
may lose what told values apart (`'01'` and `'1'` both become 1, a
|
|
402
|
+
large BIGINT a rounded DOUBLE). Integer types only widen, so they mix
|
|
403
|
+
safely. A result whose type is not known is left out, never guessed.
|
|
404
|
+
The type of the CASE itself is the type its results share
|
|
405
|
+
(`rules/value_typing.py`)."""
|
|
406
|
+
kinds: dict[str, str] = {}
|
|
407
|
+
for result in _result_expressions(expression):
|
|
408
|
+
while isinstance(result, exp.Paren):
|
|
409
|
+
result = result.this
|
|
410
|
+
kind: exp.DataType | None = None
|
|
411
|
+
match result:
|
|
412
|
+
case None | exp.Null():
|
|
413
|
+
continue # Takes the type of the other results.
|
|
414
|
+
case exp.Column():
|
|
415
|
+
kind = self._declared_type(lower(result))
|
|
416
|
+
case exp.Cast():
|
|
417
|
+
kind = result.to
|
|
418
|
+
case exp.Literal(is_string=True):
|
|
419
|
+
kinds.setdefault("text", "a text literal")
|
|
420
|
+
case _:
|
|
421
|
+
pass
|
|
422
|
+
if kind is None:
|
|
423
|
+
continue
|
|
424
|
+
family = "integer" if kind.this in exp.DataType.INTEGER_TYPES else "text" if kind.this in exp.DataType.TEXT_TYPES else kind.this.name
|
|
425
|
+
kinds.setdefault(family, kind.sql(dialect=self.dialect))
|
|
426
|
+
select = expression.find_ancestor(exp.Select)
|
|
427
|
+
if len(kinds) < 2 or select is None or (position := marker_position(select)) is None:
|
|
428
|
+
return
|
|
429
|
+
offset, line = position
|
|
430
|
+
self._mixed_cases.append((
|
|
431
|
+
AttachmentSite(_select_label(select), line, offset, True),
|
|
432
|
+
f"{written_sql(expression, self.dialect)} mixes {' and '.join(kinds.values())}",
|
|
433
|
+
))
|
|
434
|
+
|
|
435
|
+
def _lower_case(self: IrParser, case: exp.Case, bindings: tuple[_Binding, ...], *, schema_complete: bool) -> ir.SimpleCase:
|
|
436
|
+
"""A simple CASE, and the assertion its marker states, once per CASE."""
|
|
437
|
+
|
|
438
|
+
def lower(expression: Expr) -> ir.ScalarExpr:
|
|
439
|
+
return self._lower_expression(expression, bindings, schema_complete=schema_complete)
|
|
440
|
+
|
|
441
|
+
arms = case.args.get("ifs") or ()
|
|
442
|
+
default = case.args.get("default")
|
|
443
|
+
origin = self._placed(case)
|
|
444
|
+
lowered = ir.SimpleCase(
|
|
445
|
+
origin=origin,
|
|
446
|
+
operand=lower(case.this),
|
|
447
|
+
whens=tuple(lower(arm.this) for arm in arms),
|
|
448
|
+
thens=tuple(lower(arm.args["true"]) for arm in arms),
|
|
449
|
+
# A missing ELSE shares the CASE's origin, which marks it missing.
|
|
450
|
+
default=lower(default) if default is not None else ir.NullLiteral(origin=origin),
|
|
451
|
+
)
|
|
452
|
+
if id(case) not in self._sited_cases:
|
|
453
|
+
self._sited_cases.add(id(case))
|
|
454
|
+
self._add_attachment_site(case, f"CASE {case.this.sql(dialect=self.dialect)}", lowered)
|
|
455
|
+
span = exhaustive_span(case)
|
|
456
|
+
if span is not None and id(case) not in self._handled_cases:
|
|
457
|
+
self._handled_cases.add(id(case))
|
|
458
|
+
origin = Origin.marked(case.sql(dialect=self.dialect), span)
|
|
459
|
+
self._assertions.append(ir.Assertion(origin=origin, property=ExhaustiveCase(case=lowered)))
|
|
460
|
+
return lowered
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _as_list(value: Expr | list[Expr]) -> list[Expr]:
|
|
464
|
+
return value if isinstance(value, list) else [value]
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
def _disjuncts(predicate: Expr) -> list[Expr]:
|
|
468
|
+
"""The operands of a predicate's top-level ORs, parentheses removed."""
|
|
469
|
+
while isinstance(predicate, exp.Paren):
|
|
470
|
+
predicate = predicate.this
|
|
471
|
+
if isinstance(predicate, exp.Or):
|
|
472
|
+
return _disjuncts(predicate.this) + _disjuncts(predicate.expression)
|
|
473
|
+
return [predicate]
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def _selection_parts(expression: exp.Case | exp.If) -> list[tuple[Expr, bool]]:
|
|
477
|
+
"""The expressions a searched CASE or an IF reads, in order, each with
|
|
478
|
+
whether it is a value the expression may return (not a condition)."""
|
|
479
|
+
match expression:
|
|
480
|
+
case exp.Case():
|
|
481
|
+
parts: list[tuple[Expr, bool]] = []
|
|
482
|
+
for arm in expression.args.get("ifs") or ():
|
|
483
|
+
parts.extend([(arm.this, False), (arm.args["true"], True)])
|
|
484
|
+
default = expression.args.get("default")
|
|
485
|
+
return [*parts, *([(default, True)] if default is not None else [])]
|
|
486
|
+
case exp.If():
|
|
487
|
+
false = expression.args.get("false")
|
|
488
|
+
return [(expression.this, False), (expression.args["true"], True), *([(false, True)] if false is not None else [])]
|
|
489
|
+
case _:
|
|
490
|
+
assert_never(expression)
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def _result_expressions(expression: exp.Case | exp.If | exp.Coalesce | exp.Nullif) -> list[Expr | None]:
|
|
494
|
+
"""The values `expression` may return (None: an absent ELSE, a NULL), not its conditions."""
|
|
495
|
+
match expression:
|
|
496
|
+
case exp.Case():
|
|
497
|
+
return [*(arm.args["true"] for arm in expression.args.get("ifs") or ()), expression.args.get("default")]
|
|
498
|
+
case exp.If():
|
|
499
|
+
return [expression.args.get("true"), expression.args.get("false")]
|
|
500
|
+
case exp.Coalesce():
|
|
501
|
+
return [expression.this, *expression.expressions]
|
|
502
|
+
case exp.Nullif():
|
|
503
|
+
return [expression.this, expression.expression]
|
|
504
|
+
case _:
|
|
505
|
+
assert_never(expression)
|
|
506
|
+
# TIMESTAMPTZ is too, where it holds an instant only (`zoned_timestamp_is_instant`).
|
|
507
|
+
|
|
508
|
+
# Types whose values keep the zone they were given, where a TIMESTAMP WITH
|
|
509
|
+
# TIME ZONE is not an instant only: a CAST to another type reads that zone.
|
|
510
|
+
_ZONED_TYPES = {exp.DataType.Type.TIMESTAMPTZ, exp.DataType.Type.TIMETZ}
|
|
511
|
+
|
|
512
|
+
# Types whose `null` (JSON's, a VARIANT's) is a non-null value that a CAST turns into NULL.
|
|
513
|
+
_JSON_TYPES = {exp.DataType.Type.JSON, exp.DataType.Type.JSONB, exp.DataType.Type.VARIANT, exp.DataType.Type.OBJECT}
|
|
514
|
+
|
|
515
|
+
# Composite types: a comparison of their values may be NULL for a NULL element.
|
|
516
|
+
_COMPOSITE_TYPES = {exp.DataType.Type.ARRAY, exp.DataType.Type.LIST, exp.DataType.Type.STRUCT, exp.DataType.Type.MAP, exp.DataType.Type.NESTED}
|
|
517
|
+
|
|
518
|
+
# The Builtins that compare two values, which compare composites element by element.
|
|
519
|
+
# Never NULL, in every dialect: a NULL operand is a value they compare.
|
|
520
|
+
_IS_DISTINCT_FROM = ir.Builtin(name="IS DISTINCT FROM", strict=(False, False), total=(False, False), injective=False)
|
|
521
|
+
# Never NULL: TRUE or FALSE, whatever its subquery returns.
|
|
522
|
+
_EXISTS = ir.Builtin(name="EXISTS", strict=(False,), total=(False,), injective=False)
|
|
523
|
+
_ORDER_COMPARISONS = {"<>", ">", ">=", "<", "<=", "BETWEEN"}
|
|
524
|
+
# Never NULL: `NULL IS TRUE` is FALSE, so never TRUE where the operand is NULL.
|
|
525
|
+
_IS_TRUE = ir.Builtin(name="IS TRUE", strict=(False,), total=(False,), injective=False, true_only_if_argument=True)
|
|
526
|
+
_IS_FALSE = ir.Builtin(name="IS FALSE", strict=(False,), total=(False,), injective=False, rejecting=(True,))
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
@cache
|
|
530
|
+
def _any_comparison(node: type[Expr]) -> ir.Builtin:
|
|
531
|
+
"""`x op ANY (...)`, in every dialect: FALSE over no values, even for a
|
|
532
|
+
NULL `x`, else NULL where `x` is, so never TRUE where `x` is NULL. Not
|
|
533
|
+
`ALL`, which is TRUE over no values."""
|
|
534
|
+
names: dict[type[Expr], str] = {exp.EQ: "=", exp.NEQ: "<>", exp.GT: ">", exp.GTE: ">=", exp.LT: "<", exp.LTE: "<="}
|
|
535
|
+
name = names[node]
|
|
536
|
+
return ir.Builtin(name=f"{name} ANY", strict=(False, False), total=None, injective=False, rejecting=(True, False))
|
|
537
|
+
|
|
538
|
+
# Comparisons, whose operands a zoned timestamp's text may be.
|
|
539
|
+
_COMPARISONS = (exp.EQ, exp.NEQ, exp.GT, exp.GTE, exp.LT, exp.LTE, exp.NullSafeEQ, exp.NullSafeNEQ, exp.In, exp.Like, exp.ILike, exp.Between)
|
|
540
|
+
|
|
541
|
+
# The largest value of each signed integer type, the same in every dialect.
|
|
542
|
+
_INTEGER_MAXIMA = {
|
|
543
|
+
exp.DataType.Type.TINYINT: 2**7 - 1, exp.DataType.Type.SMALLINT: 2**15 - 1,
|
|
544
|
+
exp.DataType.Type.INT: 2**31 - 1, exp.DataType.Type.BIGINT: 2**63 - 1,
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def _cast_integer_literal(expression: Expr) -> ir.LiteralValue | None:
|
|
549
|
+
"""The value of `CAST('1' AS INTEGER)` or `CAST(1 AS BIGINT)`: a
|
|
550
|
+
non-negative integer, written as a number or a string with no sign,
|
|
551
|
+
leading zero or space, within a signed integer type's range. That is the
|
|
552
|
+
same integer in every dialect; a decimal (`CAST('1.5' AS INTEGER)` rounds
|
|
553
|
+
or truncates by dialect) or any other cast is not folded."""
|
|
554
|
+
if type(expression) is not exp.Cast: # TRY_CAST and the like are not modelled
|
|
555
|
+
return None
|
|
556
|
+
to = expression.args.get("to")
|
|
557
|
+
maximum = _INTEGER_MAXIMA.get(to.this) if isinstance(to, exp.DataType) else None
|
|
558
|
+
value = literal_value(expression.this)
|
|
559
|
+
if maximum is None or value is None or value.type == "boolean" or not _PLAIN_INTEGER.fullmatch(value.text):
|
|
560
|
+
return None
|
|
561
|
+
return ir.LiteralValue(type="numeric", text=value.text) if int(value.text) <= maximum else None
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
_PLAIN_INTEGER = re.compile(r"0|[1-9][0-9]{0,18}")
|
|
565
|
+
|
|
566
|
+
# Nodes whose value is not a function of the columns an expression reads.
|
|
567
|
+
# Builtins modelled only when the call sets no argument but their own.
|
|
568
|
+
_ONE_ARGUMENT_BUILTINS = (exp.Lower, exp.Upper, exp.Length, exp.Trim, exp.Abs, exp.Floor, exp.Ceil)
|
|
569
|
+
|
|
570
|
+
# Functions whose type follows their operands' (`rules/value_typing.py`), or that
|
|
571
|
+
# are not calls of a named function: no `unknown-function` warning.
|
|
572
|
+
_OPERAND_TYPED = (exp.Case, exp.If, exp.Nullif, exp.Coalesce, exp.Binary, exp.Unary, exp.Predicate, exp.Cast, exp.AggFunc, exp.Window)
|