sqlassert 0.3.3__py3-none-any.whl → 0.4.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. sqlassert/__init__.py +1 -2
  2. sqlassert/check.py +88 -13
  3. sqlassert/declared_types.py +158 -0
  4. sqlassert/diagnostics.py +15 -7
  5. sqlassert/dialects.py +259 -107
  6. sqlassert/discovery/bigquery.py +4 -2
  7. sqlassert/discovery/databricks.py +26 -5
  8. sqlassert/discovery/duckdb.py +49 -7
  9. sqlassert/discovery/fetcher.py +137 -58
  10. sqlassert/discovery/information_schema.py +31 -6
  11. sqlassert/discovery/mysql.py +21 -4
  12. sqlassert/discovery/postgres.py +28 -20
  13. sqlassert/discovery/redshift.py +3 -2
  14. sqlassert/discovery/snowflake.py +5 -2
  15. sqlassert/discovery/trino.py +2 -2
  16. sqlassert/functions/__init__.py +10 -0
  17. sqlassert/functions/load.py +375 -0
  18. sqlassert/functions/table.py +2721 -0
  19. sqlassert/hazards.py +249 -88
  20. sqlassert/ir/__init__.py +15 -4
  21. sqlassert/ir/convert/__init__.py +13 -0
  22. sqlassert/ir/convert/aggregation.py +438 -0
  23. sqlassert/ir/convert/expressions.py +581 -0
  24. sqlassert/ir/convert/joins.py +264 -0
  25. sqlassert/ir/convert/markers.py +249 -0
  26. sqlassert/ir/convert/parser.py +249 -0
  27. sqlassert/ir/convert/queries.py +259 -0
  28. sqlassert/ir/convert/schema.py +537 -0
  29. sqlassert/ir/convert/scopes.py +205 -0
  30. sqlassert/ir/convert/selects.py +352 -0
  31. sqlassert/ir/convert/shared.py +428 -0
  32. sqlassert/ir/convert/sources.py +433 -0
  33. sqlassert/ir/convert/subqueries.py +364 -0
  34. sqlassert/ir/convert/value_types.py +78 -0
  35. sqlassert/ir/convert/windows.py +275 -0
  36. sqlassert/ir/model.py +417 -146
  37. sqlassert/ir/names.py +63 -0
  38. sqlassert/main.py +7 -10
  39. sqlassert/properties.py +12 -1
  40. sqlassert/provenance.py +5 -1
  41. sqlassert/python_engine.py +104 -44
  42. sqlassert/reporting.py +33 -32
  43. sqlassert/rewrites.py +111 -61
  44. sqlassert/rules/STYLEGUIDE.md +3 -2
  45. sqlassert/rules/causes/__init__.py +41 -0
  46. sqlassert/rules/causes/coverage.py +113 -0
  47. sqlassert/rules/causes/domain.py +123 -0
  48. sqlassert/rules/causes/joins.py +73 -0
  49. sqlassert/rules/causes/nulls.py +154 -0
  50. sqlassert/rules/causes/unique.py +564 -0
  51. sqlassert/rules/domain.py +9 -8
  52. sqlassert/rules/equality.py +6 -147
  53. sqlassert/rules/exactly_one.py +2 -1
  54. sqlassert/rules/foreign_key.py +8 -9
  55. sqlassert/rules/join_cardinality.py +277 -43
  56. sqlassert/rules/nullability.py +8 -8
  57. sqlassert/rules/uniqueness.py +212 -87
  58. sqlassert/rules/value_typing.py +470 -0
  59. sqlassert/sql_parse.py +28 -1
  60. sqlassert/suggest.py +13 -17
  61. sqlassert-0.4.2.dist-info/METADATA +239 -0
  62. sqlassert-0.4.2.dist-info/RECORD +72 -0
  63. sqlassert/ir/convert.py +0 -3509
  64. sqlassert-0.3.3.dist-info/METADATA +0 -807
  65. sqlassert-0.3.3.dist-info/RECORD +0 -46
  66. {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/WHEEL +0 -0
  67. {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/entry_points.txt +0 -0
  68. {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/licenses/LICENSE +0 -0
  69. {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,581 @@
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 functions, ir
16
+ from sqlassert.declared_types import declared_typing
17
+ from sqlassert.diagnostics import Diagnostic, quoted
18
+ from sqlassert.properties import ExhaustiveCase, NonNullElements
19
+ from sqlassert.provenance import AttachmentSite, Origin
20
+ from sqlassert.sql_parse import exhaustive_span, literal_value, marker_position, written_sql
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 a
76
+ Call of a conservative Builtin over 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
+ found = None if quantified else functions.call(self.dialect, expression)
195
+ if found is not None:
196
+ function, values = found
197
+ if type(expression) is exp.Cast and self._is_json(expression.this, lower):
198
+ # `CAST(JSON 'null' AS BIGINT)` is NULL.
199
+ function = _never_total(function)
200
+ if isinstance(expression, exp.Cast):
201
+ # The target is the call's own type: TRY_CAST too, a failure being NULL, which equals nothing.
202
+ function = functions.captured(function, declared_typing(expression.to, self.dialect))
203
+ arguments = tuple(lower(value) for value in values)
204
+ if (
205
+ type(expression) is exp.Like and self.semantics.text_is_binary
206
+ and isinstance(arguments[1], ir.Constant)
207
+ and (pattern := arguments[1].value) is not None and pattern.type == "string"
208
+ and not any(character in pattern.text for character in "%_\\")
209
+ and expression.find_ancestor(exp.Escape) is None
210
+ and (kind := self._declared_type(arguments[0], through_sets=False)) is not None
211
+ and kind.this in _TEXT_TYPES
212
+ ):
213
+ return ir.Equality(origin=origin, left=arguments[0], right=arguments[1], total=True)
214
+ total = function.properties((ir.Argument(),) * len(arguments), None).total is not None
215
+ composites = [
216
+ (value, argument) for value, argument in zip(values, arguments)
217
+ if function.name in _ORDER_COMPARISONS and total and self._is_composite(value, lower)
218
+ ]
219
+ if composites:
220
+ function, arguments = self._composite_comparison(expression, function, arguments, composites, self._origin(expression, line or _source_line(expression)))
221
+ return self._typed_call(expression, ir.Call(origin=origin, function=function, arguments=arguments, description=description))
222
+ if isinstance(expression, _NOT_A_FUNCTION_OF_ITS_COLUMNS):
223
+ # A function SQLGlot does not know has the type the dialect gives it, if any.
224
+ opaque = ir.OpaqueExpression(origin=origin, description=description, typing=functions.fixed_typing(self.dialect, expression) if isinstance(expression, exp.Anonymous) or functions.volatile(self.dialect, expression) else None)
225
+ if isinstance(expression, exp.Anonymous):
226
+ self._typed_call(expression, opaque)
227
+ if isinstance(expression, exp.Window):
228
+ if _row_number_window(expression) is not None:
229
+ # An integer type in every engine, whichever (docs/dialects.md).
230
+ opaque = replace(opaque, typing=declared_typing(exp.DataType.build("BIGINT", dialect=self.dialect), self.dialect))
231
+ self._unsupported.append((opaque, "a window function (other than a row_number() select item or QUALIFY row_number() ... = 1)"))
232
+ return opaque
233
+ if isinstance(expression, exp.Case) or isinstance(expression, exp.If):
234
+ # A searched CASE (a simple one is a SimpleCase) or IF: conditions and results, flat.
235
+ parts = _selection_parts(expression)
236
+ results = tuple(index for index, (_, is_result) in enumerate(parts) if is_result)
237
+ return ir.Call(
238
+ origin=origin, function=functions.selection(type(expression).__name__.upper(), len(parts), results),
239
+ arguments=tuple(lower(part) for part, _ in parts), description=description,
240
+ )
241
+ children = list(expression.iter_expressions())
242
+ return self._typed_call(expression, ir.Call(
243
+ origin=origin, function=functions.unmodelled(expression, len(children)),
244
+ arguments=tuple(lower(child) for child in children), description=description,
245
+ ))
246
+
247
+ def _typed_call[T: ir.Call | ir.OpaqueExpression](self: IrParser, expression: Expr, call: T) -> T:
248
+ """`call`, warning `unknown-function` once when it is a function call
249
+ whose result type sqlassert does not know for the dialect: the
250
+ function table (`functions/table.py`) gives it none, fixed or
251
+ following an argument's. Its value then has no known type, so an
252
+ equality on it binds nothing; the warning names the gap where it is
253
+ written, not as an unknown type further down. Operators, CASE, NULLIF
254
+ and arithmetic are typed by their operands (`rules/value_typing.py`)
255
+ and are not function calls here."""
256
+ untyped = not call.function.typed if isinstance(call, ir.Call) else call.typing is None
257
+ if not untyped or not isinstance(expression, exp.Func) or isinstance(expression, _OPERAND_TYPED) or id(expression) in self._untyped_calls:
258
+ return call
259
+ self._untyped_calls.add(id(expression))
260
+ name = expression.name if isinstance(expression, exp.Anonymous) else expression.sql_name()
261
+ self._warnings.append(Diagnostic(
262
+ diag.UNKNOWN_FUNCTION,
263
+ f"{name.lower()}() has no result type sqlassert knows in {self.dialect}, so its value has no known type and "
264
+ "an equality on it proves nothing; CAST it to the type it returns",
265
+ _placed(call.origin, expression),
266
+ ))
267
+ return call
268
+
269
+ def _checked_comparison(self: IrParser, comparison: exp.Binary, lower: Callable[[Expr], ir.ScalarExpr]) -> bool:
270
+ """Whether `comparison` compares its operands' values as they are:
271
+ where a failed implicit cast raises, and neither is a composite, which
272
+ may hold a NULL element."""
273
+ return self.semantics.casts_raise and not any(
274
+ self._is_composite(operand, lower) for operand in (comparison.this, comparison.expression)
275
+ )
276
+
277
+ def _check_zoned_text(self: IrParser, comparison: Expr, lower: Callable[[Expr], ir.ScalarExpr], origin: Origin) -> None:
278
+ """Warn of a comparison with a CAST of a zoned timestamp, where it keeps
279
+ its zone: equal instants cast to different text (or dates, or local
280
+ times), so the comparison depends on the zone each value was given."""
281
+ if self.semantics.zoned_timestamp_is_instant or id(comparison) in self._zone_checked:
282
+ return
283
+ self._zone_checked.add(id(comparison))
284
+ operands = [comparison.this, *_as_list(comparison.args.get("expression") or []), *comparison.expressions]
285
+ operands += [comparison.args[key] for key in ("low", "high") if comparison.args.get(key) is not None]
286
+ for operand in operands:
287
+ while isinstance(operand, exp.Paren):
288
+ operand = operand.this
289
+ if not isinstance(operand, exp.Cast) or operand.to.this in _ZONED_TYPES or not isinstance(operand.this, exp.Column):
290
+ continue
291
+ kind = self._declared_type(lower(operand.this))
292
+ if kind is None or kind.this not in _ZONED_TYPES:
293
+ continue
294
+ cast = operand.sql(dialect=self.dialect)
295
+ self._warnings.append(Diagnostic(
296
+ diag.ZONED_TIMESTAMP_CAST,
297
+ f"{cast} is compared, but a {kind.sql(dialect=self.dialect)} keeps the zone it was given in {self.dialect}, "
298
+ "so equal instants cast to different values and the comparison depends on each value's zone: "
299
+ "compare the timestamps themselves, or convert to one zone first (AT TIME ZONE 'UTC')",
300
+ origin,
301
+ ))
302
+
303
+ def _composite_comparison(
304
+ self: IrParser, comparison: Expr, function: ir.Builtin, arguments: tuple[ir.ScalarExpr, ...],
305
+ composites: list[tuple[Expr, ir.ScalarExpr]], origin: Origin,
306
+ ) -> tuple[ir.Builtin, tuple[ir.ScalarExpr, ...]]:
307
+ """A comparison of composites (ARRAYs, ROWs, MAPs), non-null only when
308
+ no element is NULL either: `ARRAY[1, NULL] <> ARRAY[1, NULL]` is NULL in
309
+ Trino. So it also takes each composite operand's Elements, as a
310
+ non-strict, total argument. A composite column or CAST, whose elements
311
+ the SQL does not show, is noted for a warning."""
312
+ count, extra = len(arguments), len(composites)
313
+
314
+ def properties(summaries: tuple[ir.Argument, ...], result: ir.ValueTyping | None) -> ir.CallProperties:
315
+ compared = function.properties(summaries[:count], result)
316
+ assert compared.total is not None
317
+ return ir.CallProperties(
318
+ strict=compared.strict + (False,) * extra, total=compared.total + (True,) * extra,
319
+ respects=compared.respects + (False,) * extra, reflects=compared.reflects + (False,) * extra, reason=compared.reason,
320
+ )
321
+
322
+ widened = replace(function, arity=count + extra, properties=properties)
323
+ elements = tuple(ir.Elements(origin=argument.origin, operand=argument) for _, argument in composites)
324
+ for value, argument in composites:
325
+ while isinstance(value, exp.Paren):
326
+ value = value.this
327
+ if isinstance(value, (exp.Column, exp.Cast)) and id(value) not in self._composite_comparisons:
328
+ self._composite_comparisons[id(value)] = (origin, comparison.sql(dialect=self.dialect), value.sql(dialect=self.dialect), argument)
329
+ return widened, arguments + elements
330
+
331
+ def _composite_warnings(self: IrParser) -> list[Diagnostic]:
332
+ """A warning for each composite operand whose elements no NOT NULL
333
+ ELEMENTS declaration covers, on it or on a column it passes on from."""
334
+ declared = {column for item in self._declarations if isinstance(item, NonNullElements) for column in item.columns}
335
+ warnings = []
336
+ for origin, comparison, operand, argument in self._composite_comparisons.values():
337
+ expression, covered = argument, False
338
+ while isinstance(expression, ir.ColumnRef) and not covered:
339
+ covered = expression.column in declared
340
+ expression = expression.column.scalar_expr
341
+ if not covered:
342
+ warnings.append(Diagnostic(
343
+ diag.COMPOSITE_COMPARISON,
344
+ f"{comparison} compares {operand}, which may hold a NULL element, and a comparison of composites with "
345
+ "a NULL element may be NULL (it is in Trino), so it is not taken to be non-null: if its elements are "
346
+ "never NULL, say so with /**DECLARE NOT NULL ELEMENTS(...)**/ on a Select Expression that outputs it",
347
+ origin,
348
+ ))
349
+ return warnings
350
+
351
+ def _is_composite(self: IrParser, node: Expr, lower: Callable[[Expr], ir.ScalarExpr]) -> bool:
352
+ """Whether the operand may be composite, including unknown column types."""
353
+ match node:
354
+ case exp.Paren() | exp.Nullif():
355
+ return self._is_composite(node.this, lower)
356
+ case exp.Cast():
357
+ return node.to.this in _COMPOSITE_TYPES
358
+ case exp.Column():
359
+ kind = self._declared_type(lower(node))
360
+ return self.dialect in {"trino", "postgres"} if kind is None else kind.this in _COMPOSITE_TYPES
361
+ case exp.Array() | exp.Struct() | exp.Map() | exp.VarMap():
362
+ return True
363
+ case exp.Coalesce():
364
+ return any(self._is_composite(each, lower) for each in (node.this, *node.expressions))
365
+ case exp.Case():
366
+ arms = [arm.args["true"] for arm in node.args.get("ifs") or ()]
367
+ default = node.args.get("default")
368
+ return any(self._is_composite(each, lower) for each in (*arms, *([default] if default is not None else [])))
369
+ case exp.If():
370
+ false = node.args.get("false")
371
+ return any(self._is_composite(each, lower) for each in (node.args["true"], *([false] if false is not None else [])))
372
+ case _:
373
+ return False
374
+
375
+ def _is_json(self: IrParser, node: Expr, lower: Callable[[Expr], ir.ScalarExpr]) -> bool:
376
+ """Whether the operand may be JSON or VARIANT, whose null can cast to SQL NULL."""
377
+ match node:
378
+ case exp.Paren() | exp.Nullif():
379
+ return self._is_json(node.this, lower)
380
+ case exp.Cast():
381
+ return node.to.this in _JSON_TYPES
382
+ case exp.Column():
383
+ kind = self._declared_type(lower(node))
384
+ return kind is None or kind.this in _JSON_TYPES
385
+ case exp.ParseJSON() | exp.JSONExtract() | exp.JSONBExtract() | exp.JSONObject() | exp.JSONArray() | exp.JSONObjectAgg() | exp.JSONArrayAgg():
386
+ return True
387
+ case exp.Coalesce():
388
+ return any(self._is_json(each, lower) for each in (node.this, *node.expressions))
389
+ case exp.Case():
390
+ arms = [arm.args["true"] for arm in node.args.get("ifs") or ()]
391
+ default = node.args.get("default")
392
+ return any(self._is_json(each, lower) for each in (*arms, *([default] if default is not None else [])))
393
+ case exp.If():
394
+ false = node.args.get("false")
395
+ return any(self._is_json(each, lower) for each in (node.args["true"], *([false] if false is not None else [])))
396
+ case _:
397
+ return False
398
+
399
+ def _mixed_results(self: IrParser, expression: exp.Case | exp.If, lower: Callable[[Expr], ir.ScalarExpr]) -> None:
400
+ """Read the results of a CASE or IF (the values it may return, no
401
+ condition) for a Hazard: when they have different declared types the
402
+ engine casts them to a common type (or rejects the query), and a cast
403
+ may lose what told values apart (`'01'` and `'1'` both become 1, a
404
+ large BIGINT a rounded DOUBLE). Integer types only widen, so they mix
405
+ safely. A result whose type is not known is left out, never guessed.
406
+ The type of the CASE itself is the type its results share
407
+ (`rules/value_typing.py`)."""
408
+ kinds: dict[str, str] = {}
409
+ for result in _result_expressions(expression):
410
+ while isinstance(result, exp.Paren):
411
+ result = result.this
412
+ kind: exp.DataType | None = None
413
+ match result:
414
+ case None | exp.Null():
415
+ continue # Takes the type of the other results.
416
+ case exp.Column():
417
+ kind = self._declared_type(lower(result))
418
+ case exp.Cast():
419
+ kind = result.to
420
+ case exp.Literal(is_string=True):
421
+ kinds.setdefault("text", "a text literal")
422
+ case _:
423
+ pass
424
+ if kind is None:
425
+ continue
426
+ family = "integer" if kind.this in exp.DataType.INTEGER_TYPES else "text" if kind.this in exp.DataType.TEXT_TYPES else kind.this.name
427
+ kinds.setdefault(family, kind.sql(dialect=self.dialect))
428
+ select = expression.find_ancestor(exp.Select)
429
+ if len(kinds) < 2 or select is None or (position := marker_position(select)) is None:
430
+ return
431
+ offset, line = position
432
+ self._mixed_cases.append((
433
+ AttachmentSite(_select_label(select), line, offset, True),
434
+ f"{written_sql(expression, self.dialect)} mixes {' and '.join(kinds.values())}",
435
+ ))
436
+
437
+ def _lower_case(self: IrParser, case: exp.Case, bindings: tuple[_Binding, ...], *, schema_complete: bool) -> ir.SimpleCase:
438
+ """A simple CASE, and the assertion its marker states, once per CASE."""
439
+
440
+ def lower(expression: Expr) -> ir.ScalarExpr:
441
+ return self._lower_expression(expression, bindings, schema_complete=schema_complete)
442
+
443
+ arms = case.args.get("ifs") or ()
444
+ default = case.args.get("default")
445
+ origin = self._placed(case)
446
+ lowered = ir.SimpleCase(
447
+ origin=origin,
448
+ operand=lower(case.this),
449
+ whens=tuple(lower(arm.this) for arm in arms),
450
+ thens=tuple(lower(arm.args["true"]) for arm in arms),
451
+ # A missing ELSE shares the CASE's origin, which marks it missing.
452
+ default=lower(default) if default is not None else ir.NullLiteral(origin=origin),
453
+ )
454
+ if id(case) not in self._sited_cases:
455
+ self._sited_cases.add(id(case))
456
+ self._add_attachment_site(case, f"CASE {case.this.sql(dialect=self.dialect)}", lowered)
457
+ span = exhaustive_span(case)
458
+ if span is not None and id(case) not in self._handled_cases:
459
+ self._handled_cases.add(id(case))
460
+ origin = Origin.marked(case.sql(dialect=self.dialect), span)
461
+ self._assertions.append(ir.Assertion(origin=origin, property=ExhaustiveCase(case=lowered)))
462
+ return lowered
463
+
464
+
465
+ def _as_list(value: Expr | list[Expr]) -> list[Expr]:
466
+ return value if isinstance(value, list) else [value]
467
+
468
+
469
+ def _disjuncts(predicate: Expr) -> list[Expr]:
470
+ """The operands of a predicate's top-level ORs, parentheses removed."""
471
+ while isinstance(predicate, exp.Paren):
472
+ predicate = predicate.this
473
+ if isinstance(predicate, exp.Or):
474
+ return _disjuncts(predicate.this) + _disjuncts(predicate.expression)
475
+ return [predicate]
476
+
477
+
478
+ def _selection_parts(expression: exp.Case | exp.If) -> list[tuple[Expr, bool]]:
479
+ """The expressions a searched CASE or an IF reads, in order, each with
480
+ whether it is a value the expression may return (not a condition)."""
481
+ match expression:
482
+ case exp.Case():
483
+ parts: list[tuple[Expr, bool]] = []
484
+ for arm in expression.args.get("ifs") or ():
485
+ parts.extend([(arm.this, False), (arm.args["true"], True)])
486
+ default = expression.args.get("default")
487
+ return [*parts, *([(default, True)] if default is not None else [])]
488
+ case exp.If():
489
+ false = expression.args.get("false")
490
+ return [(expression.this, False), (expression.args["true"], True), *([(false, True)] if false is not None else [])]
491
+ case _:
492
+ assert_never(expression)
493
+
494
+
495
+ def _result_expressions(expression: exp.Case | exp.If | exp.Coalesce | exp.Nullif) -> list[Expr | None]:
496
+ """The values `expression` may return (None: an absent ELSE, a NULL), not its conditions."""
497
+ match expression:
498
+ case exp.Case():
499
+ return [*(arm.args["true"] for arm in expression.args.get("ifs") or ()), expression.args.get("default")]
500
+ case exp.If():
501
+ return [expression.args.get("true"), expression.args.get("false")]
502
+ case exp.Coalesce():
503
+ return [expression.this, *expression.expressions]
504
+ case exp.Nullif():
505
+ return [expression.this, expression.expression]
506
+ case _:
507
+ assert_never(expression)
508
+ # TIMESTAMPTZ is too, where it holds an instant only (`zoned_timestamp_is_instant`).
509
+
510
+ # Types whose values keep the zone they were given, where a TIMESTAMP WITH
511
+ # TIME ZONE is not an instant only: a CAST to another type reads that zone.
512
+ _ZONED_TYPES = {exp.DataType.Type.TIMESTAMPTZ, exp.DataType.Type.TIMETZ}
513
+
514
+ # Types whose `null` (JSON's, a VARIANT's) is a non-null value that a CAST turns into NULL.
515
+ _JSON_TYPES = {exp.DataType.Type.JSON, exp.DataType.Type.JSONB, exp.DataType.Type.VARIANT, exp.DataType.Type.OBJECT}
516
+
517
+ # Composite types: a comparison of their values may be NULL for a NULL element.
518
+ _COMPOSITE_TYPES = {exp.DataType.Type.ARRAY, exp.DataType.Type.LIST, exp.DataType.Type.STRUCT, exp.DataType.Type.MAP, exp.DataType.Type.NESTED}
519
+
520
+ # The Builtins that compare two values, which compare composites element by element.
521
+ # Never NULL, in every dialect: a NULL operand is a value they compare.
522
+ _IS_DISTINCT_FROM = ir.Builtin.constant("IS DISTINCT FROM", (False, False), (False, False))
523
+ # Never NULL: TRUE or FALSE, whatever its subquery returns.
524
+ _EXISTS = ir.Builtin.constant("EXISTS", (False,), (False,))
525
+ _ORDER_COMPARISONS = {"<>", ">", ">=", "<", "<=", "BETWEEN"}
526
+ # Never NULL: `NULL IS TRUE` is FALSE, so never TRUE where the operand is NULL.
527
+ _IS_TRUE = ir.Builtin.constant("IS TRUE", (False,), (False,), true_only_if_argument=True)
528
+ _IS_FALSE = ir.Builtin.constant("IS FALSE", (False,), (False,), rejecting=(True,))
529
+
530
+
531
+ @cache
532
+ def _any_comparison(node: type[Expr]) -> ir.Builtin:
533
+ """`x op ANY (...)`, in every dialect: FALSE over no values, even for a
534
+ NULL `x`, else NULL where `x` is, so never TRUE where `x` is NULL. Not
535
+ `ALL`, which is TRUE over no values."""
536
+ names: dict[type[Expr], str] = {exp.EQ: "=", exp.NEQ: "<>", exp.GT: ">", exp.GTE: ">=", exp.LT: "<", exp.LTE: "<="}
537
+ name = names[node]
538
+ return ir.Builtin.constant(f"{name} ANY", (False, False), None, rejecting=(True, False))
539
+
540
+ # Comparisons, whose operands a zoned timestamp's text may be.
541
+ _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)
542
+
543
+ # The largest value of each signed integer type, the same in every dialect.
544
+ _INTEGER_MAXIMA = {
545
+ exp.DataType.Type.TINYINT: 2**7 - 1, exp.DataType.Type.SMALLINT: 2**15 - 1,
546
+ exp.DataType.Type.INT: 2**31 - 1, exp.DataType.Type.BIGINT: 2**63 - 1,
547
+ }
548
+
549
+
550
+ def _cast_integer_literal(expression: Expr) -> ir.LiteralValue | None:
551
+ """The value of `CAST('1' AS INTEGER)` or `CAST(1 AS BIGINT)`: a
552
+ non-negative integer, written as a number or a string with no sign,
553
+ leading zero or space, within a signed integer type's range. That is the
554
+ same integer in every dialect; a decimal (`CAST('1.5' AS INTEGER)` rounds
555
+ or truncates by dialect) or any other cast is not folded."""
556
+ if type(expression) is not exp.Cast: # TRY_CAST and the like are not modelled
557
+ return None
558
+ to = expression.args.get("to")
559
+ maximum = _INTEGER_MAXIMA.get(to.this) if isinstance(to, exp.DataType) else None
560
+ value = literal_value(expression.this)
561
+ if maximum is None or value is None or value.type == "boolean" or not _PLAIN_INTEGER.fullmatch(value.text):
562
+ return None
563
+ return ir.LiteralValue(type="numeric", text=value.text) if int(value.text) <= maximum else None
564
+
565
+
566
+ _PLAIN_INTEGER = re.compile(r"0|[1-9][0-9]{0,18}")
567
+
568
+
569
+ def _never_total(function: ir.Builtin) -> ir.Builtin:
570
+ """`function`, but possibly NULL for non-null arguments: a CAST from JSON,
571
+ whose `null` casts to NULL."""
572
+
573
+ def properties(arguments: tuple[ir.Argument, ...], result: ir.ValueTyping | None) -> ir.CallProperties:
574
+ return replace(function.properties(arguments, result), total=None)
575
+
576
+ return replace(function, properties=properties)
577
+
578
+
579
+ # Functions whose type follows their operands' (`rules/value_typing.py`), or that
580
+ # are not calls of a named function: no `unknown-function` warning.
581
+ _OPERAND_TYPED = (exp.Case, exp.If, exp.Nullif, exp.Coalesce, exp.Binary, exp.Unary, exp.Predicate, exp.Cast, exp.AggFunc, exp.Window)