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.
Files changed (73) hide show
  1. sqlassert/__init__.py +1 -2
  2. sqlassert/__main__.py +2 -131
  3. sqlassert/check.py +98 -16
  4. sqlassert/diagnostics.py +31 -7
  5. sqlassert/dialects.py +504 -27
  6. sqlassert/discovery/bigquery.py +3 -1
  7. sqlassert/discovery/databricks.py +25 -2
  8. sqlassert/discovery/duckdb.py +61 -23
  9. sqlassert/discovery/fetcher.py +170 -45
  10. sqlassert/discovery/information_schema.py +34 -5
  11. sqlassert/discovery/mysql.py +22 -1
  12. sqlassert/discovery/postgres.py +28 -12
  13. sqlassert/discovery/redshift.py +3 -2
  14. sqlassert/discovery/snowflake.py +3 -0
  15. sqlassert/discovery/trino.py +2 -2
  16. sqlassert/edits.py +240 -0
  17. sqlassert/hazards.py +735 -0
  18. sqlassert/ir/__init__.py +6 -1
  19. sqlassert/ir/convert/__init__.py +13 -0
  20. sqlassert/ir/convert/aggregation.py +439 -0
  21. sqlassert/ir/convert/builtins.py +140 -0
  22. sqlassert/ir/convert/expressions.py +572 -0
  23. sqlassert/ir/convert/joins.py +264 -0
  24. sqlassert/ir/convert/markers.py +249 -0
  25. sqlassert/ir/convert/parser.py +253 -0
  26. sqlassert/ir/convert/queries.py +259 -0
  27. sqlassert/ir/convert/schema.py +606 -0
  28. sqlassert/ir/convert/scopes.py +205 -0
  29. sqlassert/ir/convert/selects.py +337 -0
  30. sqlassert/ir/convert/shared.py +429 -0
  31. sqlassert/ir/convert/sources.py +432 -0
  32. sqlassert/ir/convert/subqueries.py +364 -0
  33. sqlassert/ir/convert/value_types.py +223 -0
  34. sqlassert/ir/convert/windows.py +275 -0
  35. sqlassert/ir/model.py +247 -66
  36. sqlassert/ir/names.py +63 -0
  37. sqlassert/main.py +3 -9
  38. sqlassert/properties.py +12 -1
  39. sqlassert/provenance.py +5 -1
  40. sqlassert/python_engine.py +167 -50
  41. sqlassert/reporting.py +36 -32
  42. sqlassert/rewrites.py +1591 -0
  43. sqlassert/rules/STYLEGUIDE.md +3 -2
  44. sqlassert/rules/causes/__init__.py +41 -0
  45. sqlassert/rules/causes/coverage.py +113 -0
  46. sqlassert/rules/causes/domain.py +123 -0
  47. sqlassert/rules/causes/joins.py +73 -0
  48. sqlassert/rules/causes/nulls.py +154 -0
  49. sqlassert/rules/causes/unique.py +523 -0
  50. sqlassert/rules/domain.py +123 -26
  51. sqlassert/rules/equality.py +153 -85
  52. sqlassert/rules/exactly_one.py +42 -2
  53. sqlassert/rules/foreign_key.py +15 -13
  54. sqlassert/rules/join_cardinality.py +302 -39
  55. sqlassert/rules/nullability.py +244 -35
  56. sqlassert/rules/uniqueness.py +513 -86
  57. sqlassert/rules/value_typing.py +337 -0
  58. sqlassert/sql_parse.py +224 -90
  59. sqlassert/suggest.py +132 -57
  60. sqlassert-0.4.1.dist-info/METADATA +235 -0
  61. sqlassert-0.4.1.dist-info/RECORD +69 -0
  62. sqlassert-0.4.1.dist-info/entry_points.txt +2 -0
  63. sqlassert-0.4.1.dist-info/top_level.txt +2 -0
  64. sqlassert_cli.py +130 -0
  65. sqlassert/improvements.py +0 -528
  66. sqlassert/ir/convert.py +0 -2377
  67. sqlassert/smells.py +0 -306
  68. sqlassert-0.3.1.dist-info/METADATA +0 -725
  69. sqlassert-0.3.1.dist-info/RECORD +0 -44
  70. sqlassert-0.3.1.dist-info/entry_points.txt +0 -2
  71. sqlassert-0.3.1.dist-info/top_level.txt +0 -1
  72. {sqlassert-0.3.1.dist-info → sqlassert-0.4.1.dist-info}/WHEEL +0 -0
  73. {sqlassert-0.3.1.dist-info → sqlassert-0.4.1.dist-info}/licenses/LICENSE +0 -0
sqlassert/ir/__init__.py CHANGED
@@ -1,8 +1,9 @@
1
1
  """Relational intermediate representation."""
2
2
 
