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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sqlassert/smells.py DELETED
@@ -1,306 +0,0 @@
1
- """Low-level suggestions: code smells, from the Kossmann et al. 2022 triage (issue 15).
2
-
3
- A Smell is not a rewrite: the SQL may be what its author meant. It names a
4
- place where the result depends on something the SQL does not pin down, and
5
- the proof that would have pinned it, which failed:
6
-
7
- - `LIMIT` or `OFFSET` whose `ORDER BY` does not strictly determine every
8
- selected column (or that has no `ORDER BY`): rows tied on the sort keys come
9
- in an arbitrary order, so which rows are kept may change from run to run
10
- (Kossmann's "unstable sorting", read the other way round).
11
- - An aggregate over a join that can repeat the rows its argument comes from
12
- (issue 41): a fan trap when the join is many to many, a chasm trap when it
13
- is one to many and the argument is on the side with one row per key. Every
14
- aggregate counts, `min` and `max` included: the join is wrong either way.
15
- `count(*)` has no argument, so only a many-to-many join is a trap for it.
16
- Silent when the input whose rows are repeated has no known Unique Set.
17
- - A join equality between text and another declared type: the text is cast,
18
- so different strings may match one value (`'01'` and `'1'` both equal 1),
19
- and no cardinality is proved across it. Write the cast explicitly.
20
- - A scalar subquery not proved to return at most one row (issue 38): more
21
- than one is a runtime error. Uncorrelated, its body must have at most one
22
- row; correlated, the columns its WHERE binds must reach its Row Identity.
23
-
24
- A smell is reported only when sqlassert sees the whole Select Expression; an
25
- `ORDER BY` key it cannot map to a selected column keeps it silent.
26
- """
27
-
28
- from __future__ import annotations
29
-
30
- from dataclasses import dataclass
31
- from enum import Enum
32
- from typing import ClassVar
33
-
34
- from sqlglot import exp
35
-
36
- from sqlassert import ir
37
- from sqlassert.improvements import Level, _syntax_at_sites
38
- from sqlassert.provenance import AttachmentSite
39
- from sqlassert.python_engine import Arena, Result
40
- from sqlassert.rules.equality import _binary_text, _comparison_type, _exact_arithmetic, _identity_comparison
41
- from sqlassert.rules.join_cardinality import _at_most_one_match, many_to_one_join, one_to_many_join, unique_join
42
- from sqlassert.rules.uniqueness import _closure, _reaches_row_identity, minimal_keys
43
- from sqlassert.sql_parse import ParsedProgram
44
-
45
-
46
- class Concern(Enum):
47
- ARBITRARY_LIMIT = "Arbitrary LIMIT"
48
- FAN_TRAP = "Fan trap"
49
- CHASM_TRAP = "Chasm trap"
50
- SCALAR_SUBQUERY = "Scalar subquery"
51
- IMPLICIT_CAST = "Implicit cast"
52
-
53
-
54
- @dataclass(frozen=True)
55
- class Smell:
56
- """A place whose result the SQL leaves unspecified, with the failed proof."""
57
-
58
- site: AttachmentSite
59
- concern: Concern
60
- message: str
61
- evidence: Result
62
- level: ClassVar[Level] = Level.LOW
63
-
64
-
65
- def smells(ast: ParsedProgram, program: ir.Program, arena: Arena) -> list[Smell]:
66
- """Every Smell in `program`, in source order. `arena` must be active."""
67
- syntax = _syntax_at_sites(ast)
68
- reachable = set(program.nodes())
69
- found: list[Smell] = []
70
- join_labels = {relation: site.label for site, relation in program.attachment_sites if isinstance(relation, ir.Join)}
71
- sort_keys = dict(program.sort_keys)
72
- for site, relation in program.attachment_sites:
73
- node = syntax.get((site.offset, site.trailing))
74
- if isinstance(relation, ir.Limit) and relation in reachable and isinstance(node, exp.Select):
75
- found.extend(_arbitrary_limit(site, relation, sort_keys.get(site)))
76
- if isinstance(relation, ir.Join) and relation in reachable and not site.trailing:
77
- found.extend(_implicit_casts(site, relation))
78
- aggregate = relation.input if isinstance(relation, ir.Limit) else relation
79
- if isinstance(aggregate, ir.Aggregate) and aggregate in reachable:
80
- found.extend(_traps(site, aggregate, join_labels))
81
- for site, join in program.scalar_subqueries:
82
- if join in reachable:
83
- found.extend(_scalar_subquery(site, join))
84
- return sorted(found, key=lambda item: item.site.offset)
85
-
86
-
87
- def _implicit_casts(site: AttachmentSite, join: ir.Join) -> list[Smell]:
88
- """Each ON equality between a text column and a column of another known type."""
89
- found = []
90
- for conjunct in join.conjuncts:
91
- match conjunct:
92
- case ir.Equality(left=ir.ColumnRef(column=first), right=ir.ColumnRef(column=second)):
93
- types = (_comparison_type(first).value, _comparison_type(second).value)
94
- if None in types or _binary_text(first).value == _binary_text(second).value:
95
- continue
96
- message = (
97
- f"{first.name} ({types[0]}) = {second.name} ({types[1]}) compares text with another type: the text is cast, "
98
- "so different strings may match one value ('01' and '1' both equal 1): cast explicitly"
99
- )
100
- evidence = Result(False, "The comparison casts text", (conjunct,))
101
- found.append(Smell(site, Concern.IMPLICIT_CAST, message, evidence))
102
- case _:
103
- pass
104
- return found
105
-
106
-
107
- def _scalar_subquery(site: AttachmentSite, join: ir.Join) -> list[Smell]:
108
- """A scalar subquery that may return more than one row.
109
-
110
- Its join is many to one by construction (more rows fail the query), so
111
- the question is asked of its body: uncorrelated, under the implied LIMIT
112
- 1, whether the body has at most one row (the empty set is a Unique Set);
113
- correlated, whether the columns ON binds reach the body's Row Identity."""
114
- match join.right:
115
- case ir.Limit(input=body) if join.predicate is None:
116
- proof = _reaches_row_identity(_closure(body, frozenset(), frozenset()))
117
- reason = "it is not proved to have at most one row"
118
- case _:
119
- proof = _at_most_one_match(join, "right")
120
- reason = "the columns its WHERE binds to the outer row are not proved to be a Unique Set"
121
- if proof.value:
122
- return []
123
- message = f"this scalar subquery may return more than one row, a runtime error: {reason}"
124
- return [Smell(site, Concern.SCALAR_SUBQUERY, message, proof)]
125
-
126
-
127
- # Join traps ------------------------------------------------------------------
128
-
129
-
130
- def _traps(site: AttachmentSite, aggregate: ir.Aggregate, join_labels: dict[ir.Join, str]) -> list[Smell]:
131
- """Each aggregate call whose input rows a join may repeat."""
132
- found: list[Smell] = []
133
- for call in aggregate.calls:
134
- inputs = [ir.determinants(argument) for argument in call.arguments]
135
- if any(columns is None for columns in inputs):
136
- continue # An argument whose columns are unknown.
137
- columns = frozenset(column for columns in inputs if columns is not None for column in columns)
138
- if not columns:
139
- # `count(*)`, or a constant: it counts the input's rows.
140
- for join, path, proof in _many_to_many_joins(aggregate.input, []):
141
- if _unrepeated(aggregate.input, join.left, path) or _unrepeated(aggregate.input, join.right, path):
142
- continue
143
- message = (
144
- f"{call.description} counts the rows of {_label(join, join_labels)}, which is not proved "
145
- "to repeat rows of only one input (a fan trap): rows may be counted more than once"
146
- )
147
- found.append(Smell(site, Concern.FAN_TRAP, message, proof))
148
- continue
149
- repeated = _repeating_join(aggregate.input, columns)
150
- if repeated is None:
151
- continue
152
- join, side, path, proof = repeated
153
- if _unrepeated(aggregate.input, side, path):
154
- continue # A filter keeps one row per key after all (`WHERE o.id = 1`).
155
- if unique_join(join).value:
156
- concern, why = Concern.CHASM_TRAP, "is one to many, and the argument is on the side with one row per key"
157
- else:
158
- concern, why = Concern.FAN_TRAP, "is not proved to repeat rows of only one input"
159
- message = (
160
- f"{call.description} reads rows that {_label(join, join_labels)} may repeat: the join {why} "
161
- f"({concern.value.lower()}), so a value may be counted more than once"
162
- )
163
- found.append(Smell(site, concern, message, proof))
164
- return found
165
-
166
-
167
- def _repeating_join(
168
- relation: ir.RelationExpr, columns: frozenset[ir.OutputColumn]
169
- ) -> tuple[ir.Join, ir.RelationExpr, list[ir.RelationExpr], Result] | None:
170
- """The first join, from `relation` down to the input `columns` come from,
171
- not proved to keep that input's rows unrepeated: the join, that input,
172
- the stages from `relation` down to the join, and the failed proof. None
173
- when every join on the way is proved, or the columns cannot be traced to
174
- one input of a join."""
175
- path: list[ir.RelationExpr] = []
176
- while True:
177
- path.append(relation)
178
- upstream = _upstream(relation, columns)
179
- if upstream is None:
180
- return None
181
- match relation:
182
- case ir.Join(kind="semi" | "anti"):
183
- side = relation.left # It never repeats a row.
184
- case ir.Join():
185
- if upstream <= set(relation.left.output_columns):
186
- side, proof = relation.left, many_to_one_join(relation)
187
- elif upstream <= set(relation.right.output_columns):
188
- side, proof = relation.right, one_to_many_join(relation)
189
- else:
190
- return None # The argument reads both inputs.
191
- if not proof.value and _has_unique_set(side):
192
- return relation, side, path, proof
193
- case ir.Filter(input=side) | ir.Alias(source=side) | ir.Project(input=side) | ir.Limit(input=side):
194
- pass
195
- case ir.NamedRelation(body=ir.RelationExpr() as side):
196
- pass
197
- case _:
198
- return None # A base table, or a stage that drops or merges rows.
199
- if not upstream <= set(side.output_columns):
200
- return None
201
- relation, columns = side, upstream
202
-
203
-
204
- def _many_to_many_joins(relation: ir.RelationExpr, path: list[ir.RelationExpr]):
205
- """Each join under `relation` not proved to repeat rows of at most one
206
- input, both of whose inputs have a known Unique Set, with the stages down
207
- to it and the failed proof."""
208
- path = [*path, relation]
209
- match relation:
210
- case ir.Join(kind="semi" | "anti", left=left):
211
- yield from _many_to_many_joins(left, path)
212
- case ir.Join(left=left, right=right):
213
- proof = unique_join(relation)
214
- if not proof.value and _has_unique_set(left) and _has_unique_set(right):
215
- yield relation, path, proof
216
- yield from _many_to_many_joins(left, path)
217
- yield from _many_to_many_joins(right, path)
218
- case ir.Filter(input=source) | ir.Alias(source=source) | ir.Project(input=source) | ir.Limit(input=source):
219
- yield from _many_to_many_joins(source, path)
220
- case ir.NamedRelation(body=ir.RelationExpr() as source):
221
- yield from _many_to_many_joins(source, path)
222
- case _:
223
- pass
224
-
225
-
226
- def _unrepeated(top: ir.RelationExpr, side: ir.RelationExpr, path: list[ir.RelationExpr]) -> bool:
227
- """Whether a Unique Set of `side`, carried up `path` (the stages from
228
- `top` down to the join `side` is an input of), is a Unique Set of `top`:
229
- `side`'s rows are not repeated there after all."""
230
- for key in minimal_keys(side):
231
- lifted: list[ir.OutputColumn] = list(key)
232
- for stage in reversed(path):
233
- passed = {
234
- output.scalar_expr.column: output for output in stage.output_columns if isinstance(output.scalar_expr, ir.ColumnRef)
235
- }
236
- if not all(column in passed for column in lifted):
237
- break
238
- lifted = [passed[column] for column in lifted]
239
- else:
240
- members = frozenset(lifted)
241
- if _reaches_row_identity(_closure(top, members, members)).value:
242
- return True
243
- return False
244
-
245
-
246
- def _upstream(relation: ir.RelationExpr, columns: frozenset[ir.OutputColumn]) -> frozenset[ir.OutputColumn] | None:
247
- """The input columns `columns` of `relation` are computed from, if known."""
248
- found: set[ir.OutputColumn] = set()
249
- for column in columns:
250
- inputs = ir.determinants(column.scalar_expr)
251
- if inputs is None:
252
- return None
253
- found.update(inputs)
254
- return frozenset(found)
255
-
256
-
257
- def _has_unique_set(relation: ir.RelationExpr) -> bool:
258
- """Some set of `relation`'s columns is a Unique Set: its rows are distinct."""
259
- columns = frozenset(relation.output_columns)
260
- return bool(columns) and _reaches_row_identity(_closure(relation, columns, columns)).value
261
-
262
-
263
- def _label(join: ir.Join, join_labels: dict[ir.Join, str]) -> str:
264
- return join_labels.get(join, "a join")
265
-
266
-
267
- # Arbitrary LIMIT -------------------------------------------------------------
268
-
269
-
270
- def _arbitrary_limit(site: AttachmentSite, limit: ir.Limit, keys: tuple[ir.OutputColumn, ...] | None) -> list[Smell]:
271
- """A LIMIT whose sort keys leave two different rows tied.
272
-
273
- Rows that agree on every selected column are interchangeable, so the keys
274
- need only strictly determine the selected columns (NULL equal to NULL, as
275
- ORDER BY ties them), not a row of the input. Under a projection the keys
276
- are input columns it may not select, so the question is asked there. A
277
- key that does not compare by identity (a collation, a float) ties
278
- different values, so it determines nothing here.
279
- """
280
- if limit.count == 0 or keys is None:
281
- return []
282
- relation = limit.input
283
- if isinstance(relation, ir.Project):
284
- scope, needed = relation.input, {column: _needed(column) for column in relation.output_columns}
285
- else:
286
- scope, needed = relation, {column: frozenset({column}) for column in relation.output_columns}
287
- exact = tuple(key for key in keys if _ties_identical(key))
288
- closure = _closure(scope, frozenset(exact), frozenset())
289
- loose = [column for column, inputs in needed.items() if inputs is None or not inputs <= closure.value.columns]
290
- if not loose:
291
- return []
292
- names = ", ".join(column.name for column in loose)
293
- reason = f"the ORDER BY does not determine ({names}), so rows tied on it" if keys else "with no ORDER BY, rows"
294
- message = f"{reason} come in an arbitrary order and LIMIT may keep different rows on each run: order by a key as well"
295
- return [Smell(site, Concern.ARBITRARY_LIMIT, message, closure)]
296
-
297
-
298
- def _ties_identical(column: ir.OutputColumn) -> bool:
299
- """Whether rows ORDER BY ties on `column` hold identical values of it."""
300
- return _identity_comparison(column).value or _exact_arithmetic(column)
301
-
302
-
303
- def _needed(column: ir.OutputColumn) -> frozenset[ir.OutputColumn] | None:
304
- """The input columns a projected column's value is a function of, if known."""
305
- inputs = ir.determinants(column.scalar_expr)
306
- return None if inputs is None else frozenset(inputs)
@@ -1,44 +0,0 @@
1
- sqlassert/__init__.py,sha256=djiGuSufeXXL-PhI5VFfeSO7eo-tgknDIeOiC8JIklM,1099
2
- sqlassert/__main__.py,sha256=Hqy4nwuvMutmv26WYl2b8REepNgy5fU_iHHFKCHLUno,6665
3
- sqlassert/check.py,sha256=0p6Jouu4Q2Rn0vSZt_QtIqqSPcHrcJZTxo3pRtC57VU,17142
4
- sqlassert/diagnostics.py,sha256=cK6SeHCzjc-c7oROhkjEwjInIrrMhZEgTLXTyFmMoIM,2425
5
- sqlassert/dialects.py,sha256=1EemSBb3VXkft2aoXxovCZRDlXBnInD6roFeVwhtv-8,9418
6
- sqlassert/improvements.py,sha256=_X9guYtszWmkBDcD9RwwTRyNwcAitRY9nMEOF_KpuDI,26194
7
- sqlassert/main.py,sha256=7b2v-LOXq7vp5b8Yt7pr-3ZgYddr5fINSt85hgUQXdE,2722
8
- sqlassert/properties.py,sha256=0PfG6bJbElPrHAyaC7TcQueacmZ5g6zVtjSrCgLbn2k,3460
9
- sqlassert/provenance.py,sha256=MmGR_b6tdjjgfeN40SG3JjAmVJuPFNnkbSfV4ZFdlMU,2158
10
- sqlassert/python_engine.py,sha256=OqydHRBCX3v_D45r8YBcDNgcdxWtWX4u8mVMP0Har4A,12392
11
- sqlassert/reporting.py,sha256=uLtOICLSiDKDmlvaKODRFNQswI_qfrB8th1ma_Y0B04,3638
12
- sqlassert/smells.py,sha256=6p60SDCVRXXg3c1DPZ8yJ9n4kHKgywBzoIbWA_hTqT0,15038
13
- sqlassert/sql_parse.py,sha256=Heuky0j3OCB2w5BZbqSn0w4khbdkwpgupJ5WyrO67fg,47049
14
- sqlassert/suggest.py,sha256=ICnrh2b1dZ9xg8WD5DxYmxXWo4SPrhtIk0OWrDRdx70,16086
15
- sqlassert/discovery/__init__.py,sha256=pa9tv0G_YRJEFYO-aPPOQtvhc3YVg4_WZ1bYQqraoBU,854
16
- sqlassert/discovery/bigquery.py,sha256=WgWnLd5Ik8vBLDwlH8ACcV11OYwJLPAQDaR8WWN2Kl0,3373
17
- sqlassert/discovery/databricks.py,sha256=Ir4yhtvwoLzQXfpPehxFXPJOUReIb22rualaWHv1s6g,750
18
- sqlassert/discovery/duckdb.py,sha256=alkWzLAJ86np5E5ellJgvbQJnUat33CLAohqwJreZbQ,7911
19
- sqlassert/discovery/fetcher.py,sha256=LDbz8gbVY4ly2jRI885cbHTizFA8OpmMImqhfrVOI64,19460
20
- sqlassert/discovery/information_schema.py,sha256=Fr8sHNF6tMe1sJLq3D106eFmlClSMoBmAbnQMq3-TUY,16555
21
- sqlassert/discovery/mysql.py,sha256=_oQynTv2BFWJ93H6aT1gY-lUaofLagUUFgD7unt3H0c,3390
22
- sqlassert/discovery/postgres.py,sha256=KoqY6-0jTDpSnSwkhJfasBu0s4XMui7kHPKpLrcRdLU,6624
23
- sqlassert/discovery/redshift.py,sha256=_QWfwBwAf9lhMjbDbqfjLbkRZ2LLpvC5ZGqH_O3RxtE,1669
24
- sqlassert/discovery/snowflake.py,sha256=kJzwVk_trVRIC_H5_LmBjVXup-hMJBnYg1GWRf5utBM,3115
25
- sqlassert/discovery/trino.py,sha256=xRnyk_jPQGann1sXYCSJw2JxfMWwF7uiuvE0wzyLKMM,1664
26
- sqlassert/ir/__init__.py,sha256=PU2-h1I1bYxRds6inHNgpZGZxxbCq2OOfH0oZBSrlZc,1542
27
- sqlassert/ir/convert.py,sha256=2kN45Gsi39xetDSsfL1gRiGnmrvKEkGUZ1hxY0PWuAs,126212
28
- sqlassert/ir/model.py,sha256=kq_XtVB_Bwl-jcuGmmI00iqKWkq4XcEUrP4wdQU5L3k,25521
29
- sqlassert/rules/STYLEGUIDE.md,sha256=8Oqy6vPdJ5LZ5zjKCfd5oVTWjwFHhb6NMrmHpAxqZ0c,1435
30
- sqlassert/rules/__init__.py,sha256=VwDKt2zRCexIWxHwrZRBpvW0T6Ziesg-S7edcrQRiAo,526
31
- sqlassert/rules/column_set.py,sha256=CFUz1iVC88gsg2iRcqe7h6hOR8sLfrvk80C1S5JGmuM,772
32
- sqlassert/rules/domain.py,sha256=jgMTfo54lgxHK2uCI1f9zyO15nkNwV7QvTX3W4yIx_E,18718
33
- sqlassert/rules/equality.py,sha256=hEQ6nrEOEKR4ag3B_WtS6yMUHELE0xWcrb5dD7YCmEk,10953
34
- sqlassert/rules/exactly_one.py,sha256=vF4ei6ZW1Si-ItVdlcenzCk7I16NoTc_qc4_5YHk_Sw,3734
35
- sqlassert/rules/foreign_key.py,sha256=iShG1Xmp3lIL3XCL7HNNNphka-WSE3AiyDlMfEDo4bw,16832
36
- sqlassert/rules/join_cardinality.py,sha256=UPwd0AF3Au-Yi8ymeS5yKhc4S4Ve2o-uoIalkFHFZy4,4675
37
- sqlassert/rules/nullability.py,sha256=VkWXl9GhIFyIxxIzvlOjwJJI5KOWB7d1xbYP1_YRRGc,20750
38
- sqlassert/rules/uniqueness.py,sha256=QHiXQq70N_QYgaJLfW6_UPL3Z2-i3S70SMhc8lJAj64,30744
39
- sqlassert-0.3.1.dist-info/licenses/LICENSE,sha256=KCR0_j-gr5ufUNxamIKNzeyyiI6g-S69oecRjZ07l_A,1068
40
- sqlassert-0.3.1.dist-info/METADATA,sha256=h9bbjDqctZg8D0NHBfePHsh6qwmTnrv1cOvmXtkAZHE,46446
41
- sqlassert-0.3.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
42
- sqlassert-0.3.1.dist-info/entry_points.txt,sha256=62_aZX2ftMZAXQcwI7AbWWvDXjgo1b7jeUE5aNSGQHM,54
43
- sqlassert-0.3.1.dist-info/top_level.txt,sha256=BINwf_eEiAW975zV29VyXrSnTO9G136zvJVJ2pupnLI,10
44
- sqlassert-0.3.1.dist-info/RECORD,,
@@ -1,2 +0,0 @@
1
- [console_scripts]
2
- sqlassert = sqlassert.__main__:main
@@ -1 +0,0 @@
1
- sqlassert