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.
- sqlassert/declared_types.py +158 -0
- sqlassert/diagnostics.py +1 -4
- sqlassert/dialects.py +118 -396
- sqlassert/discovery/bigquery.py +2 -2
- sqlassert/discovery/databricks.py +4 -6
- sqlassert/discovery/fetcher.py +22 -52
- sqlassert/discovery/information_schema.py +7 -10
- sqlassert/discovery/mysql.py +4 -8
- sqlassert/discovery/postgres.py +17 -26
- sqlassert/discovery/redshift.py +2 -2
- sqlassert/discovery/snowflake.py +2 -2
- sqlassert/functions/__init__.py +10 -0
- sqlassert/functions/load.py +375 -0
- sqlassert/functions/table.py +2721 -0
- sqlassert/hazards.py +1 -1
- sqlassert/ir/__init__.py +13 -5
- sqlassert/ir/convert/aggregation.py +2 -3
- sqlassert/ir/convert/expressions.py +76 -67
- sqlassert/ir/convert/parser.py +0 -4
- sqlassert/ir/convert/schema.py +11 -80
- sqlassert/ir/convert/selects.py +30 -15
- sqlassert/ir/convert/shared.py +2 -3
- sqlassert/ir/convert/sources.py +2 -1
- sqlassert/ir/convert/value_types.py +12 -157
- sqlassert/ir/model.py +331 -138
- sqlassert/main.py +7 -10
- sqlassert/rules/causes/domain.py +1 -1
- sqlassert/rules/causes/unique.py +46 -5
- sqlassert/rules/domain.py +1 -1
- sqlassert/rules/join_cardinality.py +14 -21
- sqlassert/rules/nullability.py +3 -3
- sqlassert/rules/uniqueness.py +42 -41
- sqlassert/rules/value_typing.py +266 -133
- sqlassert/suggest.py +2 -2
- {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/METADATA +18 -14
- sqlassert-0.4.2.dist-info/RECORD +72 -0
- sqlassert/ir/convert/builtins.py +0 -140
- sqlassert-0.4.1.dist-info/RECORD +0 -69
- {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/WHEEL +0 -0
- {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/entry_points.txt +0 -0
- {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/licenses/LICENSE +0 -0
- {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/top_level.txt +0 -0
sqlassert/hazards.py
CHANGED
|
@@ -36,7 +36,7 @@ the proof that would have pinned it, which failed:
|
|
|
36
36
|
for (a foreign key's orphan check), a `WHERE x IS NULL` on a column proved
|
|
37
37
|
non-null (the `LEFT JOIN ... IS NULL` form of it), an `EXCEPT` whose left
|
|
38
38
|
rows all appear on the right. Whether the key is enforced is not asked:
|
|
39
|
-
sqlassert trusts every
|
|
39
|
+
sqlassert trusts every declared constraint (ADR 0012).
|
|
40
40
|
- A CASE (or IF) whose results have different declared types: the engine
|
|
41
41
|
casts them to a common type, and the cast may lose what told values apart
|
|
42
42
|
(`'01'` and `'1'` both become 1). Integer types only widen. A result whose
|
sqlassert/ir/__init__.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"""Relational intermediate representation."""
|
|
2
2
|
|
|
3
|
-
from sqlassert.ir.model import Accumulation, Aggregate, AggregateCall, Alias, And, AnyAggregate, AnyRelation, AnyScalar,
|
|
3
|
+
from sqlassert.ir.model import Accumulation, Aggregate, AggregateCall, Alias, And, AnyAggregate, AnyRelation, AnyScalar, Argument, Assertion, Builtin, Call, CallProperties, CastKind, CastTable, CastTarget, Coalesce, ColumnRef, Constant, Count, Distinct, Elements, Equality, Filter, InList, IsNotNull, IsNull, Join, JoinKind, Limit, NamedRelation, Node, NullLiteral, NullSafeEquality, OpaqueExpression, OpaqueRelation, Or, OutputColumn, Program, Project, QualifyByPartition, RecursiveRelation, RelationExpr, RelationRole, ScalarExpr, SetOperation, SimpleCase, TypeFamily, ValuesList, ValueTyping, LiteralValue, PropertyFunction, SetOperator, TypingFunction, untyped, common_typing, NO_KNOWN_TYPE, children, conjuncts, determinants, identity_arguments, strict_inputs, total
|
|
4
4
|
|
|
5
5
|
__all__ = [
|
|
6
6
|
"Accumulation",
|
|
@@ -12,8 +12,11 @@ __all__ = [
|
|
|
12
12
|
"AnyRelation",
|
|
13
13
|
"AnyScalar",
|
|
14
14
|
"Builtin",
|
|
15
|
-
"BuiltinVariadic",
|
|
16
15
|
"Call",
|
|
16
|
+
"CallProperties",
|
|
17
|
+
"CastKind",
|
|
18
|
+
"CastTable",
|
|
19
|
+
"CastTarget",
|
|
17
20
|
"Assertion",
|
|
18
21
|
"Coalesce",
|
|
19
22
|
"ColumnRef",
|
|
@@ -35,12 +38,16 @@ __all__ = [
|
|
|
35
38
|
"NullLiteral",
|
|
36
39
|
"NullSafeEquality",
|
|
37
40
|
"OpaqueExpression",
|
|
38
|
-
"OpaquePureFunction",
|
|
39
41
|
"OpaqueRelation",
|
|
40
42
|
"Or",
|
|
41
43
|
"OutputColumn",
|
|
42
44
|
"Program",
|
|
43
45
|
"Project",
|
|
46
|
+
"PropertyFunction",
|
|
47
|
+
"TypingFunction",
|
|
48
|
+
"untyped",
|
|
49
|
+
"common_typing",
|
|
50
|
+
"NO_KNOWN_TYPE",
|
|
44
51
|
"QualifyByPartition",
|
|
45
52
|
"RecursiveRelation",
|
|
46
53
|
"RelationExpr",
|
|
@@ -49,13 +56,14 @@ __all__ = [
|
|
|
49
56
|
"SetOperation",
|
|
50
57
|
"SetOperator",
|
|
51
58
|
"ValuesList",
|
|
59
|
+
"TypeFamily",
|
|
52
60
|
"ValueTyping",
|
|
53
|
-
"
|
|
61
|
+
"Argument",
|
|
54
62
|
"SimpleCase",
|
|
55
63
|
"children",
|
|
56
64
|
"conjuncts",
|
|
57
65
|
"determinants",
|
|
58
|
-
"
|
|
66
|
+
"identity_arguments",
|
|
59
67
|
"strict_inputs",
|
|
60
68
|
"total",
|
|
61
69
|
]
|
|
@@ -7,8 +7,7 @@ from typing import TYPE_CHECKING
|
|
|
7
7
|
|
|
8
8
|
from sqlglot import Expr, exp
|
|
9
9
|
|
|
10
|
-
from sqlassert import ir
|
|
11
|
-
from sqlassert.ir.convert.builtins import dialect_builtins
|
|
10
|
+
from sqlassert import functions, ir
|
|
12
11
|
from sqlassert.ir.convert.shared import (
|
|
13
12
|
_Binding, _Lowered, _placed, _pass_output_columns, _source_line, _and, _filter_conjuncts, _unsupported_grouping, _only_star, _matching_output,
|
|
14
13
|
_unaliased, _NOT_A_FUNCTION_OF_ITS_COLUMNS,
|
|
@@ -187,7 +186,7 @@ class _Aggregation:
|
|
|
187
186
|
inputs qualify, not a literal (which a name may shadow)."""
|
|
188
187
|
return not isinstance(expression, exp.Literal) and all(
|
|
189
188
|
not isinstance(node, _NOT_A_FUNCTION_OF_ITS_COLUMNS)
|
|
190
|
-
and (not isinstance(node, exp.Func) or type(node)
|
|
189
|
+
and (not isinstance(node, exp.Func) or functions.modelled(self.dialect, type(node)))
|
|
191
190
|
or isinstance(node, exp.Count | exp.Sum | exp.Min | exp.Max | exp.Avg | exp.Star)
|
|
192
191
|
for node in expression.walk()
|
|
193
192
|
)
|
|
@@ -12,12 +12,12 @@ from typing import TYPE_CHECKING, assert_never
|
|
|
12
12
|
from sqlglot import Expr, exp
|
|
13
13
|
|
|
14
14
|
from sqlassert import diagnostics as diag
|
|
15
|
-
from sqlassert import ir
|
|
15
|
+
from sqlassert import functions, ir
|
|
16
|
+
from sqlassert.declared_types import declared_typing
|
|
16
17
|
from sqlassert.diagnostics import Diagnostic, quoted
|
|
17
18
|
from sqlassert.properties import ExhaustiveCase, NonNullElements
|
|
18
19
|
from sqlassert.provenance import AttachmentSite, Origin
|
|
19
20
|
from sqlassert.sql_parse import exhaustive_span, literal_value, marker_position, written_sql
|
|
20
|
-
from sqlassert.ir.convert.builtins import dialect_builtins
|
|
21
21
|
from sqlassert.ir.convert.shared import (
|
|
22
22
|
_Binding, _source_line, _conjuncts, _TEXT_TYPES, _USING_QUALIFIER, _SCALAR_QUALIFIER, _schema_path, _Carried, _renamed, _row_number_window,
|
|
23
23
|
_NOT_A_FUNCTION_OF_ITS_COLUMNS, _select_label, _placed,
|
|
@@ -72,8 +72,8 @@ class _Expressions:
|
|
|
72
72
|
when every source's schema is complete: otherwise the one visible match
|
|
73
73
|
might be shadowed by a column of a source whose columns are unknown.
|
|
74
74
|
|
|
75
|
-
A Builtin becomes a Call; any other function or operator
|
|
76
|
-
|
|
75
|
+
A Builtin becomes a Call; any other function or operator a
|
|
76
|
+
Call of a conservative Builtin over its lowered arguments, unless its value is not a
|
|
77
77
|
function of them (`_NOT_A_FUNCTION_OF_ITS_COLUMNS`)."""
|
|
78
78
|
origin = self._origin(expression, line)
|
|
79
79
|
if (grouped := self._grouped_values.get(id(expression))) is not None:
|
|
@@ -191,73 +191,69 @@ class _Expressions:
|
|
|
191
191
|
return ir.NullLiteral(origin=origin)
|
|
192
192
|
if value is not None or isinstance(expression, exp.Literal):
|
|
193
193
|
return self._constant(origin, value)
|
|
194
|
-
|
|
195
|
-
if
|
|
196
|
-
function,
|
|
197
|
-
if type(expression) is exp.Cast and
|
|
194
|
+
found = None if quantified else functions.call(self.dialect, expression)
|
|
195
|
+
if found is not None:
|
|
196
|
+
function, values = found
|
|
197
|
+
if type(expression) is exp.Cast and self._is_json(expression.this, lower):
|
|
198
198
|
# `CAST(JSON 'null' AS BIGINT)` is NULL.
|
|
199
|
-
function =
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
function, arguments = self._composite_comparison(expression, function, arguments, composites, self._origin(expression, line or _source_line(expression)))
|
|
223
|
-
call = ir.Call(origin=origin, function=function, arguments=arguments, description=description)
|
|
224
|
-
if type(expression) is exp.Cast:
|
|
225
|
-
return replace(call, typing=self._cast_typing(expression))
|
|
226
|
-
return self._typed_call(expression, replace(call, typing=self._fixed_typing(expression), typed_by=self._argument_typing(expression, values)))
|
|
199
|
+
function = _never_total(function)
|
|
200
|
+
if isinstance(expression, exp.Cast):
|
|
201
|
+
# The target is the call's own type: TRY_CAST too, a failure being NULL, which equals nothing.
|
|
202
|
+
function = functions.captured(function, declared_typing(expression.to, self.dialect))
|
|
203
|
+
arguments = tuple(lower(value) for value in values)
|
|
204
|
+
if (
|
|
205
|
+
type(expression) is exp.Like and self.semantics.text_is_binary
|
|
206
|
+
and isinstance(arguments[1], ir.Constant)
|
|
207
|
+
and (pattern := arguments[1].value) is not None and pattern.type == "string"
|
|
208
|
+
and not any(character in pattern.text for character in "%_\\")
|
|
209
|
+
and expression.find_ancestor(exp.Escape) is None
|
|
210
|
+
and (kind := self._declared_type(arguments[0], through_sets=False)) is not None
|
|
211
|
+
and kind.this in _TEXT_TYPES
|
|
212
|
+
):
|
|
213
|
+
return ir.Equality(origin=origin, left=arguments[0], right=arguments[1], total=True)
|
|
214
|
+
total = function.properties((ir.Argument(),) * len(arguments), None).total is not None
|
|
215
|
+
composites = [
|
|
216
|
+
(value, argument) for value, argument in zip(values, arguments)
|
|
217
|
+
if function.name in _ORDER_COMPARISONS and total and self._is_composite(value, lower)
|
|
218
|
+
]
|
|
219
|
+
if composites:
|
|
220
|
+
function, arguments = self._composite_comparison(expression, function, arguments, composites, self._origin(expression, line or _source_line(expression)))
|
|
221
|
+
return self._typed_call(expression, ir.Call(origin=origin, function=function, arguments=arguments, description=description))
|
|
227
222
|
if isinstance(expression, _NOT_A_FUNCTION_OF_ITS_COLUMNS):
|
|
228
223
|
# A function SQLGlot does not know has the type the dialect gives it, if any.
|
|
229
|
-
opaque = ir.OpaqueExpression(origin=origin, description=description, typing=self.
|
|
224
|
+
opaque = ir.OpaqueExpression(origin=origin, description=description, typing=functions.fixed_typing(self.dialect, expression) if isinstance(expression, exp.Anonymous) or functions.volatile(self.dialect, expression) else None)
|
|
230
225
|
if isinstance(expression, exp.Anonymous):
|
|
231
226
|
self._typed_call(expression, opaque)
|
|
232
227
|
if isinstance(expression, exp.Window):
|
|
233
228
|
if _row_number_window(expression) is not None:
|
|
234
229
|
# An integer type in every engine, whichever (docs/dialects.md).
|
|
235
|
-
opaque = replace(opaque, typing=
|
|
230
|
+
opaque = replace(opaque, typing=declared_typing(exp.DataType.build("BIGINT", dialect=self.dialect), self.dialect))
|
|
236
231
|
self._unsupported.append((opaque, "a window function (other than a row_number() select item or QUALIFY row_number() ... = 1)"))
|
|
237
232
|
return opaque
|
|
238
233
|
if isinstance(expression, exp.Case) or isinstance(expression, exp.If):
|
|
239
234
|
# A searched CASE (a simple one is a SimpleCase) or IF: conditions and results, flat.
|
|
240
235
|
parts = _selection_parts(expression)
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
236
|
+
results = tuple(index for index, (_, is_result) in enumerate(parts) if is_result)
|
|
237
|
+
return ir.Call(
|
|
238
|
+
origin=origin, function=functions.selection(type(expression).__name__.upper(), len(parts), results),
|
|
239
|
+
arguments=tuple(lower(part) for part, _ in parts), description=description,
|
|
244
240
|
)
|
|
245
241
|
children = list(expression.iter_expressions())
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
242
|
+
return self._typed_call(expression, ir.Call(
|
|
243
|
+
origin=origin, function=functions.unmodelled(expression, len(children)),
|
|
244
|
+
arguments=tuple(lower(child) for child in children), description=description,
|
|
245
|
+
))
|
|
250
246
|
|
|
251
|
-
def _typed_call[T: ir.Call | ir.
|
|
247
|
+
def _typed_call[T: ir.Call | ir.OpaqueExpression](self: IrParser, expression: Expr, call: T) -> T:
|
|
252
248
|
"""`call`, warning `unknown-function` once when it is a function call
|
|
253
|
-
whose result type sqlassert does not know for the dialect:
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
not as an unknown type further down. Operators, CASE, NULLIF
|
|
258
|
-
arithmetic are typed by their operands (`rules/value_typing.py`)
|
|
259
|
-
are not function calls here."""
|
|
260
|
-
untyped = call.
|
|
249
|
+
whose result type sqlassert does not know for the dialect: the
|
|
250
|
+
function table (`functions/table.py`) gives it none, fixed or
|
|
251
|
+
following an argument's. Its value then has no known type, so an
|
|
252
|
+
equality on it binds nothing; the warning names the gap where it is
|
|
253
|
+
written, not as an unknown type further down. Operators, CASE, NULLIF
|
|
254
|
+
and arithmetic are typed by their operands (`rules/value_typing.py`)
|
|
255
|
+
and are not function calls here."""
|
|
256
|
+
untyped = not call.function.typed if isinstance(call, ir.Call) else call.typing is None
|
|
261
257
|
if not untyped or not isinstance(expression, exp.Func) or isinstance(expression, _OPERAND_TYPED) or id(expression) in self._untyped_calls:
|
|
262
258
|
return call
|
|
263
259
|
self._untyped_calls.add(id(expression))
|
|
@@ -313,11 +309,17 @@ class _Expressions:
|
|
|
313
309
|
Trino. So it also takes each composite operand's Elements, as a
|
|
314
310
|
non-strict, total argument. A composite column or CAST, whose elements
|
|
315
311
|
the SQL does not show, is noted for a warning."""
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
312
|
+
count, extra = len(arguments), len(composites)
|
|
313
|
+
|
|
314
|
+
def properties(summaries: tuple[ir.Argument, ...], result: ir.ValueTyping | None) -> ir.CallProperties:
|
|
315
|
+
compared = function.properties(summaries[:count], result)
|
|
316
|
+
assert compared.total is not None
|
|
317
|
+
return ir.CallProperties(
|
|
318
|
+
strict=compared.strict + (False,) * extra, total=compared.total + (True,) * extra,
|
|
319
|
+
respects=compared.respects + (False,) * extra, reflects=compared.reflects + (False,) * extra, reason=compared.reason,
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
widened = replace(function, arity=count + extra, properties=properties)
|
|
321
323
|
elements = tuple(ir.Elements(origin=argument.origin, operand=argument) for _, argument in composites)
|
|
322
324
|
for value, argument in composites:
|
|
323
325
|
while isinstance(value, exp.Paren):
|
|
@@ -517,13 +519,13 @@ _COMPOSITE_TYPES = {exp.DataType.Type.ARRAY, exp.DataType.Type.LIST, exp.DataTyp
|
|
|
517
519
|
|
|
518
520
|
# The Builtins that compare two values, which compare composites element by element.
|
|
519
521
|
# Never NULL, in every dialect: a NULL operand is a value they compare.
|
|
520
|
-
_IS_DISTINCT_FROM = ir.Builtin(
|
|
522
|
+
_IS_DISTINCT_FROM = ir.Builtin.constant("IS DISTINCT FROM", (False, False), (False, False))
|
|
521
523
|
# Never NULL: TRUE or FALSE, whatever its subquery returns.
|
|
522
|
-
_EXISTS = ir.Builtin(
|
|
524
|
+
_EXISTS = ir.Builtin.constant("EXISTS", (False,), (False,))
|
|
523
525
|
_ORDER_COMPARISONS = {"<>", ">", ">=", "<", "<=", "BETWEEN"}
|
|
524
526
|
# Never NULL: `NULL IS TRUE` is FALSE, so never TRUE where the operand is NULL.
|
|
525
|
-
_IS_TRUE = ir.Builtin(
|
|
526
|
-
_IS_FALSE = ir.Builtin(
|
|
527
|
+
_IS_TRUE = ir.Builtin.constant("IS TRUE", (False,), (False,), true_only_if_argument=True)
|
|
528
|
+
_IS_FALSE = ir.Builtin.constant("IS FALSE", (False,), (False,), rejecting=(True,))
|
|
527
529
|
|
|
528
530
|
|
|
529
531
|
@cache
|
|
@@ -533,7 +535,7 @@ def _any_comparison(node: type[Expr]) -> ir.Builtin:
|
|
|
533
535
|
`ALL`, which is TRUE over no values."""
|
|
534
536
|
names: dict[type[Expr], str] = {exp.EQ: "=", exp.NEQ: "<>", exp.GT: ">", exp.GTE: ">=", exp.LT: "<", exp.LTE: "<="}
|
|
535
537
|
name = names[node]
|
|
536
|
-
return ir.Builtin(
|
|
538
|
+
return ir.Builtin.constant(f"{name} ANY", (False, False), None, rejecting=(True, False))
|
|
537
539
|
|
|
538
540
|
# Comparisons, whose operands a zoned timestamp's text may be.
|
|
539
541
|
_COMPARISONS = (exp.EQ, exp.NEQ, exp.GT, exp.GTE, exp.LT, exp.LTE, exp.NullSafeEQ, exp.NullSafeNEQ, exp.In, exp.Like, exp.ILike, exp.Between)
|
|
@@ -563,9 +565,16 @@ def _cast_integer_literal(expression: Expr) -> ir.LiteralValue | None:
|
|
|
563
565
|
|
|
564
566
|
_PLAIN_INTEGER = re.compile(r"0|[1-9][0-9]{0,18}")
|
|
565
567
|
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
568
|
+
|
|
569
|
+
def _never_total(function: ir.Builtin) -> ir.Builtin:
|
|
570
|
+
"""`function`, but possibly NULL for non-null arguments: a CAST from JSON,
|
|
571
|
+
whose `null` casts to NULL."""
|
|
572
|
+
|
|
573
|
+
def properties(arguments: tuple[ir.Argument, ...], result: ir.ValueTyping | None) -> ir.CallProperties:
|
|
574
|
+
return replace(function.properties(arguments, result), total=None)
|
|
575
|
+
|
|
576
|
+
return replace(function, properties=properties)
|
|
577
|
+
|
|
569
578
|
|
|
570
579
|
# Functions whose type follows their operands' (`rules/value_typing.py`), or that
|
|
571
580
|
# are not calls of a named function: no `unknown-function` warning.
|
sqlassert/ir/convert/parser.py
CHANGED
|
@@ -67,8 +67,6 @@ class IrConversionResult:
|
|
|
67
67
|
@dataclass
|
|
68
68
|
class IrParser(_Schema, _Scopes, _Queries, _Sources, _ValueTypes, _Joins, _Selects, _Subqueries, _Aggregation, _Windows, _Expressions, _Markers):
|
|
69
69
|
dialect: str
|
|
70
|
-
# Unenforced keys and foreign keys become Property Declarations, as `RELY` makes them.
|
|
71
|
-
trust_unenforced_keys: bool = True
|
|
72
70
|
# Relations a caller binds Properties onto after conversion, by name as
|
|
73
71
|
# SQL writes it, with the columns it names (the dbt plugin's relationships
|
|
74
72
|
# tests): each is reached as a Foreign Key marker reaches its referenced
|
|
@@ -148,8 +146,6 @@ class IrParser(_Schema, _Scopes, _Queries, _Sources, _ValueTypes, _Joins, _Selec
|
|
|
148
146
|
_marker_targets: dict[int, _Symbol] = field(default_factory=dict)
|
|
149
147
|
_marker_references: list[_MarkerReference] = field(default_factory=list)
|
|
150
148
|
_constraint_references: list[_ConstraintReference] = field(default_factory=list)
|
|
151
|
-
# Constraints an ALTER TABLE ... NOT VALID added: rows already there were never checked.
|
|
152
|
-
_unvalidated: set[int] = field(default_factory=set)
|
|
153
149
|
# The USING columns merged so far, for the qualifier of each one's binding.
|
|
154
150
|
_using_columns: int = 0
|
|
155
151
|
|
sqlassert/ir/convert/schema.py
CHANGED
|
@@ -7,15 +7,16 @@ from __future__ import annotations
|
|
|
7
7
|
import re
|
|
8
8
|
from collections.abc import Iterable, Mapping
|
|
9
9
|
from dataclasses import replace
|
|
10
|
-
from typing import TYPE_CHECKING
|
|
10
|
+
from typing import TYPE_CHECKING
|
|
11
11
|
|
|
12
12
|
from sqlglot import Expr, exp
|
|
13
13
|
|
|
14
14
|
from sqlassert import diagnostics as diag
|
|
15
15
|
from sqlassert import ir
|
|
16
|
+
from sqlassert.declared_types import column_typing
|
|
16
17
|
from sqlassert.dialects import DialectSemantics
|
|
17
18
|
from sqlassert.diagnostics import Diagnostic, quoted_all
|
|
18
|
-
from sqlassert.properties import EnumeratedDomain, NonNullColumn,
|
|
19
|
+
from sqlassert.properties import EnumeratedDomain, NonNullColumn, ReferentialCoverage, UniqueSet
|
|
19
20
|
from sqlassert.provenance import ORIGIN_META, Origin, SQL
|
|
20
21
|
from sqlassert.sql_parse import literal_value
|
|
21
22
|
from sqlassert.ir.convert.shared import _Symbol, _Binding, _ConstraintReference, _source_line, _missing, _qualified_name, _unwrap_query
|
|
@@ -115,8 +116,6 @@ class _Schema:
|
|
|
115
116
|
return
|
|
116
117
|
symbol.constraints.extend(added)
|
|
117
118
|
symbol.not_null.update(not_null)
|
|
118
|
-
if statement.args.get("not_valid"):
|
|
119
|
-
self._unvalidated.update(id(constraint) for constraint in added)
|
|
120
119
|
|
|
121
120
|
def _created_before(self: IrParser, table: exp.Table, statement: Expr) -> _Symbol | None:
|
|
122
121
|
"""The table `statement` amends, which a CREATE TABLE earlier in the
|
|
@@ -170,7 +169,7 @@ class _Schema:
|
|
|
170
169
|
collated = {name for name, definition in by_name.items() if _collated(definition)}
|
|
171
170
|
by_name = {name: definition for name, definition in by_name.items() if name not in collated}
|
|
172
171
|
typed = tuple(
|
|
173
|
-
replace(column, typing=
|
|
172
|
+
replace(column, typing=column_typing(by_name[column.name], self.dialect)) if column.name in by_name else column
|
|
174
173
|
for column in columns
|
|
175
174
|
)
|
|
176
175
|
for column in typed:
|
|
@@ -214,11 +213,7 @@ class _Schema:
|
|
|
214
213
|
reference.origin,
|
|
215
214
|
))
|
|
216
215
|
continue
|
|
217
|
-
|
|
218
|
-
if trust is not None:
|
|
219
|
-
(self._knowledge if trust == "enforced" else self._declarations).append(
|
|
220
|
-
ReferentialCoverage(columns=columns, referenced_columns=referenced)
|
|
221
|
-
)
|
|
216
|
+
self._knowledge.append(ReferentialCoverage(columns=columns, referenced_columns=referenced))
|
|
222
217
|
|
|
223
218
|
def _primary_key(self: IrParser, symbol: _Symbol) -> tuple[str, ...] | None:
|
|
224
219
|
"""A declared table's primary key, from its SQL or the catalog alike."""
|
|
@@ -228,8 +223,7 @@ class _Schema:
|
|
|
228
223
|
|
|
229
224
|
def _table_knowledge(self: IrParser, relation: ir.NamedRelation, symbol: _Symbol) -> None:
|
|
230
225
|
"""A declared table's ENUM types, NOT NULL columns, keys and CHECK
|
|
231
|
-
domains: Knowledge
|
|
232
|
-
Declarations where they are trusted (`_key_trust`)."""
|
|
226
|
+
domains: Knowledge, whether or not the database enforces them (ADR 0012)."""
|
|
233
227
|
statement = symbol.statement
|
|
234
228
|
if statement is None:
|
|
235
229
|
return
|
|
@@ -269,21 +263,14 @@ class _Schema:
|
|
|
269
263
|
members = tuple(columns[name.lower()] for name in column_names if name.lower() in columns)
|
|
270
264
|
if len(members) != len(column_names):
|
|
271
265
|
continue
|
|
272
|
-
|
|
273
|
-
if
|
|
274
|
-
|
|
275
|
-
facts: list[Property] = [UniqueSet(columns=frozenset(members))]
|
|
276
|
-
if primary and (trust == "declared" or self.semantics.primary_key_not_null):
|
|
277
|
-
facts.extend(NonNullColumn(column=member) for member in members if member.name.lower() not in non_null)
|
|
278
|
-
(self._knowledge if trust == "enforced" else self._declarations).extend(facts)
|
|
266
|
+
self._knowledge.append(UniqueSet(columns=frozenset(members)))
|
|
267
|
+
if primary and self.semantics.primary_key_not_null:
|
|
268
|
+
self._knowledge.extend(NonNullColumn(column=member) for member in members if member.name.lower() not in non_null)
|
|
279
269
|
for parts, index in symbol.expression_keys:
|
|
280
270
|
members = self._expression_key(relation, parts, index)
|
|
281
271
|
if members is None:
|
|
282
272
|
continue
|
|
283
|
-
|
|
284
|
-
trust = self._key_trust(exp.UniqueColumnConstraint(), symbol, names)
|
|
285
|
-
if trust is not None:
|
|
286
|
-
(self._knowledge if trust == "enforced" else self._declarations).append(UniqueSet(columns=frozenset(members)))
|
|
273
|
+
self._knowledge.append(UniqueSet(columns=frozenset(members)))
|
|
287
274
|
for check in checks:
|
|
288
275
|
self._check_knowledge(check, symbol, columns, types)
|
|
289
276
|
|
|
@@ -302,11 +289,7 @@ class _Schema:
|
|
|
302
289
|
self._constraint_origin(check, symbol),
|
|
303
290
|
))
|
|
304
291
|
return
|
|
305
|
-
|
|
306
|
-
if trust is None:
|
|
307
|
-
return
|
|
308
|
-
facts = [EnumeratedDomain(column=columns[name], values=values) for name, values in domains]
|
|
309
|
-
(self._knowledge if trust == "enforced" else self._declarations).extend(facts)
|
|
292
|
+
self._knowledge.extend(EnumeratedDomain(column=columns[name], values=values) for name, values in domains)
|
|
310
293
|
|
|
311
294
|
def _expression_key(
|
|
312
295
|
self: IrParser, relation: ir.NamedRelation, parts: list[Expr], index: exp.Create
|
|
@@ -340,51 +323,6 @@ class _Schema:
|
|
|
340
323
|
return None
|
|
341
324
|
return tuple(found)
|
|
342
325
|
|
|
343
|
-
def _key_trust(self: IrParser, constraint: Expr, symbol: _Symbol, columns: tuple[str, ...]) -> Literal["enforced", "declared"] | None:
|
|
344
|
-
"""Whether a key or foreign key constraint holds: enforced by the
|
|
345
|
-
database (Knowledge), trusted by its author (a Property Declaration:
|
|
346
|
-
marked `RELY`, or any unenforced one under `trust_unenforced_keys`),
|
|
347
|
-
or neither, which a warning reports. An unenforced one is never
|
|
348
|
-
Knowledge, so never proves anything by itself (ADR 0005)."""
|
|
349
|
-
assert symbol.statement is not None
|
|
350
|
-
foreign = isinstance(constraint, exp.ForeignKey | exp.Reference)
|
|
351
|
-
check = isinstance(constraint, exp.CheckColumnConstraint)
|
|
352
|
-
reference = constraint.args.get("reference") if isinstance(constraint, exp.ForeignKey) else constraint
|
|
353
|
-
options = {str(option).upper() for option in (reference.args.get("options") or ())} if isinstance(reference, Expr) else set()
|
|
354
|
-
meaning = self.semantics
|
|
355
|
-
reason = None
|
|
356
|
-
if "NOT ENFORCED" in options:
|
|
357
|
-
reason = "it is declared NOT ENFORCED"
|
|
358
|
-
elif id(constraint) in self._unvalidated:
|
|
359
|
-
reason = "ALTER TABLE ... NOT VALID added it, so rows already in the table were never checked"
|
|
360
|
-
elif "DEFERRABLE" in options or "INITIALLY DEFERRED" in options:
|
|
361
|
-
reason = "it is DEFERRABLE, so a transaction may see it violated"
|
|
362
|
-
elif (meaning.check_constraints if check else meaning.foreign_keys if foreign else meaning.unique_keys) != "enforced":
|
|
363
|
-
reason = f"{self.dialect} does not enforce it"
|
|
364
|
-
elif isinstance(constraint, exp.Reference) and not meaning.inline_references:
|
|
365
|
-
reason = f"{self.dialect} before 9.0 ignores a column-level REFERENCES"
|
|
366
|
-
elif foreign and meaning.foreign_key_engines is not None and (engine := _engine(symbol)) not in meaning.foreign_key_engines:
|
|
367
|
-
reason = (
|
|
368
|
-
f"ENGINE={engine} does not enforce foreign keys" if engine is not None
|
|
369
|
-
else "its table names no ENGINE, and the server's default_storage_engine may not enforce foreign keys"
|
|
370
|
-
)
|
|
371
|
-
if reason is None:
|
|
372
|
-
return "enforced"
|
|
373
|
-
if ("RELY" in options and meaning.rely) or self.trust_unenforced_keys:
|
|
374
|
-
return "declared"
|
|
375
|
-
kind = "check constraint" if check else "foreign key" if foreign else "primary key" if isinstance(constraint, exp.PrimaryKey | exp.PrimaryKeyColumnConstraint) else "unique constraint"
|
|
376
|
-
fixes = ["mark it RELY"] if meaning.rely and not check else []
|
|
377
|
-
if foreign and meaning.foreign_key_engines is not None and _engine(symbol) is None:
|
|
378
|
-
fixes.append("write ENGINE=InnoDB")
|
|
379
|
-
fixes.append("analyze with trust_unenforced_keys=True")
|
|
380
|
-
self._warnings.append(Diagnostic(
|
|
381
|
-
diag.UNENFORCED_CONSTRAINT,
|
|
382
|
-
f"the {kind} ({quoted_all(columns)}) of {symbol.name} is not Knowledge, since {reason}: "
|
|
383
|
-
f"if the data satisfies it, {' or '.join(fixes)}",
|
|
384
|
-
self._constraint_origin(constraint, symbol),
|
|
385
|
-
))
|
|
386
|
-
return None
|
|
387
|
-
|
|
388
326
|
def _constraint_origin(self: IrParser, constraint: Expr, symbol: _Symbol) -> Origin:
|
|
389
327
|
"""Where a table's constraint is stated: the catalog for one a catalog
|
|
390
328
|
declares (`ORIGIN_META`), else the SQL, at its line or its table's."""
|
|
@@ -597,10 +535,3 @@ def _array_values(array: Expr) -> list[Expr] | None:
|
|
|
597
535
|
values = _array_values(array.this) if to.this == exp.DataType.Type.ARRAY and len(to.expressions) == 1 else None
|
|
598
536
|
return None if values is None else [exp.Cast(this=value, to=to.expressions[0].copy()) for value in values]
|
|
599
537
|
return [value.copy() for value in array.expressions] if isinstance(array, exp.Array) else None
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
def _engine(symbol: _Symbol) -> str | None:
|
|
603
|
-
"""The storage ENGINE a CREATE TABLE names (lower-cased), if any."""
|
|
604
|
-
assert symbol.statement is not None
|
|
605
|
-
engine = symbol.statement.find(exp.EngineProperty)
|
|
606
|
-
return engine.name.lower() if engine is not None else None
|
sqlassert/ir/convert/selects.py
CHANGED
|
@@ -9,7 +9,7 @@ from typing import TYPE_CHECKING
|
|
|
9
9
|
|
|
10
10
|
from sqlglot import Expr, exp
|
|
11
11
|
|
|
12
|
-
from sqlassert import ir
|
|
12
|
+
from sqlassert import functions, ir
|
|
13
13
|
from sqlassert.provenance import Origin
|
|
14
14
|
from sqlassert.sql_parse import grouping
|
|
15
15
|
from sqlassert.ir.convert.shared import (
|
|
@@ -23,8 +23,8 @@ if TYPE_CHECKING:
|
|
|
23
23
|
|
|
24
24
|
class _Selects:
|
|
25
25
|
def _expand_stars(self: IrParser, items: list[Expr], lowered: _Lowered, *, grouped: bool) -> tuple[list[Expr], str | None] | None:
|
|
26
|
-
"""`items` with each star (`*`, `t.*`, with
|
|
27
|
-
|
|
26
|
+
"""`items` with each star (`*`, `t.*`, with the dialect's
|
|
27
|
+
`star_modifiers`) as the columns it selects, when every input column is
|
|
28
28
|
known (`_star_expansion`); and why a star stayed one item although
|
|
29
29
|
they are, which the caller reports. Each star expands on its own: one
|
|
30
30
|
that cannot is an opaque item beside the others' columns. Not a
|
|
@@ -33,7 +33,8 @@ class _Selects:
|
|
|
33
33
|
name another item may repeat) is unknown, and the select is opaque
|
|
34
34
|
(None). A star in a GROUP BY select is left as it is."""
|
|
35
35
|
stars = [star for item in items if (star := _projection_star(item)) is not None]
|
|
36
|
-
|
|
36
|
+
modifiers = {_MODIFIERS.get(key, key) for star in stars for key, value in star.args.items() if value}
|
|
37
|
+
if modifiers and (not modifiers <= set(self.semantics.star_modifiers) or grouped or not lowered.relation.is_schema_complete):
|
|
37
38
|
return None
|
|
38
39
|
if not lowered.relation.is_schema_complete:
|
|
39
40
|
return items, None # Connection Warnings say which columns are missing.
|
|
@@ -44,7 +45,7 @@ class _Selects:
|
|
|
44
45
|
renamed = False
|
|
45
46
|
for item in items:
|
|
46
47
|
star = _projection_star(item)
|
|
47
|
-
columns = None if star is None else _star_expansion(item, star, lowered)
|
|
48
|
+
columns = None if star is None else _star_expansion(item, star, lowered, exact=self.semantics.case_sensitive_names)
|
|
48
49
|
if columns is None:
|
|
49
50
|
expanded.append(item)
|
|
50
51
|
elif isinstance(columns, str):
|
|
@@ -69,6 +70,12 @@ class _Selects:
|
|
|
69
70
|
keys = grouping(select)
|
|
70
71
|
items = select.expressions
|
|
71
72
|
unexpanded = None
|
|
73
|
+
if any(isinstance(item, exp.Apply) or item.find(exp.Columns) for item in items):
|
|
74
|
+
# ClickHouse's `* APPLY(f)` and COLUMNS('re'), DuckDB's COLUMNS(...):
|
|
75
|
+
# which columns, and how many, the data's names decide.
|
|
76
|
+
opaque = self._opaque_relation(select)
|
|
77
|
+
self._unsupported.append((opaque, "a modified star projection"))
|
|
78
|
+
return opaque
|
|
72
79
|
if any(_projection_star(item) is not None for item in items):
|
|
73
80
|
expansion = self._expand_stars(items, lowered, grouped=keys is not None)
|
|
74
81
|
if expansion is None:
|
|
@@ -217,7 +224,7 @@ class _Selects:
|
|
|
217
224
|
case exp.Window() if _row_number_window(expression) is not None:
|
|
218
225
|
kind = exp.DataType.build("BIGINT", dialect=self.dialect)
|
|
219
226
|
case _:
|
|
220
|
-
kind = self.
|
|
227
|
+
kind = functions.result_type(self.dialect, expression)
|
|
221
228
|
if kind is not None:
|
|
222
229
|
self._declared_types[column] = kind
|
|
223
230
|
return column
|
|
@@ -245,6 +252,8 @@ def _unsupported_select(select: exp.Select, items: list[Expr], star: str | None)
|
|
|
245
252
|
if any(_projection_star(item) is not None for item in select.expressions):
|
|
246
253
|
clauses.append("*")
|
|
247
254
|
return f"this SELECT form ({', '.join(clauses)})" if clauses else "this SELECT form"
|
|
255
|
+
# A star's modifier by its SQLGlot argument (`DialectSemantics.star_modifiers`).
|
|
256
|
+
_MODIFIERS = {"except_": "except"}
|
|
248
257
|
# The constructs a star that stays one select item is reported as.
|
|
249
258
|
_UNNAMEABLE_STAR = "a star whose columns cannot each be named unambiguously"
|
|
250
259
|
_GROUPED_STAR = "a star in a GROUP BY select"
|
|
@@ -277,15 +286,18 @@ def _carrying(column: ir.OutputColumn, scope: ir.RelationExpr) -> ir.OutputColum
|
|
|
277
286
|
return found[0] if len(found) == 1 else None
|
|
278
287
|
|
|
279
288
|
|
|
280
|
-
def _star_expansion(item: Expr, star: exp.Star, lowered: _Lowered) -> tuple[list[Expr], bool] | str:
|
|
289
|
+
def _star_expansion(item: Expr, star: exp.Star, lowered: _Lowered, *, exact: bool = False) -> tuple[list[Expr], bool] | str:
|
|
281
290
|
"""The select items a star stands for, one per column in the input's
|
|
282
291
|
order, and whether any is renamed; else why it stays one item.
|
|
283
292
|
|
|
284
293
|
Each item is written as its column's qualified name and carries the
|
|
285
294
|
column itself (`_Carried`), which its lowering binds: a derived table's
|
|
286
295
|
repeat, which no name reaches, is carried on to the next relation so.
|
|
287
|
-
Modifiers
|
|
288
|
-
|
|
296
|
+
Modifiers act on the star's own columns, each named by exactly one of
|
|
297
|
+
them (spelled exactly as declared where names are case-sensitive,
|
|
298
|
+
`exact`), never by a name an engine may have given a repeat, nor by
|
|
299
|
+
`q.c` where `q` also names one of them (Spark's `* EXCEPT (s.f)` drops a
|
|
300
|
+
field of the struct `s`)."""
|
|
289
301
|
bindings = lowered.bindings
|
|
290
302
|
if isinstance(item, exp.Column):
|
|
291
303
|
# `a.*` selects all of a's columns, a USING column's own side included.
|
|
@@ -297,17 +309,20 @@ def _star_expansion(item: Expr, star: exp.Star, lowered: _Lowered) -> tuple[list
|
|
|
297
309
|
if not bindings or any(b.name == "*" for b in bindings) or not all(column in covered for column in lowered.relation.output_columns):
|
|
298
310
|
return _UNNAMEABLE_STAR
|
|
299
311
|
|
|
300
|
-
def find(
|
|
301
|
-
|
|
302
|
-
|
|
312
|
+
def find(spelled: str, qualifier: str = "", schema: str = "") -> int | None:
|
|
313
|
+
name = spelled.lower()
|
|
314
|
+
if _renamed(bindings, qualifier, schema, name) is not None or (qualifier and any(b.name == qualifier for b in bindings)):
|
|
315
|
+
return None # May be a name the engine gave a repeated column, or a struct's field.
|
|
303
316
|
found = [index for index, b in enumerate(bindings) if _named((b,), qualifier or b.qualifier, name, schema)]
|
|
304
|
-
|
|
317
|
+
if len(found) != 1 or (exact and bindings[found[0]].column.name != spelled):
|
|
318
|
+
return None
|
|
319
|
+
return found[0]
|
|
305
320
|
|
|
306
321
|
def star_column(column: Expr) -> int | None:
|
|
307
|
-
return find(column.name
|
|
322
|
+
return find(column.name, column.table.lower(), _schema_path(column)) if isinstance(column, exp.Column) else None
|
|
308
323
|
|
|
309
324
|
excluded = {star_column(column) for column in star.args.get("except_") or ()}
|
|
310
|
-
replaced = {find(alias.alias
|
|
325
|
+
replaced = {find(alias.alias): alias for alias in star.args.get("replace") or ()}
|
|
311
326
|
renamed = {star_column(alias.this): alias.args.get("alias") for alias in star.args.get("rename") or ()}
|
|
312
327
|
if (
|
|
313
328
|
star.args.get("ilike") or None in excluded or None in replaced or None in renamed
|
sqlassert/ir/convert/shared.py
CHANGED
|
@@ -9,6 +9,7 @@ from typing import Literal, TypeGuard
|
|
|
9
9
|
from sqlglot import Expr, exp
|
|
10
10
|
|
|
11
11
|
from sqlassert import ir
|
|
12
|
+
from sqlassert.declared_types import TEXT_TYPES as _TEXT_TYPES
|
|
12
13
|
from sqlassert.ir.names import may_be_renamed
|
|
13
14
|
from sqlassert.provenance import Origin
|
|
14
15
|
from sqlassert.sql_parse import ColumnMarker, marker_position, written_at
|
|
@@ -215,8 +216,6 @@ def _missing(relation: ir.RelationExpr, names: Iterable[str]) -> list[str]:
|
|
|
215
216
|
known = {column.name.lower() for column in relation.output_columns}
|
|
216
217
|
return [name for name in names if name.lower() not in known]
|
|
217
218
|
|
|
218
|
-
_TEXT_TYPES = {exp.DataType.Type.VARCHAR, exp.DataType.Type.TEXT}
|
|
219
|
-
|
|
220
219
|
|
|
221
220
|
def _is_named_table(source: Expr) -> TypeGuard[exp.Table]:
|
|
222
221
|
"""A FROM source naming a table, view or CTE. SQLGlot parses a
|
|
@@ -407,7 +406,7 @@ def _ended_set_operation(query: exp.Query, offset: int) -> exp.SetOperation | No
|
|
|
407
406
|
|
|
408
407
|
_NOT_A_FUNCTION_OF_ITS_COLUMNS = (
|
|
409
408
|
exp.Anonymous, exp.Rand, exp.Randn, exp.Uuid, exp.AggFunc, exp.Filter, exp.WithinGroup, exp.Window, exp.Query, exp.Subquery,
|
|
410
|
-
exp.CurrentDate, exp.CurrentDatetime, exp.CurrentTime, exp.CurrentTimestamp, exp.Placeholder, exp.Parameter, exp.Star,
|
|
409
|
+
exp.CurrentDate, exp.CurrentDatetime, exp.CurrentTime, exp.CurrentTimestamp, exp.Localtimestamp, exp.Seq4, exp.Placeholder, exp.Parameter, exp.Star,
|
|
411
410
|
)
|
|
412
411
|
|
|
413
412
|
|