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,158 @@
1
+ """How a SQL type compares: the `ir.ValueTyping` of a column declared with it,
2
+ of a CAST's target, and of a type a dialect's function table names
3
+ (`sqlassert/functions/`). One place, so a declared column and a function's
4
+ result type of the same SQL type compare alike."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from functools import cache
9
+
10
+ from sqlglot import exp
11
+
12
+ from sqlassert import ir
13
+ from sqlassert.dialects import DialectSemantics, semantics
14
+
15
+ TEXT_TYPES = {exp.DataType.Type.VARCHAR, exp.DataType.Type.TEXT}
16
+
17
+
18
+ def declared_typing(kind: exp.DataType, dialect: str) -> ir.ValueTyping | None:
19
+ """How a column declared with `kind` compares in `dialect`; None when it has no comparison type."""
20
+ return column_typing(exp.ColumnDef(kind=kind), dialect)
21
+
22
+
23
+ def column_typing(definition: exp.ColumnDef, dialect: str) -> ir.ValueTyping | None:
24
+ meaning = semantics(dialect)
25
+ comparison_type = _comparison_type(definition, dialect, meaning)
26
+ if comparison_type is None:
27
+ return None
28
+ kind = definition.args["kind"]
29
+ family = _FAMILIES.get(kind.this)
30
+ parameters = _parameters(kind)
31
+ length = precision = scale = None
32
+ match family:
33
+ case "text" if kind.expressions:
34
+ # A length that is not a number (`VARCHAR(MAX)`) is 0: some length, not known to hold the value.
35
+ length = parameters[0] if parameters else 0
36
+ case "decimal" if parameters:
37
+ precision, scale = parameters[0], parameters[1] if len(parameters) > 1 else 0
38
+ case "time" | "timestamp" | "timestamptz" if parameters:
39
+ precision = parameters[0]
40
+ case _:
41
+ pass
42
+ return ir.ValueTyping(
43
+ comparison_type, _is_binary_text(definition, meaning), _identity_comparison(definition, dialect, meaning), _exact_numeric(definition, meaning),
44
+ floating=kind.this in FLOATS, integer=_INTEGER_RANK.get(kind.this),
45
+ text=kind.this in exp.DataType.TEXT_TYPES, temporal=kind.this in exp.DataType.TEMPORAL_TYPES,
46
+ family=family, length=length, precision=precision, scale=scale, casts=cast_table(meaning),
47
+ )
48
+
49
+
50
+ @cache
51
+ def cast_table(meaning: DialectSemantics) -> ir.CastTable:
52
+ """The dialect's cast table (`DialectSemantics.casts`), one per dialect."""
53
+ return ir.CastTable(meaning.casts)
54
+
55
+
56
+ def _comparison_type(definition: exp.ColumnDef, dialect: str, meaning: DialectSemantics) -> str | None:
57
+ kind = definition.args.get("kind")
58
+ if not isinstance(kind, exp.DataType):
59
+ return None
60
+ if _unscaled_decimal(kind, meaning):
61
+ return None
62
+ return _type_name(kind, dialect)
63
+
64
+
65
+ def _type_name(kind: exp.DataType, dialect: str) -> str:
66
+ """The name two values of one comparison type share: the type's SQL,
67
+ without a date or time type's parameters. TIMESTAMP(3) holds values
68
+ TIMESTAMP(6) holds unchanged, so they compare as one type (ADR 0009)."""
69
+ if kind.this in exp.DataType.TEMPORAL_TYPES and kind.expressions:
70
+ kind = kind.copy()
71
+ kind.set("expressions", [])
72
+ return kind.sql(dialect=dialect)
73
+
74
+
75
+ def _identity_comparison(definition: exp.ColumnDef, dialect: str, meaning: DialectSemantics) -> bool:
76
+ """Declared with a type whose equal values are identical (text only
77
+ when compared by identity)."""
78
+ kind = definition.args.get("kind")
79
+ if not (_comparison_type(definition, dialect, meaning) is not None and isinstance(kind, exp.DataType)):
80
+ return False
81
+ if kind.this == exp.DataType.Type.TIMESTAMPTZ:
82
+ return meaning.zoned_timestamp_is_instant
83
+ if kind.this in exp.DataType.TEXT_TYPES:
84
+ return _is_binary_text(definition, meaning)
85
+ return kind.this in _IDENTITY_TYPES
86
+
87
+
88
+ def _exact_numeric(definition: exp.ColumnDef, meaning: DialectSemantics) -> bool:
89
+ kind = definition.args.get("kind")
90
+ return isinstance(kind, exp.DataType) and kind.this in _EXACT_NUMERIC_TYPES and not _unscaled_decimal(kind, meaning)
91
+
92
+
93
+ def _unscaled_decimal(kind: exp.DataType, meaning: DialectSemantics) -> bool:
94
+ """A Postgres NUMERIC with no scale: 1.0 and 1.00 are equal values that differ."""
95
+ return meaning.unscaled_decimal and kind.this == exp.DataType.Type.DECIMAL and not kind.expressions
96
+
97
+
98
+ def _is_binary_text(definition: exp.ColumnDef, meaning: DialectSemantics) -> bool:
99
+ """Declared VARCHAR or TEXT in a dialect whose default collation is
100
+ binary: compared by identity. CHAR is not: it ignores trailing spaces
101
+ when compared."""
102
+ kind = definition.args.get("kind")
103
+ return isinstance(kind, exp.DataType) and kind.this in TEXT_TYPES and meaning.text_is_binary
104
+
105
+
106
+ def _parameters(kind: exp.DataType) -> tuple[int, ...]:
107
+ """A type's numeric parameters (`DECIMAL(10, 2)`: 10, 2), or none when one is not a number."""
108
+ try:
109
+ return tuple(int(parameter.sql()) for parameter in kind.expressions)
110
+ except ValueError:
111
+ return ()
112
+
113
+
114
+ # The signed integer types, by width (`ir.ValueTyping.integer`).
115
+ _INTEGER_RANK = {
116
+ exp.DataType.Type.TINYINT: 0, exp.DataType.Type.SMALLINT: 1, exp.DataType.Type.MEDIUMINT: 2, exp.DataType.Type.INT: 3,
117
+ exp.DataType.Type.BIGINT: 4, exp.DataType.Type.INT128: 5, exp.DataType.Type.INT256: 6,
118
+ }
119
+
120
+ # The floating-point types: REAL, FLOAT and DOUBLE in any spelling.
121
+ FLOATS = {exp.DataType.Type.FLOAT, exp.DataType.Type.DOUBLE, exp.DataType.Type.UDOUBLE}
122
+
123
+ # The digits of a number literal past which DuckDB's type for it is a DOUBLE.
124
+ EXACT_LITERAL_DIGITS = 38
125
+
126
+
127
+ # Types whose equal values are identical: no collation (text has a comparison
128
+ # type only when compared by identity), no signed zero or NaN, no two
129
+ # spellings of one interval.
130
+ _IDENTITY_TYPES = {
131
+ *exp.DataType.INTEGER_TYPES, *exp.DataType.TEXT_TYPES,
132
+ exp.DataType.Type.DECIMAL, exp.DataType.Type.BOOLEAN, exp.DataType.Type.DATE, exp.DataType.Type.TIME,
133
+ exp.DataType.Type.TIMESTAMP, exp.DataType.Type.UUID,
134
+ # Timestamps without a zone, as each dialect spells them (DuckDB's TIMESTAMP is TIMESTAMPNTZ).
135
+ exp.DataType.Type.TIMESTAMPNTZ, exp.DataType.Type.TIMESTAMP_S, exp.DataType.Type.TIMESTAMP_MS, exp.DataType.Type.TIMESTAMP_NS,
136
+ exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME64,
137
+ }
138
+
139
+ _EXACT_NUMERIC_TYPES = {*exp.DataType.INTEGER_TYPES, exp.DataType.Type.DECIMAL}
140
+
141
+ # The family of each type a cast table classifies (`ir.TypeFamily`): signed
142
+ # integers, decimals, floats, VARCHAR and TEXT (not CHAR, which pads), and the
143
+ # date, time and timestamp types, with and without a zone.
144
+ _T = exp.DataType.Type
145
+ _FAMILIES: dict[exp.DataType.Type, ir.TypeFamily] = {
146
+ **dict.fromkeys(_INTEGER_RANK, "integer"), _T.DECIMAL: "decimal", **dict.fromkeys(FLOATS, "float"),
147
+ _T.VARCHAR: "text", _T.TEXT: "text", _T.BOOLEAN: "boolean", _T.UUID: "uuid",
148
+ _T.DATE: "date", _T.DATE32: "date", _T.TIME: "time",
149
+ **dict.fromkeys((
150
+ _T.TIMESTAMP, _T.TIMESTAMPNTZ, _T.TIMESTAMP_S, _T.TIMESTAMP_MS, _T.TIMESTAMP_NS,
151
+ _T.DATETIME, _T.DATETIME2, _T.DATETIME64, _T.SMALLDATETIME,
152
+ ), "timestamp"),
153
+ _T.TIMESTAMPTZ: "timestamptz", _T.TIMESTAMPLTZ: "timestamptz",
154
+ _T.INTERVAL: "interval",
155
+ **dict.fromkeys((_T.BINARY, _T.VARBINARY, _T.BLOB, _T.TINYBLOB, _T.MEDIUMBLOB, _T.LONGBLOB), "bytes"),
156
+ **dict.fromkeys((_T.JSON, _T.JSONB), "json"), **dict.fromkeys((_T.ARRAY, _T.LIST), "array"), _T.STRUCT: "struct",
157
+ **dict.fromkeys((_T.GEOGRAPHY, _T.GEOMETRY), "geography"),
158
+ }
sqlassert/diagnostics.py CHANGED
@@ -52,7 +52,6 @@ UNANALYZED_ASSERTION = "unanalyzed-assertion"
52
52
  UNATTACHED_MARKER = "unattached-marker"
