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.
Files changed (65) hide show
  1. sqlassert/__init__.py +1 -2
  2. sqlassert/check.py +88 -13
  3. sqlassert/diagnostics.py +17 -6
  4. sqlassert/dialects.py +437 -7
  5. sqlassert/discovery/bigquery.py +3 -1
  6. sqlassert/discovery/databricks.py +25 -2
  7. sqlassert/discovery/duckdb.py +49 -7
  8. sqlassert/discovery/fetcher.py +130 -21
  9. sqlassert/discovery/information_schema.py +30 -2
  10. sqlassert/discovery/mysql.py +22 -1
  11. sqlassert/discovery/postgres.py +22 -5
  12. sqlassert/discovery/redshift.py +3 -2
  13. sqlassert/discovery/snowflake.py +3 -0
  14. sqlassert/discovery/trino.py +2 -2
  15. sqlassert/hazards.py +248 -87
  16. sqlassert/ir/__init__.py +4 -1
  17. sqlassert/ir/convert/__init__.py +13 -0
  18. sqlassert/ir/convert/aggregation.py +439 -0
  19. sqlassert/ir/convert/builtins.py +140 -0
  20. sqlassert/ir/convert/expressions.py +572 -0
  21. sqlassert/ir/convert/joins.py +264 -0
  22. sqlassert/ir/convert/markers.py +249 -0
  23. sqlassert/ir/convert/parser.py +253 -0
  24. sqlassert/ir/convert/queries.py +259 -0
  25. sqlassert/ir/convert/schema.py +606 -0
  26. sqlassert/ir/convert/scopes.py +205 -0
  27. sqlassert/ir/convert/selects.py +337 -0
  28. sqlassert/ir/convert/shared.py +429 -0
  29. sqlassert/ir/convert/sources.py +432 -0
  30. sqlassert/ir/convert/subqueries.py +364 -0
  31. sqlassert/ir/convert/value_types.py +223 -0
  32. sqlassert/ir/convert/windows.py +275 -0
  33. sqlassert/ir/model.py +125 -47
  34. sqlassert/ir/names.py +63 -0
  35. sqlassert/properties.py +12 -1
  36. sqlassert/provenance.py +5 -1
  37. sqlassert/python_engine.py +104 -44
  38. sqlassert/reporting.py +33 -32
  39. sqlassert/rewrites.py +111 -61
  40. sqlassert/rules/STYLEGUIDE.md +3 -2
  41. sqlassert/rules/causes/__init__.py +41 -0
  42. sqlassert/rules/causes/coverage.py +113 -0
  43. sqlassert/rules/causes/domain.py +123 -0
  44. sqlassert/rules/causes/joins.py +73 -0
  45. sqlassert/rules/causes/nulls.py +154 -0
  46. sqlassert/rules/causes/unique.py +523 -0
  47. sqlassert/rules/domain.py +8 -7
  48. sqlassert/rules/equality.py +6 -147
  49. sqlassert/rules/exactly_one.py +2 -1
  50. sqlassert/rules/foreign_key.py +8 -9
  51. sqlassert/rules/join_cardinality.py +282 -41
  52. sqlassert/rules/nullability.py +5 -5
  53. sqlassert/rules/uniqueness.py +171 -47
  54. sqlassert/rules/value_typing.py +337 -0
  55. sqlassert/sql_parse.py +28 -1
  56. sqlassert/suggest.py +11 -15
  57. sqlassert-0.4.1.dist-info/METADATA +235 -0
  58. sqlassert-0.4.1.dist-info/RECORD +69 -0
  59. sqlassert/ir/convert.py +0 -3509
  60. sqlassert-0.3.3.dist-info/METADATA +0 -807
  61. sqlassert-0.3.3.dist-info/RECORD +0 -46
  62. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/WHEEL +0 -0
  63. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/entry_points.txt +0 -0
  64. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/licenses/LICENSE +0 -0
  65. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,364 @@
