sqlassert 0.4.1__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 (42) hide show
  1. sqlassert/declared_types.py +158 -0
  2. sqlassert/diagnostics.py +1 -4
  3. sqlassert/dialects.py +118 -396
  4. sqlassert/discovery/bigquery.py +2 -2
  5. sqlassert/discovery/databricks.py +4 -6
  6. sqlassert/discovery/fetcher.py +22 -52
  7. sqlassert/discovery/information_schema.py +7 -10
  8. sqlassert/discovery/mysql.py +4 -8
  9. sqlassert/discovery/postgres.py +17 -26
  10. sqlassert/discovery/redshift.py +2 -2
  11. sqlassert/discovery/snowflake.py +2 -2
  12. sqlassert/functions/__init__.py +10 -0
  13. sqlassert/functions/load.py +375 -0
  14. sqlassert/functions/table.py +2721 -0
  15. sqlassert/hazards.py +1 -1
  16. sqlassert/ir/__init__.py +13 -5
  17. sqlassert/ir/convert/aggregation.py +2 -3
  18. sqlassert/ir/convert/expressions.py +76 -67
  19. sqlassert/ir/convert/parser.py +0 -4
  20. sqlassert/ir/convert/schema.py +11 -80
  21. sqlassert/ir/convert/selects.py +30 -15
  22. sqlassert/ir/convert/shared.py +2 -3
  23. sqlassert/ir/convert/sources.py +2 -1
  24. sqlassert/ir/convert/value_types.py +12 -157
  25. sqlassert/ir/model.py +331 -138
  26. sqlassert/main.py +7 -10
  27. sqlassert/rules/causes/domain.py +1 -1
  28. sqlassert/rules/causes/unique.py +46 -5
  29. sqlassert/rules/domain.py +1 -1
  30. sqlassert/rules/join_cardinality.py +14 -21
  31. sqlassert/rules/nullability.py +3 -3
  32. sqlassert/rules/uniqueness.py +42 -41
  33. sqlassert/rules/value_typing.py +266 -133
  34. sqlassert/suggest.py +2 -2
  35. {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/METADATA +18 -14
  36. sqlassert-0.4.2.dist-info/RECORD +72 -0
  37. sqlassert/ir/convert/builtins.py +0 -140
  38. sqlassert-0.4.1.dist-info/RECORD +0 -69
  39. {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/WHEEL +0 -0
  40. {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/entry_points.txt +0 -0
  41. {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/licenses/LICENSE +0 -0
  42. {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,375 @@
1
+ """Builds one dialect's Builtins from the function table (`functions/table.py`).
2
+
3
+ Only the dialect being analyzed is resolved, once (`@cache`): its type names
4
+ go through SQLGlot into `ir.ValueTyping`s, and each entry's typing becomes a
5
+ function of the arguments' types (`ir.Builtin.typing`)."""
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Callable
10
+ from dataclasses import dataclass, field, replace
11
+ from functools import cache
12
+
13
+ from sqlglot import Expr, exp
14
+
15
+ from sqlassert import ir
16
+ from sqlassert.declared_types import declared_typing
17
+ from sqlassert.dialects import DialectSemantics, semantics
18
+ from sqlassert.functions.table import (
19
+ CONSERVATIVE, FUNCTIONS, Absent, Common, FamilyOf, Function, Keep, OnArg, OnArity, OnLiteral, PerDialect, Properties, Shape, Target, Typing,
20
+ Undecided, Unmodelled, Unreachable, Volatile,
21
+ )
22
+
23
+ # What a decimal is after any function of it: its precision and scale are not
24
+ # claimed, so no type but another computed decimal's is the same.
25
+ _DECIMAL_EXPRESSION = ir.ValueTyping("DECIMAL EXPRESSION", False, True, True, family="decimal")
26
+
27
+
28
+ def key(expression: Expr) -> str:
29
+ """The key of a call in the table: its SQLGlot node, or `Anonymous:<lowercase name>` for one SQLGlot does not know."""
30
+ if isinstance(expression, exp.Anonymous):
31
+ return f"Anonymous:{expression.name.lower()}"
32
+ return type(expression).__name__
33
+
34
+
35
+ def call(dialect: str, expression: Expr) -> tuple[ir.Builtin, list[Expr]] | None:
36
+ """The Builtin `expression` is a call of in the dialect, with the
37
+ arguments it takes, or None when it is no function of its arguments the
38
+ table models or types.
39
+
40
+ A call that reads exactly the keys of one of the entry's signatures (and
41
+ carries no other argument but those it `ignores`) is a call of the entry's
42
+ property function. Any other call of a function with a result type is a
43
+ call of a conservative Builtin over all its arguments."""
44
+ if isinstance(expression, exp.Anonymous):
45
+ return None # A function SQLGlot does not know may be a user's or volatile: opaque, typed by `fixed_typing`.
46
+ entry = _entries(dialect.lower(), semantics(dialect)).get(key(expression))
47
+ if entry is None or entry.volatile or not (entry.modelled or entry.typed):
48
+ return None
49
+ function = entry.function
50
+ present = {name for name, value in expression.args.items() if _is_expression(value)}
51
+ for signature in function.signatures:
52
+ names = tuple(name.lstrip("*") for name in signature)
53
+ if present - set(names) - set(function.ignores):
54
+ continue
55
+ values = [value for name in names for value in _values(expression.args.get(name))]
56
+ if entry.modelled:
57
+ builtin = entry.builtin(Shape(function.name, sum(not name.startswith("*") for name in signature), any(name.startswith("*") for name in signature)))
58
+ if builtin.accepts(len(values)):
59
+ return _by_literal(entry, builtin, expression, len(values)), values
60
+ elif entry.typed:
61
+ return _by_literal(entry, entry.conservative(Shape(function.name, len(values))), expression, len(values)), values
62
+ if entry.typed:
63
+ values = list(expression.iter_expressions())
64
+ return _by_literal(entry, entry.conservative(Shape(function.name, len(values))), expression, len(values)), values
65
+ return None
66
+
67
+
68
+ def _by_literal(entry: _Entry, builtin: ir.Builtin, expression: Expr, arity: int) -> ir.Builtin:
69
+ """`builtin`, typed by the literal the call is written with where its
70
+ keyword branches on one (`on_literal`)."""
71
+ if not entry.literal_keys:
72
+ return builtin
73
+ resolved = _resolve(entry.typing, expression, arity)
74
+ compiled = _compile(resolved, entry.dialect)
75
+ return replace(
76
+ builtin, typing=compiled.function, typing_reads=compiled.reads, typed=not isinstance(resolved, Absent | Unreachable | Undecided | Unmodelled),
77
+ )
78
+
79
+
80
+ def _literal(expression: Expr, key: str) -> str | None:
81
+ """The lower-cased value of the literal argument `key`, None where it is none."""
82
+ value = expression.args.get(key)
83
+ if isinstance(value, exp.Literal | exp.Var | exp.Identifier):
84
+ return str(value.name).lower()
85
+ return None
86
+
87
+
88
+ def _resolve(typing: Typing, expression: Expr, arity: int | None = None) -> Typing:
89
+ """`typing` with each `on_literal` replaced by the branch the call's literal picks."""
90
+ match typing:
91
+ case OnLiteral(key, branches, otherwise):
92
+ return _resolve(branches.get(_literal(expression, key) or "", otherwise), expression, arity)
93
+ case OnArity(branches, otherwise):
94
+ return _resolve(branches.get(arity, otherwise) if arity is not None else otherwise, expression, arity)
95
+ case OnArg(index, branches, otherwise):
96
+ return OnArg(index, {family: _resolve(branch, expression, arity) for family, branch in branches.items()}, _resolve(otherwise, expression, arity))
97
+ case _:
98
+ return typing
99
+
100
+
101
+ def volatile(dialect: str, expression: Expr) -> bool:
102
+ """Whether the dialect's table says `expression`'s function is volatile: no function of its arguments."""
103
+ entry = _entries(dialect.lower(), semantics(dialect)).get(key(expression))
104
+ return entry is not None and entry.volatile
105
+
106
+
107
+ def modelled(dialect: str, node: type[Expr]) -> bool:
108
+ """Whether the dialect's table models the node's properties: a call of it is a function of its arguments."""
109
+ entry = _entries(dialect.lower(), semantics(dialect)).get(node.__name__)
110
+ return entry is not None and entry.modelled
111
+
112
+
113
+ def modelled_builtins(dialect: str, meaning: DialectSemantics) -> dict[type[Expr], tuple[ir.Builtin, tuple[str, ...]]]:
114
+ """Each Builtin the dialect models, by the SQLGlot node it lowers from,
115
+ with the argument keys its parameters come from (a list key in place of
116
+ a variadic Builtin's repeated parameter), as `meaning`'s flags make it.
117
+ `scripts/certify_dialects.py` probes each Builtin fact."""
118
+ found: dict[type[Expr], tuple[ir.Builtin, tuple[str, ...]]] = {}
119
+ for entry in _entries(dialect, meaning).values():
120
+ function = entry.function
121
+ if not entry.modelled or isinstance(function.node, str):
122
+ continue
123
+ signature = function.signatures[0]
124
+ shape = Shape(function.name, sum(not name.startswith("*") for name in signature), any(name.startswith("*") for name in signature))
125
+ found[function.node] = (entry.builtin(shape), tuple(name.lstrip("*") for name in signature))
126
+ return found
127
+
128
+
129
+ def result_type(dialect: str, expression: Expr) -> exp.DataType | None:
130
+ """The type the dialect fixes for a call of `expression`'s function whatever its arguments' types."""
131
+ entry = _entries(dialect.lower(), semantics(dialect)).get(key(expression))
132
+ if entry is None:
133
+ return None
134
+ typing = _resolve(entry.typing, expression)
135
+ return exp.DataType.build(typing, dialect=dialect) if isinstance(typing, str) else None
136
+
137
+
138
+ def fixed_typing(dialect: str, expression: Expr) -> ir.ValueTyping | None:
139
+ """How a call of a function SQLGlot does not know compares, where the
140
+ dialect fixes its result type (`Anonymous:<name>` in the table)."""
141
+ kind = result_type(dialect, expression)
142
+ return None if kind is None else declared_typing(kind, dialect)
143
+
144
+
145
+ def unmodelled(expression: Expr, arity: int) -> ir.Builtin:
146
+ """A pure function of its arguments sqlassert knows nothing else of (a known
147
+ SQLGlot node the table does not model or type for the dialect), named after the function."""
148
+ name = expression.sql_name().lower() if isinstance(expression, exp.Func) else type(expression).__name__.lower()
149
+
150
+ def typing(arguments: tuple[ir.Argument, ...]) -> tuple[ir.ValueTyping | None, str]:
151
+ return None, "sqlassert does not model it, so its type is not known"
152
+
153
+ return replace(CONSERVATIVE(Shape(name, arity), DialectSemantics()), typing=typing, modelled=False)
154
+
155
+
156
+ def selection(name: str, arity: int, results: tuple[int, ...]) -> ir.Builtin:
157
+ """A searched CASE or IF over `arity` conditions and results (flat): one of
158
+ the results at `results`, or NULL, so typed as the type they share; not
159
+ strict, and nothing else is known of it."""
160
+ typing = _Compiled(lambda arguments: ir.common_typing([_argument(arguments, index) for index in results]), results)
161
+ return replace(
162
+ CONSERVATIVE(Shape(name, arity), DialectSemantics()), typing=typing.function, typed=True, typing_reads=results, modelled=False,
163
+ )
164
+
165
+
166
+ def captured(function: ir.Builtin, target: ir.ValueTyping | None) -> ir.Builtin:
167
+ """`function`, a CAST, typed by the target the call site names."""
168
+
169
+ def typing(arguments: tuple[ir.Argument, ...]) -> tuple[ir.ValueTyping | None, str]:
170
+ return target, "The type the CAST names"
171
+
172
+ return replace(function, typing=typing, typed=True, typing_reads=())
173
+
174
+
175
+ def keyword(function: Function, dialect: str) -> Typing:
176
+ """The typing the entry's keyword gives the dialect."""
177
+ chosen = function.keywords[dialect]
178
+ return chosen[0] if isinstance(chosen, tuple) else chosen
179
+
180
+
181
+ # ---------------------------------------------------------------------------
182
+
183
+
184
+ @dataclass(frozen=True)
185
+ class _Entry:
186
+ """One entry for one dialect."""
187
+
188
+ function: Function
189
+ properties: Properties
190
+ typing: Typing
191
+ meaning: DialectSemantics
192
+ compiled: _Compiled
193
+ dialect: str = ""
194
+ volatile: bool = False
195
+ _builtins: dict[tuple[Shape, bool], ir.Builtin] = field(default_factory=dict, compare=False, repr=False)
196
+
197
+ @property
198
+ def literal_keys(self) -> bool:
199
+ """Whether its keyword branches on a literal."""
200
+ return _has_literal(self.typing)
201
+
202
+ @property
203
+ def modelled(self) -> bool:
204
+ """Whether its properties are known (not `CONSERVATIVE`)."""
205
+ return self.properties is not CONSERVATIVE
206
+
207
+ @property
208
+ def typed(self) -> bool:
209
+ """Whether the dialect gives it a result type, fixed or following its arguments."""
210
+ return not isinstance(self.typing, Absent | Unreachable | Undecided | Unmodelled)
211
+
212
+ def builtin(self, shape: Shape) -> ir.Builtin:
213
+ return self._build(shape, self.properties)
214
+
215
+ def conservative(self, shape: Shape) -> ir.Builtin:
216
+ return self._build(shape, CONSERVATIVE)
217
+
218
+ def _build(self, shape: Shape, properties: Properties) -> ir.Builtin:
219
+ cached = self._builtins.get((shape, properties is CONSERVATIVE))
220
+ if cached is None:
221
+ cached = replace(
222
+ properties(shape, self.meaning), typing=self.compiled.function, typed=self.typed, typing_reads=self.compiled.reads,
223
+ modelled=properties is not CONSERVATIVE,
224
+ )
225
+ self._builtins[shape, properties is CONSERVATIVE] = cached
226
+ return cached
227
+
228
+
229
+ @cache
230
+ def _entries(dialect: str, meaning: DialectSemantics) -> dict[str, _Entry]:
231
+ """Every entry the table has for the dialect, by key. A dialect the table
232
+ does not list decides nothing: its entries are undecided, and one whose
233
+ properties differ by dialect is not modelled at all."""
234
+ entries: dict[str, _Entry] = {}
235
+ for function in FUNCTIONS:
236
+ chosen = function.keywords.get(dialect)
237
+ if isinstance(function.properties, PerDialect):
238
+ if chosen is None:
239
+ continue
240
+ assert isinstance(chosen, tuple)
241
+ typing, properties = chosen
242
+ else:
243
+ assert not isinstance(chosen, tuple)
244
+ typing, properties = chosen if chosen is not None else Undecided(), function.properties
245
+ if isinstance(properties, Volatile):
246
+ properties = CONSERVATIVE
247
+ _check_indices(function, typing)
248
+ entries[function.key] = _Entry(
249
+ function, properties, typing, meaning, _compile(_resolve(typing, exp.Anonymous()), dialect), dialect, isinstance(function.properties, Volatile),
250
+ )
251
+ return entries
252
+
253
+
254
+ def _check_indices(function: Function, typing: Typing) -> None:
255
+ """Every argument index a typing names is one a signature has."""
256
+ arguments = max((len(signature) + any(name.startswith("*") for name in signature) for signature in function.signatures), default=0)
257
+ for index in _indices(typing):
258
+ assert index < arguments or any(name.startswith("*") for signature in function.signatures for name in signature), (
259
+ f"{function.key}: argument {index} is in no signature"
260
+ )
261
+
262
+
263
+ def _indices(typing: Typing) -> list[int]:
264
+ match typing:
265
+ case Keep(index) | FamilyOf(index):
266
+ return [index]
267
+ case OnArg(index, branches, otherwise):
268
+ return [index, *(i for branch in (*branches.values(), otherwise) for i in _indices(branch))]
269
+ case OnArity(branches, otherwise):
270
+ return [i for branch in (*branches.values(), otherwise) for i in _indices(branch)]
271
+ case OnLiteral(_, branches, otherwise):
272
+ return [i for branch in (*branches.values(), otherwise) for i in _indices(branch)]
273
+ case Common(indices):
274
+ return list(indices)
275
+ case _:
276
+ return []
277
+
278
+
279
+ def _has_literal(typing: Typing) -> bool:
280
+ match typing:
281
+ case OnLiteral() | OnArity():
282
+ return True
283
+ case OnArg(_, branches, otherwise):
284
+ return any(_has_literal(branch) for branch in (*branches.values(), otherwise))
285
+ case _:
286
+ return False
287
+
288
+
289
+ def _is_expression(value: object) -> bool:
290
+ return isinstance(value, Expr) or isinstance(value, list) and any(isinstance(item, Expr) for item in value)
291
+
292
+
293
+ def _values(value: object) -> list[Expr]:
294
+ if isinstance(value, Expr):
295
+ return [value]
296
+ if isinstance(value, list):
297
+ return [item for item in value if isinstance(item, Expr)]
298
+ return []
299
+
300
+
301
+ # ---------------------------------------------------------------------------
302
+ # Typing: an entry's keyword as a function of the arguments' types
303
+ # ---------------------------------------------------------------------------
304
+
305
+
306
+ @dataclass(frozen=True)
307
+ class _Compiled:
308
+ function: ir.TypingFunction
309
+ reads: tuple[int, ...]
310
+
311
+
312
+ def _compile(typing: Typing, dialect: str) -> _Compiled:
313
+ match typing:
314
+ case str():
315
+ result = declared_typing(exp.DataType.build(typing, dialect=dialect), dialect)
316
+ why = f"The type {typing} the dialect gives"
317
+ return _Compiled(lambda arguments: (result, why), ())
318
+ case Keep(index):
319
+ return _Compiled(lambda arguments: _kept(arguments, index, lambda typing: typing, "The type of its argument"), (index,))
320
+ case FamilyOf(index):
321
+ return _Compiled(lambda arguments: _kept(arguments, index, _base, "The base type of its argument"), (index,))
322
+ case OnArg(index, branches, otherwise):
323
+ compiled = {family: _compile(branch, dialect) for family, branch in branches.items()}
324
+ fallback = _compile(otherwise, dialect)
325
+
326
+ def on_arg(arguments: tuple[ir.Argument, ...]) -> tuple[ir.ValueTyping | None, str]:
327
+ argument = _argument(arguments, index)
328
+ if argument.typing is None:
329
+ return None, "The argument its type follows has no known type"
330
+ return compiled.get(_family(argument.typing), fallback).function(arguments)
331
+
332
+ reads = dict.fromkeys((index, *(i for branch in (*compiled.values(), fallback) for i in branch.reads)))
333
+ return _Compiled(on_arg, tuple(reads))
334
+ case Common(indices):
335
+ return _Compiled(lambda arguments: ir.common_typing([_argument(arguments, index) for index in indices]), indices)
336
+ case Unmodelled(reason):
337
+ return _Compiled(lambda arguments: (None, reason.value), ())
338
+ case Target() | Absent() | Unreachable() | Undecided():
339
+ return _Compiled(ir.untyped, ())
340
+ case _:
341
+ raise TypeError(f"not a typing: {typing!r}")
342
+
343
+
344
+ def _argument(arguments: tuple[ir.Argument, ...], index: int) -> ir.Argument:
345
+ return arguments[index] if index < len(arguments) else ir.Argument()
346
+
347
+
348
+ def _kept(
349
+ arguments: tuple[ir.Argument, ...], index: int, derive: Callable[[ir.ValueTyping], ir.ValueTyping], why: str,
350
+ ) -> tuple[ir.ValueTyping | None, str]:
351
+ typing = _argument(arguments, index).typing
352
+ if typing is None:
353
+ return None, "The argument its type follows has no known type"
354
+ return derive(typing), why
355
+
356
+
357
+ def _family(typing: ir.ValueTyping) -> ir.TypeFamily | None:
358
+ """The family `on_arg` branches on. A decimal literal, or an unsigned
359
+ integer, has no family of its own but is an exact number that is no
360
+ signed integer: a decimal."""
361
+ if typing.family is not None:
362
+ return typing.family
363
+ if typing.exact_numeric and typing.integer is None:
364
+ return "decimal"
365
+ return None
366
+
367
+
368
+ def _base(typing: ir.ValueTyping) -> ir.ValueTyping:
369
+ """`typing` with its parameters dropped: a decimal has no claimed
370
+ precision or scale, a sized text no length."""
371
+ if _family(typing) == "decimal":
372
+ return _DECIMAL_EXPRESSION
373
+ if typing.length is None and typing.precision is None and typing.scale is None and "(" not in typing.comparison_type:
374
+ return typing
375
+ return replace(typing, comparison_type=typing.comparison_type.split("(")[0].strip(), length=None, precision=None, scale=None)