53
53
  UNBOUND_FOREIGN_KEY = "unbound-foreign-key"
54
54
  UNDECLARED_TABLE = "undeclared-table"
55
- UNENFORCED_CONSTRAINT = "unenforced-constraint"
56
55
  UNKNOWN_ASSERTED_COLUMN = "unknown-asserted-column"
57
56
  UNKNOWN_FUNCTION = "unknown-function"
58
57
  UNRESOLVED_ASSERTED_COLUMN = "unresolved-asserted-column"
@@ -73,9 +72,7 @@ class Diagnostic:
73
72
 
74
73
 
75
74
  # Warnings about the SQL itself, which no connection answers: `analyze_database` keeps them.
76
- # An unenforced constraint among them is one a CREATE TABLE declares, the
77
- # Program's own or the declaration of a catalog table (its CHECKs).
78
75
  SQL_WARNINGS = frozenset({
79
- ALWAYS_NULL_COLUMN, AMBIGUOUS_DUPLICATE_COLUMN, COMPOSITE_COMPARISON, IGNORED_CHECK_CONSTRAINT, UNENFORCED_CONSTRAINT, UNKNOWN_FUNCTION,
76
+ ALWAYS_NULL_COLUMN, AMBIGUOUS_DUPLICATE_COLUMN, COMPOSITE_COMPARISON, IGNORED_CHECK_CONSTRAINT, UNKNOWN_FUNCTION,
80
77
  ZONED_TIMESTAMP_CAST,
81
78
  })