1
+ """WHERE and subqueries: EXISTS and IN conjuncts as semi and anti joins, and
2
+ scalar subqueries as left joins (decorrelated where they can be)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from collections.abc import Sequence
7
+ from dataclasses import replace
8
+ from typing import TYPE_CHECKING, Literal
9
+
10
+ from sqlglot import Expr, exp
11
+
12
+ from sqlassert import diagnostics as diag
13
+ from sqlassert import ir
14
+ from sqlassert.diagnostics import Diagnostic, quoted
15
+ from sqlassert.provenance import AttachmentSite
16
+ from sqlassert.sql_parse import grouping, marker_position
17
+ from sqlassert.ir.convert.shared import (
18
+ _Binding, _Lowered, _pass_output_columns, _source_line, _subquery_conjunct, _and, _filter_conjuncts, _all_joins, _from_source, _SCALAR_QUALIFIER,
19
+ _scalar_subqueries, _schema_path, _star_only,
20
+ )
21
+
22
+ if TYPE_CHECKING:
23
+ from sqlassert.ir.convert.parser import IrParser
24
+
25
+
26
+ class _Subqueries:
27
+ def _filter(self: IrParser, lowered: _Lowered, where: exp.Where) -> _Lowered:
28
+ """WHERE: each `EXISTS`, `NOT EXISTS`, or `IN (subquery)` conjunct as a
29
+ semi or anti join (Paulley §4.4.2), the other conjuncts as one Filter."""
30
+ remaining = []
31
+ for conjunct in _filter_conjuncts(where.this):
32
+ joined = self._subquery_join(lowered, conjunct)
33
+ if joined is None:
34
+ remaining.append(conjunct)
35
+ else:
36
+ lowered = joined
37
+ if not remaining:
38
+ return lowered
39
+ before = lowered.relation.output_columns
40
+ lowered, carried = self._join_scalar_subqueries(lowered, remaining)
41
+ origin = self._placed(where)
42
+ output_columns = _pass_output_columns(lowered.relation.output_columns, origin)
43
+ remapped = {source: output for source, output in zip(lowered.relation.output_columns, output_columns)}
44
+ complete = lowered.relation.is_schema_complete
45
+ relation = ir.Filter(
46
+ origin=origin, output_columns=output_columns, is_schema_complete=complete, input=lowered.relation,
47
+ predicate=self._lower_condition(where.this, remaining, lowered.bindings, schema_complete=complete),
48
+ )
49
+ bindings = tuple(
50
+ replace(binding, column=remapped[binding.column]) for binding in lowered.bindings
51
+ )
52
+ if all(carried[column] is column for column in before):
53
+ return _Lowered(relation, bindings)
54
+ # Scalar subqueries were joined in: keep only the columns from before,
55
+ # so their values stay inside this WHERE.
56
+ kept = tuple(remapped[carried[column]] for column in before)
57
+ project = ir.Project(
58
+ origin=origin, output_columns=_pass_output_columns(kept, origin), is_schema_complete=complete, input=relation,
59
+ )
60
+ projected = dict(zip(kept, project.output_columns))
61
+ return _Lowered(project, tuple(
62
+ replace(binding, column=projected[binding.column])
63
+ for binding in bindings if binding.column in projected
64
+ ))
65
+
66
+ def _correlated(self: IrParser, select: exp.Select, inner: _Lowered, outer: _Lowered) -> bool | None:
67
+ """Whether `select` reads the outer scope, only in its WHERE; None when
68
+ it reads it anywhere else, or when a column may belong to either scope."""
69
+ where = select.args.get("where")
70
+ correlated = False
71
+ for column in select.find_all(exp.Column):
72
+ found = self._scope_of(column, inner, outer)
73
+ if found is None:
74
+ return None
75
+ scope, binding = found
76
+ self._scoped_columns[id(column)] = binding.column
77
+ if scope == "outer":
78
+ if where is None or column.find_ancestor(exp.Where) is not where:
79
+ return None # Only a WHERE becomes the dependent join's ON.
80
+ correlated = True
81
+ return correlated
82
+
83
+ def _scope_of(
84
+ self: IrParser, column: exp.Column, inner: _Lowered, outer: _Lowered
85
+ ) -> tuple[Literal["inner", "outer"], _Binding] | None:
86
+ """The scope a subquery's column belongs to, the innermost that has it,
87
+ and its binding there. None when that is unknown (a table with no
88
+ CREATE may have the column) or the name binds more than one column."""
89
+ name = column.name.lower()
90
+
91
+ def one(scope: Literal["inner", "outer"], bindings: list[_Binding]) -> tuple[Literal["inner", "outer"], _Binding] | None:
92
+ return (scope, bindings[0]) if len(bindings) == 1 else None
93
+
94
+ if column.table:
95
+ qualifier, schema = column.table.lower(), _schema_path(column)
96
+ for scope, bindings in (("inner", inner.bindings), ("outer", outer.bindings)):
97
+ if any(binding.qualifier == qualifier and (not schema or binding.schema == schema) for binding in bindings):
98
+ if self._reads_renamed(column, bindings, qualifier, schema, self._origin(column, _source_line(column))):
99
+ return None
100
+ return one(scope, [
101
+ binding for binding in bindings
102
+ if binding.qualifier == qualifier and (not schema or binding.schema == schema) and binding.name == name
103
+ ])
104
+ return None
105
+ if self._reads_renamed(column, (*inner.bindings, *outer.bindings), "", "", self._origin(column, _source_line(column))):
106
+ return None
107
+ inner_named = [binding for binding in inner.bindings if binding.name == name and not binding.shadowed and self._owns(binding) != "no"]
108
+ outer_named = [binding for binding in outer.bindings if binding.name == name and not binding.shadowed and self._owns(binding) != "no"]
109
+ owners = {self._owns(binding) for binding in inner_named}
110
+ if "yes" in owners:
111
+ return one("inner", inner_named)
112
+ outer_has = bool(outer_named)
113
+ if "unknown" in owners or (not inner_named and not inner.relation.is_schema_complete and not any(binding.name == name for binding in inner.bindings)):
114
+ if not outer_has:
115
+ return one("inner", inner_named)
116
+ self._warnings.append(Diagnostic(
117
+ diag.AMBIGUOUS_COLUMN,
118
+ f"column {quoted(column.name)} in a subquery may belong to its own FROM or to the outer query, "
119
+ "since some of its tables have no declared columns: qualify it, declare those tables with CREATE TABLE, "
120
+ "or analyze with a database connection (analyze_database)",
121
+ self._origin(column, _source_line(column)),
122
+ ))
123
+ return None
124
+ return one("outer", outer_named) if outer_has else None
125
+
126
+ def _owns(self: IrParser, binding: _Binding) -> Literal["yes", "no", "unknown"]:
127
+ """Whether the relation behind `binding` has its column: a declared or
128
+ computed column it has, one its declared table lacks it does not, and
129
+ one made up for a table with no CREATE it may have."""
130
+ base = binding.column
131
+ while isinstance(base.scalar_expr, ir.ColumnRef):
132
+ base = base.scalar_expr.column
133
+ if base in self._absent:
134
+ return "no"
135
+ return "unknown" if base in self._guessed else "yes"
136
+
137
+ def _join_scalar_subqueries(
138
+ self: IrParser, lowered: _Lowered, expressions: Sequence[Expr]
139
+ ) -> tuple[_Lowered, dict[ir.OutputColumn, ir.OutputColumn]]:
140
+ """Each scalar subquery in `expressions` joined onto `lowered`, and
141
+ where each of `lowered`'s columns went."""
142
+ carried = {column: column for column in lowered.relation.output_columns}
143
+ for expression in expressions:
144
+ for subquery in _scalar_subqueries(expression):
145
+ joined = self._scalar_subquery_join(lowered, subquery)
146
+ if joined is None:
147
+ continue
148
+ lowered, remapped = joined
149
+ carried = {column: remapped[current] for column, current in carried.items()}
150
+ return lowered, carried
151
+
152
+ def _scalar_subquery_join(
153
+ self: IrParser, lowered: _Lowered, subquery: exp.Subquery
154
+ ) -> tuple[_Lowered, dict[ir.OutputColumn, ir.OutputColumn]] | None:
155
+ """A scalar subquery with body B as a left join of `lowered` with B: no
156
+ row makes it NULL, which is a left join's padding. More than one row
157
+ is a runtime error, so the join is many to one, or the query fails.
158
+
159
+ Uncorrelated, B is lowered whole under an implied LIMIT 1, sound since
160
+ it changes the result only when the query would fail: its value is
161
+ the same on every row. Correlated, B's WHERE becomes the ON of a
162
+ dependent join (as for EXISTS), so only a plain select-from-where
163
+ whose value is one of its columns is lowered. Anything else, or a
164
+ column that may belong to either scope, stays opaque."""
165
+ select = subquery.this
166
+ if not isinstance(select, exp.Select) or len(select.expressions) != 1 or _star_only(select):
167
+ return None
168
+ source = _from_source(select)
169
+ if source is None or select.args.get("with") or any(
170
+ join.args.get("method") == "NATURAL" for join in _all_joins(select)
171
+ ) or any(isinstance(node, (exp.Subquery, exp.Exists, exp.Query)) and node is not select for node in select.walk()):
172
+ return None
173
+ right = self._lower_source(source)
174
+ for join in select.args.get("joins") or ():
175
+ right = self._lower_join(right, join)
176
+ correlated = self._correlated(select, right, lowered)
177
+ origin = self._origin(subquery)
178
+ if correlated is None:
179
+ return None
180
+ if not correlated:
181
+ body = self._finish_select(self._lower_select_tail(right, select), select)
182
+ right_relation: ir.RelationExpr = ir.Limit(
183
+ origin=origin, output_columns=_pass_output_columns(body.output_columns, origin),
184
+ is_schema_complete=body.is_schema_complete, input=body, count=1,
185
+ )
186
+ value = right_relation.output_columns[0]
187
+ predicate = None
188
+ else:
189
+ if grouping(select) == [] and not any(select.args.get(key) for key in ("having", "qualify", "distinct", "limit", "offset", "windows")):
190
+ return self._aggregate_subquery_join(lowered, subquery, select, right)
191
+ if grouping(select) is not None or any(select.args.get(key) for key in ("having", "qualify", "distinct", "limit", "offset", "windows")):
192
+ return None
193
+ item = select.expressions[0]
194
+ lowered_value = self._lower_expression(
195
+ item.this if isinstance(item, exp.Alias) else item, right.bindings, schema_complete=right.relation.is_schema_complete,
196
+ )
197
+ if not (isinstance(lowered_value, ir.ColumnRef) and lowered_value.column in right.relation.output_columns):
198
+ return None
199
+ inner = select.args.get("where")
200
+ predicate = None if inner is None else self._lower_condition(
201
+ inner.this, _filter_conjuncts(inner.this), lowered.bindings + right.bindings,
202
+ schema_complete=lowered.relation.is_schema_complete and right.relation.is_schema_complete,
203
+ )
204
+ right_relation, value = right.relation, lowered_value.column
205
+ input_columns = lowered.relation.output_columns + right_relation.output_columns
206
+ output_columns = _pass_output_columns(input_columns, origin)
207
+ remapped = dict(zip(input_columns, output_columns))
208
+ join = ir.Join(
209
+ origin=origin, output_columns=output_columns,
210
+ is_schema_complete=lowered.relation.is_schema_complete and right_relation.is_schema_complete,
211
+ kind="left", left=lowered.relation, right=right_relation, predicate=predicate, scalar_subquery=True,
212
+ )
213
+ position = marker_position(select)
214
+ if position is not None:
215
+ self._scalar_subqueries.append((AttachmentSite("scalar subquery", position[1], position[0], True), join))
216
+ qualifier = f"{_SCALAR_QUALIFIER}{len(self._scalar_values)}"
217
+ self._scalar_values[id(subquery)] = qualifier
218
+ bindings = (
219
+ *(replace(binding, column=remapped[binding.column]) for binding in lowered.bindings),
220
+ _Binding(qualifier, _SCALAR_QUALIFIER, remapped[value]),
221
+ )
222
+ return _Lowered(join, bindings), remapped
223
+
224
+ def _aggregate_subquery_join(
225
+ self: IrParser, lowered: _Lowered, subquery: exp.Subquery, select: exp.Select, right: _Lowered,
226
+ ) -> tuple[_Lowered, dict[ir.OutputColumn, ir.OutputColumn]] | None:
227
+ """A correlated scalar subquery whose value is one aggregate call,
228
+ `(SELECT agg(...) FROM r WHERE r.k = outer.k AND p)`, decorrelated:
229
+ r filtered by p, grouped by k, left joined on `k = outer.k`. Each
230
+ outer row meets at most its one group, and its value is a function of
231
+ the key. A row with no group gets the aggregate over no rows: NULL,
232
+ the join's padding, for the aggregates whose value over no rows is
233
+ NULL (`_EMPTY_NULL_AGGREGATES`); a count's is 0 (the count bug), so its
234
+ value is `coalesce(count, 0)`; any other aggregate is not
235
+ decorrelated. Nor is one whose arguments read the outer row: SQL
236
+ then makes it an aggregate of the outer query. Only equalities to outer
237
+ columns of the same declared type correlate it: grouping by `k`
238
+ then merges exactly the rows one outer value matches."""
239
+ where = select.args.get("where")
240
+ item = select.expressions[0]
241
+ value_expression = item.this if isinstance(item, exp.Alias) else item
242
+ if where is None or not isinstance(value_expression, _EMPTY_NULL_AGGREGATES | exp.Count):
243
+ return None
244
+ if any(
245
+ found is None or found[0] != "inner"
246
+ for found in (self._scope_of(column, right, lowered) for column in value_expression.find_all(exp.Column))
247
+ ):
248
+ return None
249
+ keys: list[tuple[Expr, ir.OutputColumn, ir.OutputColumn]] = [] # (inner column, inner, outer)
250
+ inner_only: list[Expr] = []
251
+ for conjunct in _filter_conjuncts(where.this):
252
+ scoped = [self._scope_of(column, right, lowered) for column in conjunct.find_all(exp.Column)]
253
+ if any(found is None for found in scoped):
254
+ return None
255
+ scopes = {found[0] for found in scoped if found is not None}
256
+ if scopes <= {"inner"}:
257
+ inner_only.append(conjunct)
258
+ continue
259
+ if not isinstance(conjunct, exp.EQ) or not isinstance(conjunct.this, exp.Column) or not isinstance(conjunct.expression, exp.Column):
260
+ return None
261
+ sides = [(node, self._scope_of(node, right, lowered)) for node in (conjunct.this, conjunct.expression)]
262
+ inner = [(node, found[1].column) for node, found in sides if found is not None and found[0] == "inner"]
263
+ outer = [found[1].column for _, found in sides if found is not None and found[0] == "outer"]
264
+ if len(inner) != 1 or len(outer) != 1:
265
+ return None
266
+ if _traced_comparison_type(inner[0][1]) is None or _traced_comparison_type(inner[0][1]) != _traced_comparison_type(outer[0]):
267
+ return None
268
+ keys.append((inner[0][0], inner[0][1], outer[0]))
269
+ if not keys:
270
+ return None
271
+ grouped = select.copy()
272
+ grouped.set("expressions", [
273
+ *(exp.alias_(node.copy(), f"k{index}") for index, (node, _, _) in enumerate(keys)), exp.alias_(value_expression.copy(), "value"),
274
+ ])
275
+ grouped.set("where", exp.Where(this=exp.and_(*(conjunct.copy() for conjunct in inner_only))) if inner_only else None)
276
+ grouped.set("group", exp.Group(expressions=[node.copy() for node, _, _ in keys]))
277
+ body = self._lower_select_tail(right, grouped)
278
+ if not isinstance(body, ir.Aggregate):
279
+ return None
280
+ origin = self._origin(subquery)
281
+ predicate = _and(tuple(
282
+ ir.Equality(origin=origin, left=ir.ColumnRef(origin=origin, column=outer), right=ir.ColumnRef(origin=origin, column=body.output_columns[index]))
283
+ for index, (_, _, outer) in enumerate(keys)
284
+ ), origin)
285
+ input_columns = lowered.relation.output_columns + body.output_columns
286
+ output_columns = _pass_output_columns(input_columns, origin)
287
+ remapped = dict(zip(input_columns, output_columns))
288
+ join = ir.Join(
289
+ origin=origin, output_columns=output_columns, is_schema_complete=lowered.relation.is_schema_complete,
290
+ kind="left", left=lowered.relation, right=body, predicate=predicate, scalar_subquery=True,
291
+ )
292
+ position = marker_position(select)
293
+ if position is not None:
294
+ self._scalar_subqueries.append((AttachmentSite("scalar subquery", position[1], position[0], True), join))
295
+ relation: ir.RelationExpr = join
296
+ value = remapped[body.output_columns[-1]]
297
+ if isinstance(value_expression, exp.Count):
298
+ passed = _pass_output_columns(output_columns, origin)
299
+ zero = self._constant(origin, ir.LiteralValue(type="numeric", text="0"))
300
+ counted = ir.OutputColumn(origin=origin, name="value", scalar_expr=ir.Coalesce(
301
+ origin=origin, arguments=(ir.ColumnRef(origin=origin, column=value), zero),
302
+ ))
303
+ relation = ir.Project(origin=origin, output_columns=(*passed, counted), is_schema_complete=join.is_schema_complete, input=join)
304
+ remapped = {source: passed[output_columns.index(output)] for source, output in remapped.items()}
305
+ value = counted
306
+ qualifier = f"{_SCALAR_QUALIFIER}{len(self._scalar_values)}"
307
+ self._scalar_values[id(subquery)] = qualifier
308
+ bindings = (
309
+ *(replace(binding, column=remapped[binding.column]) for binding in lowered.bindings),
310
+ _Binding(qualifier, _SCALAR_QUALIFIER, value),
311
+ )
312
+ return _Lowered(relation, bindings), remapped
313
+
314
+ def _subquery_join(self: IrParser, lowered: _Lowered, conjunct: Expr) -> _Lowered | None:
315
+ """`EXISTS (SELECT ... FROM r WHERE p)` as a semi join of r on p, and
316
+ `NOT EXISTS` as an anti join; `p` may read the outer row (a dependent
317
+ join, so the IR stays a DAG). `x IN (SELECT a ...)` as a semi join on
318
+ `x = a`. Not `NOT IN`: a NULL among the values makes it reject every row."""
319
+ matched = _subquery_conjunct(conjunct)
320
+ if matched is None:
321
+ return None
322
+ kind, select, operand = matched
323
+ if operand is None:
324
+ source = _from_source(select)
325
+ if source is None or grouping(select) is not None or any(
326
+ select.args.get(key) for key in ("having", "qualify", "distinct", "limit", "offset", "with", "windows")
327
+ ) or any(join.args.get("method") == "NATURAL" for join in _all_joins(select)):
328
+ # Grouped by nothing (`grouping` is []), it returns one row whatever its WHERE: EXISTS is always true.
329
+ return None
330
+ right = self._lower_source(source)
331
+ for join in select.args.get("joins") or ():
332
+ right = self._lower_join(right, join)
333
+ inner = select.args.get("where")
334
+ predicate = None if inner is None else self._lower_condition(
335
+ inner.this, _filter_conjuncts(inner.this), lowered.bindings + right.bindings,
336
+ schema_complete=lowered.relation.is_schema_complete and right.relation.is_schema_complete,
337
+ )
338
+ relation = right.relation
339
+ else:
340
+ subquery = self._lower_query(select)
341
+ if subquery is None or len(subquery.output_columns) != 1:
342
+ return None
343
+ relation = subquery
344
+ predicate = ir.Equality(
345
+ origin=self._origin(conjunct, _source_line(conjunct)),
346
+ left=self._lower_expression(operand, lowered.bindings, schema_complete=lowered.relation.is_schema_complete),
347
+ right=ir.ColumnRef(origin=subquery.origin, column=subquery.output_columns[0]),
348
+ )
349
+ return self._filtering_join(lowered, relation, kind, predicate, self._origin(conjunct))
350
+
351
+
352
+ def _traced_comparison_type(column: ir.OutputColumn) -> str | None:
353
+ """The declared comparison type of the column `column` passes on; None for
354
+ text not compared by identity."""
355
+ while column.typing is None and isinstance(column.scalar_expr, ir.ColumnRef):
356
+ column = column.scalar_expr.column
357
+ typing = column.typing
358
+ return None if typing is None or typing.text and not typing.binary_text else typing.comparison_type
359
+ # Aggregates whose value over no rows is NULL, so a decorrelated subquery's
360
+ # padding is that value. Not count_if, approx_count_distinct and the like: 0.
361
+ _EMPTY_NULL_AGGREGATES = (
362
+ exp.Sum | exp.Avg | exp.Min | exp.Max | exp.AnyValue | exp.LogicalAnd | exp.LogicalOr
363
+ | exp.ArgMax | exp.ArgMin | exp.First | exp.Last | exp.Stddev | exp.Variance
364
+ )
@@ -0,0 +1,223 @@
1
+ """Types: how a declared column, a CAST, a literal, or a call whose result type
2
+ the dialect fixes compares (`ir.ValueTyping`), and the declared SQL types
3
+ hazards read."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import re
8
+ from collections.abc import Sequence
9
+ from typing import TYPE_CHECKING, assert_never
10
+
11
+ from sqlglot import Expr, exp
12
+
13
+ from sqlassert import ir
14
+ from sqlassert.provenance import Origin
15
+ from sqlassert.ir.convert.shared import _TEXT_TYPES
16
+
17
+ if TYPE_CHECKING:
18
+ from sqlassert.ir.convert.parser import IrParser
19
+
20
+
21
+ class _ValueTypes:
22
+ def _comparison_type(self: IrParser, definition: exp.ColumnDef) -> str | None:
23
+ kind = definition.args.get("kind")
24
+ if not isinstance(kind, exp.DataType):
25
+ return None
26
+ if self._unscaled_decimal(kind):
27
+ return None
28
+ return self._type_name(kind)
29
+
30
+ def _type_name(self: IrParser, kind: exp.DataType) -> str:
31
+ """The name two values of one comparison type share: the type's SQL,
32
+ without a date or time type's parameters. TIMESTAMP(3) holds values
33
+ TIMESTAMP(6) holds unchanged, so they compare as one type (ADR 0009)."""
34
+ if kind.this in exp.DataType.TEMPORAL_TYPES and kind.expressions:
35
+ kind = kind.copy()
36
+ kind.set("expressions", [])
37
+ return kind.sql(dialect=self.dialect)
38
+
39
+ def _casts_to(self: IrParser, comparison_type: str) -> frozenset[str]:
40
+ """The types `comparison_type` is cast to when compared with them,
41
+ keeping different values different (`DialectSemantics.injective_casts`)."""
42
+ return frozenset(
43
+ self._type_name(exp.DataType.build(target, dialect=self.dialect))
44
+ for source, target in self.semantics.injective_casts
45
+ if self._type_name(exp.DataType.build(source, dialect=self.dialect)) == comparison_type
46
+ )
47
+
48
+ def _identity_comparison(self: IrParser, definition: exp.ColumnDef) -> bool:
49
+ """Declared with a type whose equal values are identical (text only
50
+ when compared by identity)."""
51
+ kind = definition.args.get("kind")
52
+ if not (self._comparison_type(definition) is not None and isinstance(kind, exp.DataType)):
53
+ return False
54
+ if kind.this == exp.DataType.Type.TIMESTAMPTZ:
55
+ return self.semantics.zoned_timestamp_is_instant
56
+ if kind.this in exp.DataType.TEXT_TYPES:
57
+ return self._is_binary_text(definition)
58
+ return kind.this in _IDENTITY_TYPES
59
+
60
+ def _exact_numeric(self: IrParser, definition: exp.ColumnDef) -> bool:
61
+ kind = definition.args.get("kind")
62
+ return isinstance(kind, exp.DataType) and kind.this in _EXACT_NUMERIC_TYPES and not self._unscaled_decimal(kind)
63
+
64
+ def _unscaled_decimal(self: IrParser, kind: exp.DataType) -> bool:
65
+ """A Postgres NUMERIC with no scale: 1.0 and 1.00 are equal values that differ."""
66
+ return self.semantics.unscaled_decimal and kind.this == exp.DataType.Type.DECIMAL and not kind.expressions
67
+
68
+ def _is_binary_text(self: IrParser, definition: exp.ColumnDef) -> bool:
69
+ """Declared VARCHAR or TEXT in a dialect whose default collation is
70
+ binary: compared by identity. CHAR is not: it ignores trailing spaces
71
+ when compared."""
72
+ kind = definition.args.get("kind")
73
+ return isinstance(kind, exp.DataType) and kind.this in _TEXT_TYPES and self.semantics.text_is_binary
74
+
75
+ def _declared_typing(self: IrParser, kind: exp.DataType) -> ir.ValueTyping | None:
76
+ """How a column declared with `kind` compares; None when it has no comparison type."""
77
+ return self._typing_of_declaration(exp.ColumnDef(kind=kind))
78
+
79
+ def _typing_of_declaration(self: IrParser, definition: exp.ColumnDef) -> ir.ValueTyping | None:
80
+ comparison_type = self._comparison_type(definition)
81
+ if comparison_type is None:
82
+ return None
83
+ kind = definition.args["kind"]
84
+ return ir.ValueTyping(
85
+ comparison_type, self._is_binary_text(definition), self._identity_comparison(definition), self._exact_numeric(definition),
86
+ floating=kind.this in _FLOATS, integer=_INTEGER_RANK.get(kind.this),
87
+ text=kind.this in exp.DataType.TEXT_TYPES, temporal=kind.this in exp.DataType.TEMPORAL_TYPES,
88
+ casts_to=self._casts_to(comparison_type),
89
+ )
90
+
91
+ def _cast_typing(self: IrParser, cast: exp.Cast) -> ir.ValueTyping | None:
92
+ """A CAST (TRY_CAST too: a failure is NULL, which equals nothing) has the
93
+ type it names, text included: text compares under the engine's default
94
+ collation (docs/dialects.md), whatever the operand was."""
95
+ return self._declared_typing(cast.to)
96
+
97
+ def _fixed_typing(self: IrParser, expression: Expr) -> ir.ValueTyping | None:
98
+ """The type of a call whose result type the dialect fixes (`_result_type`)."""
99
+ kind = self._result_type(expression)
100
+ return None if kind is None else self._declared_typing(kind)
101
+
102
+ def _literal_typing(self: IrParser, literal: ir.LiteralValue | None) -> ir.ValueTyping | None:
103
+ """How a literal compares, from the type the dialect gives one of its kind.
104
+
105
+ A string is text (by identity where the dialect's is); a boolean a
106
+ BOOLEAN; an integer an INT where it fits, else a BIGINT, and a decimal
107
+ beyond BIGINT or written with a point, or an exponent, the type
108
+ `DialectSemantics.literal_types` names for it (a float is
109
+ `floating`), or none where the dialect's is not claimed. A number
110
+ of more than 38 digits is none: DuckDB turns it into a DOUBLE."""
111
+ if literal is None:
112
+ return None
113
+ match literal.type:
114
+ case "string":
115
+ return self._declared_typing(exp.DataType.build("TEXT", dialect=self.dialect))
116
+ case "boolean":
117
+ return self._declared_typing(exp.DataType.build("BOOLEAN", dialect=self.dialect))
118
+ case "numeric":
119
+ pass
120
+ case _:
121
+ assert_never(literal.type)
122
+ text = literal.text
123
+ if re.fullmatch(r"-?[0-9]+", text):
124
+ if -(2**31) <= int(text) < 2**31:
125
+ return self._declared_typing(exp.DataType.build("INT", dialect=self.dialect))
126
+ if -(2**63) <= int(text) < 2**63:
127
+ return self._declared_typing(exp.DataType.build("BIGINT", dialect=self.dialect))
128
+ kind = "decimal"
129
+ else:
130
+ kind = "exponent" if "e" in text.lower() else "decimal"
131
+ if sum(character.isdigit() for character in text.split("e")[0].split("E")[0]) > _EXACT_LITERAL_DIGITS:
132
+ return None
133
+ name = dict(self.semantics.literal_types).get(kind)
134
+ if name is None:
135
+ return None
136
+ declared = exp.DataType.build(name, dialect=self.dialect)
137
+ if declared.this in _FLOATS:
138
+ return self._declared_typing(declared)
139
+ # An exact number is compared by value. A literal is one value, so its
140
+ # scale (PostgreSQL's NUMERIC keeps the one written) does not matter.
141
+ return ir.ValueTyping("DECIMAL LITERAL", False, True, True)
142
+
143
+ def _constant(self: IrParser, origin: Origin, value: ir.LiteralValue | None) -> ir.Constant:
144
+ return ir.Constant(origin=origin, value=value, typing=self._literal_typing(value))
145
+
146
+ def _result_type(self: IrParser, expression: Expr) -> exp.DataType | None:
147
+ """The type the dialect returns for `expression`, a call of a function
148
+ whose result type does not depend on its arguments' (`DialectSemantics.result_types`)."""
149
+ name = dict(self.semantics.result_types).get(_function_key(expression))
150
+ return exp.DataType.build(name, dialect=self.dialect) if name is not None else None
151
+
152
+ def _argument_typing(self: IrParser, expression: Expr, arguments: Sequence[Expr]) -> ir.ArgumentTyping | None:
153
+ """How the type of `expression` follows one of its `arguments` (the
154
+ SQLGlot nodes lowered, in order), where the dialect says it does
155
+ (`DialectSemantics.argument_result_types`)."""
156
+ key = _function_key(expression)
157
+ for node, argument, mapping in self.semantics.argument_result_types:
158
+ value = expression.args.get(argument)
159
+ if node != key or not isinstance(value, Expr):
160
+ continue
161
+ position = next((index for index, candidate in enumerate(arguments) if candidate is value), None)
162
+ if position is None:
163
+ return None
164
+ results = []
165
+ for argument_type, result_type in mapping:
166
+ if argument_type == "*":
167
+ continue
168
+ typing = self._declared_typing(exp.DataType.build(result_type, dialect=self.dialect))
169
+ if typing is not None:
170
+ results.append((exp.DataType.build(argument_type, dialect=self.dialect).sql(dialect=self.dialect), typing))
171
+ return ir.ArgumentTyping(position, tuple(results), keeps=("*", "=") in mapping)
172
+ return None
173
+
174
+ def _declared_type(self: IrParser, expression: ir.ScalarExpr, *, through_sets: bool = True) -> exp.DataType | None:
175
+ """The type a CREATE TABLE declares for the column `expression` reads,
176
+ through every column that passes it on. A set operation passes on its
177
+ left input's type, which hazard checks want; `through_sets=False`
178
+ stops there instead, for a rewrite that the right input's values must
179
+ also satisfy."""
180
+ while isinstance(expression, ir.ColumnRef):
181
+ column = expression.column
182
+ if not through_sets and column in self._set_outputs:
183
+ return None
184
+ if column in self._declared_types:
185
+ return self._declared_types[column]
186
+ expression = column.scalar_expr
187
+ return None
188
+
189
+
190
+ def _function_key(expression: Expr) -> str:
191
+ """The key of a function call in `DialectSemantics.result_types`: its
192
+ SQLGlot node, or `Anonymous:<lowercase name>` for one SQLGlot does not know."""
193
+ if isinstance(expression, exp.Anonymous):
194
+ return f"Anonymous:{expression.name.lower()}"
195
+ return type(expression).__name__
196
+
197
+
198
+ # The signed integer types, by width (`ir.ValueTyping.integer`).
199
+ _INTEGER_RANK = {
200
+ exp.DataType.Type.TINYINT: 0, exp.DataType.Type.SMALLINT: 1, exp.DataType.Type.MEDIUMINT: 2, exp.DataType.Type.INT: 3,
201
+ exp.DataType.Type.BIGINT: 4, exp.DataType.Type.INT128: 5, exp.DataType.Type.INT256: 6,
202
+ }
203
+
204
+ # The floating-point types: REAL, FLOAT and DOUBLE in any spelling.
205
+ _FLOATS = {exp.DataType.Type.FLOAT, exp.DataType.Type.DOUBLE, exp.DataType.Type.UDOUBLE}
206
+
207
+ # The digits of a number literal past which DuckDB's type for it is a DOUBLE.
208
+ _EXACT_LITERAL_DIGITS = 38
209
+
210
+
211
+ # Types whose equal values are identical: no collation (text has a comparison
212
+ # type only when compared by identity), no signed zero or NaN, no two
213
+ # spellings of one interval.
214
+ _IDENTITY_TYPES = {
215
+ *exp.DataType.INTEGER_TYPES, *exp.DataType.TEXT_TYPES,
216
+ exp.DataType.Type.DECIMAL, exp.DataType.Type.BOOLEAN, exp.DataType.Type.DATE, exp.DataType.Type.TIME,
217
+ exp.DataType.Type.TIMESTAMP, exp.DataType.Type.UUID,
218
+ # Timestamps without a zone, as each dialect spells them (DuckDB's TIMESTAMP is TIMESTAMPNTZ).
219
+ exp.DataType.Type.TIMESTAMPNTZ, exp.DataType.Type.TIMESTAMP_S, exp.DataType.Type.TIMESTAMP_MS, exp.DataType.Type.TIMESTAMP_NS,
220
+ exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME64,
221
+ }
222
+
223
+ _EXACT_NUMERIC_TYPES = {*exp.DataType.INTEGER_TYPES, exp.DataType.Type.DECIMAL}