3
- from sqlassert.ir.model import Aggregate, AggregateCall, Alias, And, AnyAggregate, AnyRelation, AnyScalar, Assertion, Builtin, BuiltinVariadic, Call, Coalesce, ColumnRef, Constant, Count, Distinct, Elements, Equality, Filter, InList, IsNotNull, IsNull, Join, JoinKind, Limit, NamedRelation, Node, NullLiteral, OpaqueExpression, OpaquePureFunction, OpaqueRelation, Or, OutputColumn, Program, Project, QualifyByPartition, RecursiveRelation, RelationExpr, RelationRole, ScalarExpr, SetOperation, SimpleCase, LiteralValue, SetOperator, children, conjuncts, determinants, injective_input, strict_inputs, total
3
+ from sqlassert.ir.model import Accumulation, Aggregate, AggregateCall, Alias, And, AnyAggregate, AnyRelation, AnyScalar, ArgumentTyping, Assertion, Builtin, BuiltinVariadic, Call, Coalesce, ColumnRef, Constant, Count, Distinct, Elements, Equality, Filter, InList, IsNotNull, IsNull, Join, JoinKind, Limit, NamedRelation, Node, NullLiteral, NullSafeEquality, OpaqueExpression, OpaquePureFunction, OpaqueRelation, Or, OutputColumn, Program, Project, QualifyByPartition, RecursiveRelation, RelationExpr, RelationRole, ScalarExpr, SetOperation, SimpleCase, ValuesList, ValueTyping, LiteralValue, SetOperator, children, conjuncts, determinants, injective_input, strict_inputs, total
4
4
 
5
5
  __all__ = [
6
+ "Accumulation",
6
7
  "Aggregate",
7
8
  "AggregateCall",
8
9
  "Alias",
@@ -32,6 +33,7 @@ __all__ = [
32
33
  "NamedRelation",
33
34
  "Node",
34
35
  "NullLiteral",
36
+ "NullSafeEquality",
35
37
  "OpaqueExpression",
36
38
  "OpaquePureFunction",
37
39
  "OpaqueRelation",
@@ -46,6 +48,9 @@ __all__ = [
46
48
  "ScalarExpr",
47
49
  "SetOperation",
48
50
  "SetOperator",
51
+ "ValuesList",
52
+ "ValueTyping",
53
+ "ArgumentTyping",
49
54
  "SimpleCase",
50
55
  "children",
51
56
  "conjuncts",
@@ -0,0 +1,13 @@
1
+ """Link a parsed SQL program into the framework-independent relational IR.
2
+
3
+ Declaration and scope discovery happens before lowering. This gives table,
4
+ view, and CTE references compiler-like symbol resolution: every occurrence is
5
+ a fresh Alias, while all occurrences share one memoized NamedRelation.
6
+
7
+ The package lowers by responsibility: `parser.IrParser` is the driver, and
8
+ each mixin it inherits lowers one part of the SQL.
9
+ """
10
+
11
+ from sqlassert.ir.convert.parser import IrConversionResult, IrParser
12
+
13
+ __all__ = ["IrConversionResult", "IrParser"]
@@ -0,0 +1,439 @@
1
+ """Grouping: GROUP BY and its aggregates, HAVING, and DISTINCT."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from typing import TYPE_CHECKING
7
+
8
+ from sqlglot import Expr, exp
9
+
10
+ from sqlassert import ir
11
+ from sqlassert.ir.convert.builtins import dialect_builtins
12
+ from sqlassert.ir.convert.shared import (
13
+ _Binding, _Lowered, _placed, _pass_output_columns, _source_line, _and, _filter_conjuncts, _unsupported_grouping, _only_star, _matching_output,
14
+ _unaliased, _NOT_A_FUNCTION_OF_ITS_COLUMNS,
15
+ )
16
+
17
+ if TYPE_CHECKING:
18
+ from sqlassert.ir.convert.parser import IrParser
19
+
20
+
21
+ class _Aggregation:
22
+ def _lower_aggregate(self: IrParser, lowered: _Lowered, select: exp.Select, keys: list[Expr]) -> ir.RelationExpr | None:
23
+ """`select` grouped by `keys`; [] is one group, one row however many
24
+ rows its input has. HAVING filters the groups (`_lower_having`). A
25
+ key not selected, or an aggregate only HAVING reads, is a hidden
26
+ output of the Aggregate, which a Project then drops: a key still
27
+ splits the groups, and HAVING may read either.
28
+
29
+ An item computed over aggregates (`max(sal) + 1`) is computed by that
30
+ Project from the Aggregate's outputs: each repeatable aggregate call
31
+ it contains is one output, shared with the item or HAVING conjunct
32
+ written the same, and so is each column outside them. HAVING's facts
33
+ about `max(sal)` then hold of the item's operand."""
34
+ if _unsupported_grouping(select) is not None:
35
+ return None
36
+ if select.args.get("where") is not None:
37
+ lowered = self._filter(lowered, select.args["where"])
38
+
39
+ items: list[Expr] = list(select.expressions)
40
+ selected_names = {item.alias_or_name.lower() for item in items}
41
+ grouped_items: set[int] = set()
42
+ matched: list[Expr] = []
43
+ for group_expression in keys:
44
+ item = _matching_grouping_output(group_expression, select.expressions) or _same_column_alias(group_expression, select.expressions)
45
+ if item is None:
46
+ if (isinstance(group_expression, exp.Literal) and group_expression.is_int) or (
47
+ isinstance(group_expression, exp.Column) and not group_expression.table
48
+ and group_expression.name.lower() in selected_names
49
+ ) or group_expression.find(exp.AggFunc, exp.Window, exp.Subquery) is not None:
50
+ return None # A position out of range, a name that may be a select alias, or not a key.
51
+ item = exp.alias_(group_expression.copy(), f"{HIDDEN_GROUPING}{len(items)}")
52
+ items.append(item)
53
+ grouped_items.add(id(item))
54
+ matched.append(item)
55
+ computed = {id(item) for item in select.expressions if self._computed_over_aggregates(_unaliased(item))}
56
+ if any(id(item) in computed for item in matched):
57
+ return None # A grouping position naming an item that aggregates.
58
+ items = [item for item in items if id(item) not in computed]
59
+ # Each part of a computed item is an output: an item or hidden item
60
+ # written the same, when repeatable, else a hidden item of its own.
61
+ parts: dict[int, Expr] = {}
62
+ for item in select.expressions:
63
+ if id(item) not in computed:
64
+ continue
65
+ for part in _aggregate_parts(_unaliased(item)):
66
+ text = part.sql(dialect=self.dialect)
67
+ same = next((
68
+ other for other in items if self._repeatable(part) and _unaliased(other).sql(dialect=self.dialect) == text
69
+ ), None)
70
+ if same is None:
71
+ same = exp.alias_(part.copy(), f"{HIDDEN_AGGREGATE}{len(items)}")
72
+ items.append(same)
73
+ parts[id(part)] = same
74
+ having = select.args.get("having")
75
+ if having is not None:
76
+ # An aggregate HAVING reads that no item writes: a hidden output,
77
+ # like a grouping key not selected, that `_lower_having` reads.
78
+ written = {_unaliased(item).sql(dialect=self.dialect) for item in items}
79
+ for call in _outermost_aggregate_calls(having.this):
80
+ text = call.sql(dialect=self.dialect)
81
+ if text not in written and self._repeatable(call):
82
+ written.add(text)
83
+ items.append(exp.alias_(call.copy(), f"{HIDDEN_AGGREGATE}{len(items)}"))
84
+
85
+ output_columns = self._aggregate_output_columns(items, lowered, grouped_items)
86
+ grouping_outputs = [output_columns[next(index for index, item in enumerate(items) if item is match)] for match in matched]
87
+ # Each call of the items, then each call only HAVING writes.
88
+ written_calls = [
89
+ call for item in select.expressions for call in item.find_all(exp.AggFunc)
90
+ if call.find_ancestor(exp.Window, exp.Select) is select
91
+ ]
92
+ if having is not None:
93
+ texts = {call.sql(dialect=self.dialect) for call in written_calls}
94
+ for call in having.find_all(exp.AggFunc):
95
+ text = call.sql(dialect=self.dialect)
96
+ if call.find_ancestor(exp.Window, exp.Select) is select and text not in texts:
97
+ texts.add(text)
98
+ written_calls.append(call)
99
+ calls = tuple(
100
+ ir.AggregateCall(
101
+ origin=self._origin(call), description=call.sql(dialect=self.dialect),
102
+ arguments=tuple(
103
+ self._lower_expression(argument, lowered.bindings, schema_complete=lowered.relation.is_schema_complete)
104
+ for argument in _aggregate_arguments(call)
105
+ ),
106
+ )
107
+ for call in written_calls
108
+ )
109
+ aggregate = ir.Aggregate(
110
+ origin=_placed(self._origin(select), select.args.get("group")), output_columns=output_columns, is_schema_complete=True, input=lowered.relation,
111
+ grouping_outputs=tuple(grouping_outputs), calls=calls,
112
+ )
113
+ relation: ir.RelationExpr = aggregate if having is None else self._lower_having(aggregate, items, having)
114
+ if len(items) == len(select.expressions) and all(item is written for item, written in zip(items, select.expressions)):
115
+ return relation
116
+ origin = self._origin(select)
117
+ position = {id(item): index for index, item in enumerate(items)}
118
+ selected: list[ir.OutputColumn] = []
119
+ for item in select.expressions:
120
+ if id(item) not in computed:
121
+ selected.extend(_pass_output_columns((relation.output_columns[position[id(item)]],), origin))
122
+ continue
123
+ values = {
124
+ part: ir.ColumnRef(origin=self._origin(other), column=relation.output_columns[position[id(other)]])
125
+ for part, other in parts.items()
126
+ }
127
+ self._grouped_values.update(values)
128
+ try:
129
+ value = self._lower_expression(_unaliased(item), (), schema_complete=True)
130
+ finally:
131
+ for key in values:
132
+ del self._grouped_values[key]
133
+ selected.append(ir.OutputColumn(origin=self._placed(item), name=item.alias_or_name, scalar_expr=value))
134
+ return ir.Project(origin=origin, output_columns=tuple(selected), is_schema_complete=True, input=relation)
135
+
136
+ def _lower_having(self: IrParser, aggregate: ir.Aggregate, items: list[Expr], having: exp.Having) -> ir.Filter:
137
+ """HAVING as a Filter of the grouped rows. A condition reads the
138
+ aggregate's output columns, so each part of it written as a select
139
+ item is that item's column (`count(*) > 1` beside `count(*) AS c` is
140
+ `c > 1`), and so is each aggregate no item writes, a hidden item
141
+ (`_lower_aggregate`). A conjunct still reading anything else (a column
142
+ neither grouped nor aggregated, an aggregate whose repeated text may
143
+ differ, a subquery) is opaque: it removes groups for a reason not
144
+ known, which keeps every fact that holds of the groups, and states
145
+ nothing of its own: no selected column can show it."""
146
+ qualifier = "__having"
147
+ bindings = tuple(_Binding(qualifier, f"c{index}", column) for index, column in enumerate(aggregate.output_columns))
148
+ written: dict[str, int] = {}
149
+ for index, item in enumerate(items):
150
+ expression = _unaliased(item)
151
+ if self._repeatable(expression):
152
+ written.setdefault(expression.sql(dialect=self.dialect), index)
153
+
154
+ def selected(node: Expr) -> Expr:
155
+ index = written.get(node.sql(dialect=self.dialect))
156
+ return node if index is None or isinstance(node, exp.Literal) else exp.column(f"c{index}", table=qualifier)
157
+
158
+ origin = self._origin(having)
159
+ parts: list[ir.ScalarExpr] = []
160
+ for conjunct in _filter_conjuncts(having.this):
161
+ rewritten = conjunct.copy().transform(selected)
162
+ unknown = any(
163
+ column.table != qualifier for column in rewritten.find_all(exp.Column)
164
+ ) or rewritten.find(exp.AggFunc, exp.Subquery, exp.Window) is not None
165
+ if unknown:
166
+ parts.append(ir.OpaqueExpression(origin=self._origin(conjunct), description=conjunct.sql(dialect=self.dialect)))
167
+ else:
168
+ parts.append(self._lower_expression(rewritten, bindings, schema_complete=True, line=_source_line(conjunct)))
169
+ return ir.Filter(
170
+ origin=origin, output_columns=_pass_output_columns(aggregate.output_columns, origin), is_schema_complete=True,
171
+ input=aggregate, predicate=_and(tuple(parts), origin),
172
+ )
173
+
174
+ def _computed_over_aggregates(self: IrParser, expression: Expr) -> bool:
175
+ """Whether a grouped select item computes a value from aggregate
176
+ calls, rather than being one: `max(sal) + 1`, not `max(sal)`. One
177
+ with a window or a subquery stays an Aggregate output."""
178
+ return (
179
+ not _is_aggregate_call(expression) and bool(_outermost_aggregate_calls(expression))
180
+ and expression.find(exp.Window, exp.Query, exp.Subquery) is None
181
+ )
182
+
183
+ def _repeatable(self: IrParser, expression: Expr) -> bool:
184
+ """Whether every occurrence of `expression`'s SQL text in one grouped
185
+ select has one value per group. Repeated text need not denote the same
186
+ evaluation: only modelled pure expressions and aggregates over pure
187
+ inputs qualify, not a literal (which a name may shadow)."""
188
+ return not isinstance(expression, exp.Literal) and all(
189
+ not isinstance(node, _NOT_A_FUNCTION_OF_ITS_COLUMNS)
190
+ and (not isinstance(node, exp.Func) or type(node) in dialect_builtins(self.semantics))
191
+ or isinstance(node, exp.Count | exp.Sum | exp.Min | exp.Max | exp.Avg | exp.Star)
192
+ for node in expression.walk()
193
+ )
194
+
195
+ def _lower_distinct(self: IrParser, lowered: _Lowered, select: exp.Select, items: list[Expr]) -> ir.Distinct | None:
196
+ distinct = select.args.get("distinct")
197
+ if distinct is None or select.args.get("having") is not None or _only_star(items):
198
+ return None
199
+ if select.args.get("where") is not None:
200
+ lowered = self._filter(lowered, select.args["where"])
201
+ return ir.Distinct(
202
+ origin=self._placed(select), output_columns=self._selected_output_columns(items, lowered),
203
+ is_schema_complete=True, input=lowered.relation,
204
+ )
205
+
206
+ def _aggregate_output_columns(self: IrParser, items: list[Expr], source: _Lowered, grouped_items: set[int]) -> tuple[ir.OutputColumn, ...]:
207
+ """Each item of a grouped select. A column outside every aggregate must
208
+ be one the grouping determines (`_grouping_determined`): any other
209
+ (SQLite's bare column) makes its item opaque (ADR 0006)."""
210
+ grouped = {
211
+ id(item): self._lower_expression(
212
+ item.this if isinstance(item, exp.Alias) else item, source.bindings, schema_complete=source.relation.is_schema_complete,
213
+ )
214
+ for item in items if id(item) in grouped_items
215
+ }
216
+ determined = self._grouping_determined({
217
+ lowered.column for lowered in grouped.values() if isinstance(lowered, ir.ColumnRef)
218
+ }, source.relation)
219
+ # Grouped by nothing (no grouped items), the one row exists even
220
+ # over no input rows, where an aggregate of its values is NULL.
221
+ empty = not grouped_items
222
+ output_columns: list[ir.OutputColumn] = []
223
+ for item in items:
224
+ expression = item.this if isinstance(item, exp.Alias) else item
225
+ lowered = grouped[id(item)] if id(item) in grouped else self._lower_grouped(expression, source, determined, empty=empty)
226
+ if id(item) not in grouped_items and _reads_ungrouped_column(lowered, determined):
227
+ lowered = ir.OpaqueExpression(origin=self._origin(expression), description=expression.sql(dialect=self.dialect))
228
+ self._unsupported.append((lowered, "a column neither grouped nor inside an aggregate"))
229
+ if id(item) in grouped_items:
230
+ # A grouping key is typed like a projected item: `_output_column`.
231
+ output_columns.append(self._output_column(item, expression, lowered))
232
+ else:
233
+ output_columns.append(ir.OutputColumn(origin=self._placed(item), name=item.alias_or_name, scalar_expr=lowered))
234
+ return tuple(output_columns)
235
+
236
+ def _lower_grouped(
237
+ self: IrParser, expression: Expr, source: _Lowered, determined: Callable[[ir.OutputColumn], bool], *, empty: bool,
238
+ ) -> ir.ScalarExpr:
239
+ """`expression`, computed once per group of `source`'s rows: each
240
+ aggregate call is its value (`_aggregate_value`), and each column
241
+ outside them the grouping determines is one value per group, an
242
+ AnyAggregate. Any other column is left as it is, for the caller to
243
+ reject; windows and subqueries are not entered."""
244
+ values: dict[int, ir.ScalarExpr] = {}
245
+ pending: list[Expr] = [expression]
246
+ while pending:
247
+ node = pending.pop()
248
+ if isinstance(node, exp.Window | exp.Query | exp.Subquery):
249
+ continue
250
+ if _is_aggregate_call(node):
251
+ value = self._aggregate_value(node, source, empty=empty)
252
+ if value is not None:
253
+ values[id(node)] = value
254
+ continue
255
+ if isinstance(node, exp.Column):
256
+ column = self._lower_expression(node, source.bindings, schema_complete=source.relation.is_schema_complete)
257
+ if isinstance(column, ir.ColumnRef) and determined(column.column):
258
+ values[id(node)] = ir.AnyAggregate(origin=column.origin, input=column, empty=empty)
259
+ continue
260
+ pending.extend(node.iter_expressions())
261
+ self._grouped_values.update(values)
262
+ try:
263
+ return self._lower_expression(expression, source.bindings, schema_complete=source.relation.is_schema_complete)
264
+ finally:
265
+ for key in values:
266
+ del self._grouped_values[key]
267
+
268
+ def _aggregate_value(self: IrParser, call: Expr, source: _Lowered, *, empty: bool) -> ir.ScalarExpr | None:
269
+ """The value of an aggregate `call` over a group of `source`'s rows,
270
+ or None when it is not modelled. `min`, `max` and `any_value` pick a
271
+ value of their argument (AnyAggregate), `sum` and `avg` accumulate
272
+ its non-null values where that is never NULL (Accumulation,
273
+ `checked_sum`), and `count` is never NULL. One with FILTER may
274
+ see none of the group's rows: NULL, but for count."""
275
+ if isinstance(call, exp.Filter):
276
+ call, empty = call.this, True
277
+ origin = self._origin(call)
278
+
279
+ def lower(argument: Expr) -> ir.ScalarExpr:
280
+ return self._lower_expression(argument, source.bindings, schema_complete=source.relation.is_schema_complete)
281
+
282
+ if isinstance(call, exp.Count):
283
+ return ir.Count(origin=origin, description=call.sql(dialect=self.dialect))
284
+ if (argument := _picked_argument(call)) is not None:
285
+ # One of its argument's values on some row of the group.
286
+ return ir.AnyAggregate(origin=origin, input=lower(argument), empty=empty)
287
+ if (argument := _aggregate_argument(call, (exp.Sum, exp.Avg), distinct=True)) is not None and self.semantics.checked_sum:
288
+ # Elsewhere an overflow or NaN over non-null values may be NULL.
289
+ return ir.Accumulation(origin=origin, input=lower(argument), empty=empty)
290
+ return None
291
+
292
+ def _grouping_determined(self: IrParser, grouping: set[ir.OutputColumn], relation: ir.RelationExpr) -> Callable[[ir.OutputColumn], bool]:
293
+ """Whether its `grouping` columns determine a column of `relation`: one of those,
294
+ and every column of a table occurrence whose declared primary key
295
+ they include (SQL's functional dependence on a key, which
296
+ PostgreSQL and MySQL accept)."""
297
+ occurrences: dict[ir.OutputColumn, ir.Alias] = {}
298
+ pending: list[ir.RelationExpr] = [relation]
299
+ while pending:
300
+ node = pending.pop()
301
+ if isinstance(node, ir.Alias):
302
+ occurrences.update((output, node) for output in node.output_columns)
303
+ else:
304
+ pending.extend(child for child in ir.children(node) if isinstance(child, ir.RelationExpr))
305
+
306
+ def occurrence(column: ir.OutputColumn) -> tuple[ir.Alias | None, ir.OutputColumn]:
307
+ while column not in occurrences and isinstance(column.scalar_expr, ir.ColumnRef):
308
+ column = column.scalar_expr.column
309
+ return occurrences.get(column), column
310
+
311
+ keyed: set[ir.Alias] = set()
312
+ grouped_names: dict[ir.Alias, set[str]] = {}
313
+ for column in grouping:
314
+ alias, output = occurrence(column)
315
+ if alias is not None:
316
+ grouped_names.setdefault(alias, set()).add(output.name.lower())
317
+ for alias, names in grouped_names.items():
318
+ symbol = next((symbol for symbol, named in self._named_relations.items() if named is alias.source), None)
319
+ key = None if symbol is None else self._primary_key(symbol)
320
+ if key and {name.lower() for name in key} <= names:
321
+ keyed.add(alias)
322
+ return lambda column: column in grouping or occurrence(column)[0] in keyed
323
+
324
+ # A grouping key not selected, kept as a hidden Aggregate output: no SQL name can match it.
325
+ HIDDEN_GROUPING = "\0grouping"
326
+
327
+ # An aggregate HAVING reads that no item writes, a hidden Aggregate output too.
328
+ HIDDEN_AGGREGATE = "\0aggregate"
329
+
330
+
331
+ def _same_column_alias(group_expression: Expr, items: list[Expr]) -> Expr | None:
332
+ """The item `GROUP BY x` names when `x` is both the item's alias and the
333
+ column it selects (`t.x AS x`): either reading of the name is that column."""
334
+ if not isinstance(group_expression, exp.Column) or group_expression.table:
335
+ return None
336
+ name = group_expression.name.lower()
337
+ return next((
338
+ item for item in items
339
+ if isinstance(item, exp.Alias) and item.alias.lower() == name and isinstance(item.this, exp.Column) and item.this.name.lower() == name
340
+ ), None)
341
+
342
+
343
+ def _matching_grouping_output(group_expression: Expr, items: list[Expr]) -> Expr | None:
344
+ if isinstance(group_expression, exp.Literal) and group_expression.is_int:
345
+ position = int(group_expression.this)
346
+ return items[position - 1] if 1 <= position <= len(items) else None
347
+ return _matching_output(group_expression, items)
348
+
349
+
350
+ def _aggregate_argument(expression: Expr, kinds: tuple[type[exp.AggFunc], ...], *, distinct: bool = False) -> Expr | None:
351
+ """The one argument of a plain call of one of `kinds`: no FILTER, window,
352
+ or other argument (DuckDB's `max(x, 3)` is a list), and no DISTINCT
353
+ unless `distinct` allows one argument's."""
354
+ if type(expression) not in kinds or isinstance(expression.this, exp.Star) or expression.this is None:
355
+ return None
356
+ if any(value for key, value in expression.args.items() if key != "this"):
357
+ return None
358
+ if isinstance(expression.this, exp.Distinct):
359
+ arguments = expression.this.expressions
360
+ return arguments[0] if distinct and len(arguments) == 1 and not expression.this.args.get("on") else None
361
+ return expression.this
362
+
363
+
364
+ def _picked_argument(expression: Expr) -> Expr | None:
365
+ """The argument of an aggregate whose value is the argument's value on
366
+ some row of the group: `min` and `max` (a non-null one when there is one;
367
+ of distinct values or not, the same) and `any_value`, whatever its NULL
368
+ treatment (DuckDB parses its own as IGNORE NULLS). Not BigQuery's
369
+ `any_value(x HAVING MAX y)`, opaque."""
370
+ if isinstance(expression, (exp.IgnoreNulls, exp.RespectNulls)):
371
+ expression = expression.this
372
+ argument = _aggregate_argument(expression, (exp.Min, exp.Max), distinct=True) or _aggregate_argument(expression, (exp.AnyValue,))
373
+ return None if isinstance(argument, exp.HavingMax) else argument
374
+
375
+
376
+ def _outermost_aggregate_calls(expression: Expr) -> list[Expr]:
377
+ """The aggregate calls of `expression` not inside another, a window or a
378
+ subquery, with the FILTER or NULL treatment written on them."""
379
+ calls: list[Expr] = []
380
+ pending: list[Expr] = [expression]
381
+ while pending:
382
+ node = pending.pop()
383
+ if _is_aggregate_call(node):
384
+ calls.append(node)
385
+ elif not isinstance(node, exp.Window | exp.Query | exp.Subquery):
386
+ pending.extend(node.iter_expressions())
387
+ return calls
388
+
389
+
390
+ def _aggregate_parts(expression: Expr) -> list[Expr]:
391
+ """The aggregate calls of a grouped select item not inside another, and
392
+ its columns outside them: what it is computed from, per group."""
393
+ parts: list[Expr] = []
394
+ pending: list[Expr] = [expression]
395
+ while pending:
396
+ node = pending.pop()
397
+ if _is_aggregate_call(node) or isinstance(node, exp.Column):
398
+ parts.append(node)
399
+ else:
400
+ pending.extend(node.iter_expressions())
401
+ return parts
402
+
403
+
404
+ def _is_aggregate_call(node: Expr) -> bool:
405
+ """An aggregate call, with the FILTER or NULL treatment written on it."""
406
+ while isinstance(node, exp.Filter | exp.IgnoreNulls | exp.RespectNulls | exp.WithinGroup):
407
+ node = node.this
408
+ return isinstance(node, exp.AggFunc)
409
+
410
+
411
+ def _reads_ungrouped_column(lowered: ir.ScalarExpr, determined: Callable[[ir.OutputColumn], bool]) -> bool:
412
+ """Whether `lowered`, an item of a grouped select, reads a column outside
413
+ every aggregate that the grouping columns do not determine (`determined`).
414
+ Windows and subqueries lower opaque, and an aggregate's argument is read
415
+ per row, so every other column `lowered` reads is outside them."""
416
+ pending: list[ir.ScalarExpr] = [lowered]
417
+ while pending:
418
+ node = pending.pop()
419
+ if isinstance(node, ir.ColumnRef):
420
+ if not determined(node.column):
421
+ return True
422
+ continue
423
+ if isinstance(node, ir.AnyAggregate | ir.Accumulation | ir.Count):
424
+ continue
425
+ pending.extend(child for child in ir.children(node) if isinstance(child, ir.ScalarExpr))
426
+ return False
427
+
428
+
429
+ def _aggregate_arguments(call: exp.AggFunc) -> list[Expr]:
430
+ """The value arguments of an aggregate call: none for `count(*)`, the
431
+ listed ones under DISTINCT."""
432
+ this = call.this
433
+ if this is None or isinstance(this, exp.Star):
434
+ return []
435
+ if isinstance(this, exp.Distinct):
436
+ return list(this.expressions)
437
+ if not isinstance(this, Expr): # An unknown call's name (`main.max(x)` in ClickHouse).
438
+ return list(call.expressions)
439
+ return [this, *call.expressions]
@@ -0,0 +1,140 @@
1
+ """The Builtins a dialect's functions and operators lower to
2
+ (`dialect_builtins`): strictness, totality and injectivity."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from functools import cache
7
+ from typing import assert_never
8
+
9
+ from sqlglot import Expr, exp
10
+
11
+ from sqlassert import ir
12
+ from sqlassert.dialects import DialectSemantics
13
+
14
+
15
+ # The function each hash node is, as `DialectSemantics.hash_functions` names it.
16
+ _HASH_NAMES = {
17
+ "MD5": "md5", "SHA": "sha1", "SHA2": "sha256", "MD5Digest": "md5 digest", "SHA1Digest": "sha1 digest", "SHA2Digest": "sha256 digest",
18
+ }
19
+
20
+
21
+ @cache
22
+ def dialect_builtins(meaning: DialectSemantics) -> dict[type[Expr], tuple[ir.Builtin, tuple[str, ...]]]:
23
+ """Each modelled Builtin, by the SQLGlot node it lowers from (exactly that
24
+ type: TRY_CAST, a subclass of CAST, may be NULL for a value), with the
25
+ argument keys its parameters come from, a list key in place of a variadic
26
+ Builtin's repeated parameter, as a dialect's semantics define it
27
+ (`dialects.py`; `scripts/certify_dialects.py` probes each Builtin fact).
28
+
29
+ Comparisons, LIKE, NOT, BETWEEN and the bitwise operators are never NULL
30
+ for non-null arguments where a failed implicit cast raises (`casts_raise`;
31
+ in Hive `1 < 'x'` is NULL). Arithmetic and CAST only
32
+ where they raise an error rather than return NULL (`checked_arithmetic`:
33
+ SQLite turns a NaN into NULL, MySQL a bad date CAST), and division and
34
+ remainder only where division by zero raises too (`checked_division`).
35
+ A CAST from JSON is not total anywhere (`convert._is_json`): JSON `null`
36
+ is a value that casts to NULL. `+`, `-` and negation are injective in every
37
+ dialect: values are assumed to stay in range (ADR 0007). `||`, `concat()`, `concat_ws()`, `greatest()`, `least()` and
38
+ subscripts (`xs[1]`) as each dialect treats NULL (MySQL's `||` is OR)."""
39
+ checked = meaning.checked_arithmetic
40
+ casts = meaning.casts_raise
41
+
42
+ def builtin(name: str, arity: int, *, total: bool = True, injective: bool = False) -> ir.Builtin:
43
+ return ir.Builtin(name=name, strict=(True,) * arity, total=(True,) * arity if total else None, injective=injective)
44
+
45
+ binary = {
46
+ exp.NEQ: "<>", exp.GT: ">", exp.GTE: ">=", exp.LT: "<", exp.LTE: "<=", exp.Like: "LIKE", exp.ILike: "ILIKE",
47
+ exp.BitwiseAnd: "&", exp.BitwiseOr: "|", exp.BitwiseXor: "^", exp.BitwiseLeftShift: "<<", exp.BitwiseRightShift: ">>",
48
+ }
49
+ division = {exp.Div: "/", exp.IntDiv: "//", exp.Mod: "%"}
50
+ builtins: dict[type[Expr], tuple[ir.Builtin, tuple[str, ...]]] = {
51
+ **{node: (builtin(name, 2, total=casts), ("this", "expression")) for node, name in binary.items()},
52
+ exp.Mul: (builtin("*", 2, total=checked), ("this", "expression")),
53
+ **{node: (builtin(name, 2, total=meaning.checked_division), ("this", "expression")) for node, name in division.items()},
54
+ **{node: (builtin(name, 2, total=checked, injective=True), ("this", "expression")) for node, name in {exp.Add: "+", exp.Sub: "-"}.items()},
55
+ exp.Neg: (builtin("unary -", 1, total=checked, injective=True), ("this",)),
56
+ exp.Not: (builtin("NOT", 1, total=casts), ("this",)),
57
+ exp.BitwiseNot: (builtin("~", 1, total=casts), ("this",)),
58
+ exp.Cast: (builtin("CAST", 1, total=checked), ("this",)),
59
+ # `1 BETWEEN NULL AND 0` is FALSE.
60
+ exp.Between: (ir.Builtin(name="BETWEEN", strict=(True, False, False), total=(True, True, True) if casts else None, injective=False), ("this", "low", "high")),
61
+ # Text functions take any value as text, so no cast fails. `trim(' ')`
62
+ # is '', which is NULL where '' is.
63
+ exp.Lower: (builtin("lower", 1), ("this",)),
64
+ exp.Upper: (builtin("upper", 1), ("this",)),
65
+ exp.Length: (builtin("length", 1), ("this",)),
66
+ exp.Trim: (builtin("trim", 1, total=not meaning.empty_string_is_null), ("this",)),
67
+ # A number read from bad text is an error only where a bad CAST is
68
+ # (SQLite's `floor('x')` is NULL though its comparisons raise).
69
+ exp.Abs: (builtin("abs", 1, total=checked), ("this",)),
70
+ exp.Floor: (builtin("floor", 1, total=checked), ("this",)),
71
+ exp.Ceil: (builtin("ceil", 1, total=checked), ("this",)),
72
+ # NULL when its arguments are equal; NULL only through the first otherwise.
73
+ exp.Nullif: (ir.Builtin(name="nullif", strict=(True, False), total=None, injective=False), ("this", "expression")),
74
+ }
75
+ for node in meaning.hash_functions:
76
+ builtins[getattr(exp, node)] = (builtin(_HASH_NAMES[node], 1), ("this",))
77
+ match meaning.pipes:
78
+ case "strict":
79
+ builtins[exp.DPipe] = (builtin("||", 2), ("this", "expression"))
80
+ case "lenient":
81
+ builtins[exp.DPipe] = (ir.Builtin(name="||", strict=(False, False), total=(True, True), injective=False), ("this", "expression"))
82
+ case None:
83
+ pass
84
+ case _:
85
+ assert_never(meaning.pipes)
86
+ match meaning.concat:
87
+ case "strict":
88
+ builtins[exp.Concat] = (
89
+ ir.BuiltinVariadic(name="concat", strict=(), total=(), injective=False, repeated_strict=True, repeated_total=True), ("expressions",),
90
+ )
91
+ case "skips-null":
92
+ # `concat(NULL)` is ''.
93
+ builtins[exp.Concat] = (
94
+ ir.BuiltinVariadic(name="concat", strict=(), total=(), injective=False, repeated_strict=False, repeated_total=False), ("expressions",),
95
+ )
96
+ case None:
97
+ pass
98
+ case _:
99
+ assert_never(meaning.concat)
100
+ match meaning.greatest:
101
+ case "skips-null":
102
+ # NULL only when every argument is: `greatest(NULL, 1)` is 1.
103
+ for node, name in {exp.Greatest: "greatest", exp.Least: "least"}.items():
104
+ builtins[node] = (
105
+ ir.BuiltinVariadic(
106
+ name=name, strict=(False,), total=None, injective=False, repeated_strict=False, repeated_total=False, skips_null=True,
107
+ ),
108
+ ("this", "expressions"),
109
+ )
110
+ case "strict":
111
+ # NULL when any argument is: `greatest(NULL, 1)` is NULL.
112
+ for node, name in {exp.Greatest: "greatest", exp.Least: "least"}.items():
113
+ builtins[node] = (
114
+ ir.BuiltinVariadic(name=name, strict=(True,), total=None, injective=False, repeated_strict=True, repeated_total=False),
115
+ ("this", "expressions"),
116
+ )
117
+ case None:
118
+ pass
119
+ case _:
120
+ assert_never(meaning.greatest)
121
+ if meaning.subscript_strict:
122
+ # NULL for a NULL list, and for an index out of range or a NULL element.
123
+ builtins[exp.Bracket] = (ir.Builtin(name="[]", strict=(True, False), total=None, injective=False), ("this", "expressions"))
124
+ match meaning.concat_ws:
125
+ case "strict":
126
+ builtins[exp.ConcatWs] = (
127
+ ir.BuiltinVariadic(name="concat_ws", strict=(True,), total=(True,), injective=False, repeated_strict=True, repeated_total=True),
128
+ ("expressions",),
129
+ )
130
+ case "skips-null":
131
+ # NULL values are skipped: `concat_ws(',', NULL)` is ''.
132
+ builtins[exp.ConcatWs] = (
133
+ ir.BuiltinVariadic(name="concat_ws", strict=(True,), total=(True,), injective=False, repeated_strict=False, repeated_total=False),
134
+ ("expressions",),
135
+ )
136
+ case None:
137
+ pass
138
+ case _:
139
+ assert_never(meaning.concat_ws)
140
+ return builtins