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/__main__.py +2 -131
- sqlassert/check.py +10 -3
- sqlassert/diagnostics.py +19 -6
- sqlassert/dialects.py +69 -22
- sqlassert/discovery/duckdb.py +12 -16
- sqlassert/discovery/fetcher.py +45 -29
- sqlassert/discovery/information_schema.py +4 -3
- sqlassert/discovery/postgres.py +6 -7
- sqlassert/edits.py +240 -0
- sqlassert/hazards.py +574 -0
- sqlassert/ir/__init__.py +3 -1
- sqlassert/ir/convert.py +1315 -183
- sqlassert/ir/model.py +128 -25
- sqlassert/main.py +3 -9
- sqlassert/python_engine.py +63 -6
- sqlassert/reporting.py +3 -0
- sqlassert/rewrites.py +1541 -0
- sqlassert/rules/domain.py +117 -21
- sqlassert/rules/equality.py +238 -29
- sqlassert/rules/exactly_one.py +40 -1
- sqlassert/rules/foreign_key.py +7 -4
- sqlassert/rules/join_cardinality.py +33 -11
- sqlassert/rules/nullability.py +239 -30
- sqlassert/rules/uniqueness.py +355 -52
- sqlassert/sql_parse.py +196 -89
- sqlassert/suggest.py +127 -48
- {sqlassert-0.3.1.dist-info → sqlassert-0.3.3.dist-info}/METADATA +121 -39
- sqlassert-0.3.3.dist-info/RECORD +46 -0
- sqlassert-0.3.3.dist-info/entry_points.txt +2 -0
- sqlassert-0.3.3.dist-info/top_level.txt +2 -0
- sqlassert_cli.py +130 -0
- sqlassert/improvements.py +0 -528
- sqlassert/smells.py +0 -306
- sqlassert-0.3.1.dist-info/RECORD +0 -44
- sqlassert-0.3.1.dist-info/entry_points.txt +0 -2
- sqlassert-0.3.1.dist-info/top_level.txt +0 -1
- {sqlassert-0.3.1.dist-info → sqlassert-0.3.3.dist-info}/WHEEL +0 -0
- {sqlassert-0.3.1.dist-info → sqlassert-0.3.3.dist-info}/licenses/LICENSE +0 -0
sqlassert/__main__.py
CHANGED
|
@@ -1,137 +1,8 @@
|
|
|
1
|
-
"""
|
|
2
|
-
`sqlassert suggest FILE` prints the improvements and markers sqlassert can prove.
|
|
3
|
-
dbt projects are checked by the separate `sqlassert-dbt` package (`integrations/dbt/`)."""
|
|
1
|
+
"""Run the command line with `python -m sqlassert`."""
|
|
4
2
|
|
|
5
|
-
from __future__ import annotations
|
|
6
|
-
|
|
7
|
-
import argparse
|
|
8
3
|
import sys
|
|
9
|
-
from collections.abc import Iterable
|
|
10
|
-
from pathlib import Path
|
|
11
|
-
|
|
12
|
-
from sqlassert import check
|
|
13
|
-
from sqlassert.main import DEFAULT_DIALECT
|
|
14
|
-
from sqlassert.suggest import DEFAULT_MAX_SIZE, suggest
|
|
15
|
-
|
|
16
|
-
# How each suggested Property reads in the listing.
|
|
17
|
-
_KINDS = {
|
|
18
|
-
"ExactlyOneJoin": "Exactly One Join",
|
|
19
|
-
"OneToOneJoin": "One To One Join",
|
|
20
|
-
"ManyToOneJoin": "Many To One Join",
|
|
21
|
-
"OneToManyJoin": "One To Many Join",
|
|
22
|
-
"UniqueJoin": "Unique Join",
|
|
23
|
-
"UniqueSet": "Unique Set",
|
|
24
|
-
"NonNullUniqueSet": "Non-Null Unique Set",
|
|
25
|
-
"NonNullColumns": "Not Null",
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
def main(argv: list[str] | None = None) -> int:
|
|
30
|
-
parser = argparse.ArgumentParser(prog="sqlassert")
|
|
31
|
-
commands = parser.add_subparsers(dest="command", required=True)
|
|
32
|
-
suggest_command = commands.add_parser(
|
|
33
|
-
"suggest", help="list the improvements and markers sqlassert can prove for a SQL Program"
|
|
34
|
-
)
|
|
35
|
-
suggest_command.add_argument("file", help="SQL Program to read, or - for stdin")
|
|
36
|
-
suggest_command.add_argument("--dialect", default=DEFAULT_DIALECT)
|
|
37
|
-
suggest_command.add_argument(
|
|
38
|
-
"--max-size", type=int, default=DEFAULT_MAX_SIZE, help="widest Unique Set searched exhaustively"
|
|
39
|
-
)
|
|
40
|
-
suggest_command.add_argument("--explain", action="store_true", help="print each suggestion's evidence")
|
|
41
|
-
suggest_command.add_argument(
|
|
42
|
-
"--annotate", action="store_true",
|
|
43
|
-
help="paste every suggested marker into FILE (for -, print the annotated SQL instead of the list)",
|
|
44
|
-
)
|
|
45
|
-
check_command = commands.add_parser(
|
|
46
|
-
"check",
|
|
47
|
-
help="analyze SQL Programs and fail when an assertion is UNKNOWN or a Diagnostic is reported",
|
|
48
|
-
description="Analyze each SQL Program from its SQL alone. Exit status: "
|
|
49
|
-
f"{check.EXIT_OK} every assertion PROVED (warnings allowed), {check.EXIT_FINDINGS} an assertion UNKNOWN "
|
|
50
|
-
f"or a Diagnostic reported, {check.EXIT_USAGE} bad arguments, configuration, or unreadable SQL. "
|
|
51
|
-
"Defaults come from [tool.sqlassert] in the nearest pyproject.toml; flags replace them, except --ignore, which adds to them.",
|
|
52
|
-
)
|
|
53
|
-
check_command.add_argument(
|
|
54
|
-
"paths", nargs="*", metavar="PATH",
|
|
55
|
-
help="SQL files, directories (every *.sql under them), or globs; - for stdin (default: [tool.sqlassert] paths)",
|
|
56
|
-
)
|
|
57
|
-
check_command.add_argument("--dialect", help=f"SQL dialect (default: [tool.sqlassert] dialect, else {DEFAULT_DIALECT})")
|
|
58
|
-
ignoring = check_command.add_mutually_exclusive_group()
|
|
59
|
-
ignoring.add_argument(
|
|
60
|
-
"--ignore", action="append", metavar="CODE",
|
|
61
|
-
help="also drop Findings with this code, e.g. undeclared-table, besides [tool.sqlassert] ignore; "
|
|
62
|
-
"repeatable or comma-separated",
|
|
63
|
-
)
|
|
64
|
-
ignoring.add_argument(
|
|
65
|
-
"--only-ignore", action="append", metavar="CODE",
|
|
66
|
-
help="drop Findings with these codes instead of [tool.sqlassert] ignore; repeatable or comma-separated "
|
|
67
|
-
"(--only-ignore '' ignores nothing)",
|
|
68
|
-
)
|
|
69
|
-
check_command.add_argument("--format", choices=sorted(check.FORMATS), default="text")
|
|
70
|
-
check_command.add_argument("--explain", action="store_true", help="print each UNKNOWN assertion's evidence")
|
|
71
|
-
arguments = parser.parse_args(argv)
|
|
72
|
-
if arguments.command == "check":
|
|
73
|
-
return _check(arguments)
|
|
74
|
-
|
|
75
|
-
try:
|
|
76
|
-
sql = check.read_sql(Path(arguments.file))
|
|
77
|
-
except check.UsageError as error:
|
|
78
|
-
print(f"sqlassert suggest: {error}", file=sys.stderr)
|
|
79
|
-
return check.EXIT_USAGE
|
|
80
|
-
report = suggest(sql, dialect=arguments.dialect, max_size=arguments.max_size)
|
|
81
|
-
for diagnostic in report.diagnostics:
|
|
82
|
-
print(f"{diagnostic.code}: {diagnostic.message}", file=sys.stderr)
|
|
83
|
-
for warning in report.warnings:
|
|
84
|
-
print(f"warning: {warning.code}: {warning.message}", file=sys.stderr)
|
|
85
|
-
if arguments.annotate and arguments.file == "-":
|
|
86
|
-
sys.stdout.write(report.annotated())
|
|
87
|
-
return 1 if report.diagnostics else 0
|
|
88
|
-
if arguments.annotate and report.suggestions:
|
|
89
|
-
Path(arguments.file).write_text(report.annotated())
|
|
90
|
-
# Improvements (High) first, then markers (Mid), then smells (Low).
|
|
91
|
-
items = (*report.improvements, *report.suggestions, *report.smells)
|
|
92
|
-
rows = [
|
|
93
|
-
(i.level.value, f"line {i.site.line}", i.site.label, i.rewrite.value, i.message) for i in report.improvements
|
|
94
|
-
] + [
|
|
95
|
-
(s.level.value, f"line {s.site.line}", s.site.label, _KINDS[type(s.property).__name__], s.marker)
|
|
96
|
-
for s in report.suggestions
|
|
97
|
-
] + [
|
|
98
|
-
(s.level.value, f"line {s.site.line}", s.site.label, s.concern.value, s.message) for s in report.smells
|
|
99
|
-
]
|
|
100
|
-
widths = [max((len(row[i]) for row in rows), default=0) for i in range(4)]
|
|
101
|
-
for row, item in zip(rows, items):
|
|
102
|
-
print(" ".join(cell.ljust(width) for cell, width in zip(row[:4], widths)) + " " + row[4])
|
|
103
|
-
if arguments.explain:
|
|
104
|
-
print(check.indented(item.evidence.explain()))
|
|
105
|
-
return 1 if report.diagnostics else 0
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
def _check(arguments: argparse.Namespace) -> int:
|
|
109
|
-
try:
|
|
110
|
-
config = check.load_config(Path.cwd())
|
|
111
|
-
dialect = arguments.dialect or config.dialect
|
|
112
|
-
ignore = (
|
|
113
|
-
_codes(arguments.only_ignore) if arguments.only_ignore is not None
|
|
114
|
-
else config.ignore | _codes(arguments.ignore or ())
|
|
115
|
-
)
|
|
116
|
-
check.validate(dialect, ignore)
|
|
117
|
-
if arguments.paths:
|
|
118
|
-
paths = check.expand(arguments.paths, Path.cwd())
|
|
119
|
-
elif config.paths:
|
|
120
|
-
paths = check.expand(config.paths, config.root)
|
|
121
|
-
else:
|
|
122
|
-
raise check.UsageError("no SQL to check: name files, directories or globs, or set paths in [tool.sqlassert]")
|
|
123
|
-
programs = [(check.display(path), check.read_sql(path)) for path in paths]
|
|
124
|
-
except check.UsageError as error:
|
|
125
|
-
print(f"sqlassert check: {error}", file=sys.stderr)
|
|
126
|
-
return check.EXIT_USAGE
|
|
127
|
-
checked = [check.check(path, sql, dialect=dialect, ignore=ignore) for path, sql in programs]
|
|
128
|
-
sys.stdout.write(check.FORMATS[arguments.format](checked, explain=arguments.explain))
|
|
129
|
-
return check.exit_code(checked)
|
|
130
|
-
|
|
131
4
|
|
|
132
|
-
|
|
133
|
-
"""The codes of repeated, comma-separated flag values."""
|
|
134
|
-
return frozenset(code.strip() for value in values for code in value.split(",") if code.strip())
|
|
5
|
+
from sqlassert_cli import main as main
|
|
135
6
|
|
|
136
7
|
|
|
137
8
|
if __name__ == "__main__":
|
sqlassert/check.py
CHANGED
|
@@ -29,7 +29,7 @@ from urllib.parse import quote
|
|
|
29
29
|
from sqlglot.dialects.dialect import Dialect
|
|
30
30
|
|
|
31
31
|
from sqlassert import diagnostics as diag
|
|
32
|
-
from sqlassert.diagnostics import Diagnostic
|
|
32
|
+
from sqlassert.diagnostics import UNSUPPORTED_CONSTRUCT, Diagnostic
|
|
33
33
|
from sqlassert.main import DEFAULT_DIALECT, analyze
|
|
34
34
|
from sqlassert.provenance import Origin, Span
|
|
35
35
|
from sqlassert.reporting import ASSERTED_KINDS, Outcome, Report
|
|
@@ -99,14 +99,21 @@ def findings(path: str, sql: str, report: Report, *, ignore: Iterable[str] = ())
|
|
|
99
99
|
ignored = frozenset(ignore)
|
|
100
100
|
unknown = [
|
|
101
101
|
Finding(
|
|
102
|
-
path, Severity.ERROR, unproved(assertion.kind),
|
|
102
|
+
path, Severity.ERROR, unproved(assertion.kind),
|
|
103
|
+
f"{_written(sql, assertion.origin)} is not proved (UNKNOWN)"
|
|
104
|
+
+ (f": {assertion.unsupported} is not supported by sqlassert yet, which may be why" if assertion.unsupported else ""),
|
|
103
105
|
assertion.origin, assertion.evidence.explain() if assertion.evidence is not None else None,
|
|
104
106
|
)
|
|
105
107
|
for assertion in report.assertions
|
|
106
108
|
if assertion.outcome is Outcome.UNKNOWN
|
|
107
109
|
]
|
|
108
110
|
reported = [_diagnostic(path, diagnostic, Severity.ERROR) for diagnostic in report.diagnostics]
|
|
109
|
-
|
|
111
|
+
# An unsupported construct an UNKNOWN assertion reached is already named on it.
|
|
112
|
+
named = {assertion.origin for assertion in report.assertions if assertion.unsupported is not None}
|
|
113
|
+
warned = [
|
|
114
|
+
_diagnostic(path, warning, Severity.WARNING) for warning in report.warnings
|
|
115
|
+
if not (warning.code == UNSUPPORTED_CONSTRUCT and warning.origin in named)
|
|
116
|
+
]
|
|
110
117
|
return tuple(
|
|
111
118
|
finding for finding in sorted((*unknown, *reported, *warned), key=_source_order)
|
|
112
119
|
if finding.code not in ignored
|
sqlassert/diagnostics.py
CHANGED
|
@@ -6,27 +6,39 @@ Disproof and never an inference: it says that analysis stopped short, and why.
|
|
|
6
6
|
A warning is a Diagnostic too, reported apart (`Report.warnings`): the program
|
|
7
7
|
is supported, but a fact a connection would supply is missing, so analysis
|
|
8
8
|
treats it as unknown (ADR 0005). So are a constraint the dialect does not
|
|
9
|
-
enforce, and, about the SQL itself (`SQL_WARNINGS`),
|
|
10
|
-
|
|
11
|
-
values do not show, like a zoned timestamp's zone (`dialects.py`),
|
|
12
|
-
comparison of composites whose elements may be NULL
|
|
9
|
+
enforce, and, about the SQL itself (`SQL_WARNINGS`), a CHECK constraint
|
|
10
|
+
that states no Enumerated Domain, a comparison that depends on something the
|
|
11
|
+
values do not show, like a zoned timestamp's zone (`dialects.py`), a
|
|
12
|
+
comparison of composites whose elements may be NULL, and a proved Property
|
|
13
|
+
that holds only because a column it names is always NULL.
|
|
13
14
|
Warnings never make a Report fail.
|
|
14
15
|
"""
|
|
15
16
|
|
|
16
17
|
from __future__ import annotations
|
|
17
18
|
|
|
19
|
+
from collections.abc import Iterable
|
|
18
20
|
from dataclasses import dataclass
|
|
19
21
|
|
|
20
22
|
from sqlassert.provenance import Origin
|
|
21
23
|
|
|
24
|
+
def quoted(name: str) -> str:
|
|
25
|
+
"""A column name, or a term naming one, as messages write it: 'job'."""
|
|
26
|
+
return f"'{name}'"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def quoted_all(names: Iterable[str]) -> str:
|
|
30
|
+
return ", ".join(quoted(name) for name in names)
|
|
31
|
+
|
|
32
|
+
|
|
22
33
|
CATALOG_METADATA_UNAVAILABLE = "catalog-metadata-unavailable"
|
|
34
|
+
ALWAYS_NULL_COLUMN = "always-null-column"
|
|
23
35
|
AMBIGUOUS_COLUMN = "ambiguous-column"
|
|
24
|
-
AMBIGUOUS_OPERATOR = "ambiguous-operator"
|
|
25
36
|
CARDINALITY_ON_FILTERING_JOIN = "cardinality-on-filtering-join"
|
|
26
37
|
CATALOG_RELATION_NOT_FOUND = "catalog-relation-not-found"
|
|
27
38
|
COMPOSITE_COMPARISON = "composite-comparison"
|
|
28
39
|
CONSTRAINT_WITHOUT_TABLE = "constraint-without-table"
|
|
29
40
|
DUPLICATE_DECLARATION = "duplicate-declaration"
|
|
41
|
+
IGNORED_CHECK_CONSTRAINT = "ignored-check-constraint"
|
|
30
42
|
INCOMPLETE_CATALOG_METADATA = "incomplete-catalog-metadata"
|
|
31
43
|
INVALID_FOREIGN_KEY_CONSTRAINT = "invalid-foreign-key-constraint"
|
|
32
44
|
MULTIPLE_ROOT_SELECTS = "multiple-root-selects"
|
|
@@ -40,6 +52,7 @@ UNKNOWN_ASSERTED_COLUMN = "unknown-asserted-column"
|
|
|
40
52
|
UNRESOLVED_ASSERTED_COLUMN = "unresolved-asserted-column"
|
|
41
53
|
UNKNOWN_REFERENCED_COLUMN = "unknown-referenced-column"
|
|
42
54
|
UNRECOGNIZED_MARKER = "unrecognized-marker"
|
|
55
|
+
UNSUPPORTED_CONSTRUCT = "unsupported-construct"
|
|
43
56
|
UNSUPPORTED_CREATE_STATEMENT = "unsupported-create-statement"
|
|
44
57
|
UNSUPPORTED_NATURAL_JOIN = "unsupported-natural-join"
|
|
45
58
|
UNSUPPORTED_STATEMENT = "unsupported-statement"
|
|
@@ -54,4 +67,4 @@ class Diagnostic:
|
|
|
54
67
|
|
|
55
68
|
|
|
56
69
|
# Warnings about the SQL itself, which no connection answers: `analyze_database` keeps them.
|
|
57
|
-
SQL_WARNINGS = frozenset({
|
|
70
|
+
SQL_WARNINGS = frozenset({ALWAYS_NULL_COLUMN, COMPOSITE_COMPARISON, IGNORED_CHECK_CONSTRAINT, ZONED_TIMESTAMP_CAST})
|
sqlassert/dialects.py
CHANGED
|
@@ -2,16 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
One `DialectSemantics` per dialect name (SQLGlot's), read by `ir/convert.py`
|
|
4
4
|
while it lowers SQL: which Builtins raise an error rather than return NULL,
|
|
5
|
-
which text compares by identity, what
|
|
6
|
-
which constraints the database enforces. A dialect not listed gets
|
|
5
|
+
which text compares by identity, what `||`, `concat()`, `greatest()` and
|
|
6
|
+
subscripts do with NULL, and which constraints the database enforces. A dialect not listed gets
|
|
7
7
|
`DialectSemantics()`, whose arithmetic, collation and `||` are the cautious
|
|
8
8
|
choice; only its keys are taken as enforced, as before dialects were listed.
|
|
9
9
|
|
|
10
|
-
Every flag is a claim
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
arithmetic raises or returns NULL depending on ANSI mode, so it may return
|
|
14
|
-
NULL. `docs/dialects.md` argues each entry and says how soundness is judged
|
|
10
|
+
Every flag is a claim about the dialect's latest release under its default
|
|
11
|
+
settings, strict modes on (ADR 0006): MySQL's `||` is OR, since the default
|
|
12
|
+
`sql_mode` has no PIPES_AS_CONCAT; Spark is modelled with ANSI mode on. `docs/dialects.md` argues each entry and says how soundness is judged
|
|
15
13
|
without DuckDB; `docs/dialect-provenance.json` records, per fact, the engine
|
|
16
14
|
versions it was certified on or the vendor doc it rests on
|
|
17
15
|
(`scripts/certify_dialects.py`).
|
|
@@ -19,7 +17,7 @@ versions it was certified on or the vendor doc it rests on
|
|
|
19
17
|
|
|
20
18
|
from __future__ import annotations
|
|
21
19
|
|
|
22
|
-
from dataclasses import dataclass
|
|
20
|
+
from dataclasses import dataclass, replace
|
|
23
21
|
from typing import Literal
|
|
24
22
|
|
|
25
23
|
# How a dialect treats a declared key (PRIMARY KEY, UNIQUE) or foreign key:
|
|
@@ -27,15 +25,19 @@ from typing import Literal
|
|
|
27
25
|
type KeyTrust = Literal["enforced", "rely", "unenforced"]
|
|
28
26
|
|
|
29
27
|
# What `a || b` is: concatenation whose NULL operand makes it NULL ("strict"),
|
|
30
|
-
# concatenation that may skip a NULL operand ("lenient", Postgres arrays)
|
|
31
|
-
#
|
|
32
|
-
|
|
33
|
-
type PipesMeaning = Literal["strict", "lenient", "ambiguous"] | None
|
|
28
|
+
# or concatenation that may skip a NULL operand ("lenient", Postgres arrays);
|
|
29
|
+
# None when it is not modelled (MySQL, where it is OR).
|
|
30
|
+
type PipesMeaning = Literal["strict", "lenient"] | None
|
|
34
31
|
|
|
35
32
|
# What `concat(a, ...)` does with NULL: makes the result NULL ("strict"), or
|
|
36
33
|
# skips it, so the result is never NULL ("skips-null"); None when not modelled.
|
|
37
34
|
type ConcatMeaning = Literal["strict", "skips-null"] | None
|
|
38
35
|
|
|
36
|
+
# What `greatest(a, ...)` and `least(a, ...)` do with NULL: make the result
|
|
37
|
+
# NULL ("strict"), or skip it, so the result is NULL only when every argument
|
|
38
|
+
# is ("skips-null"); None when not modelled.
|
|
39
|
+
type GreatestMeaning = Literal["strict", "skips-null"] | None
|
|
40
|
+
|
|
39
41
|
|
|
40
42
|
@dataclass(frozen=True)
|
|
41
43
|
class DialectSemantics:
|
|
@@ -44,13 +46,17 @@ class DialectSemantics:
|
|
|
44
46
|
checked_arithmetic: bool = False
|
|
45
47
|
# `/`, integer division and `%` by zero raise an error rather than return NULL.
|
|
46
48
|
checked_division: bool = False
|
|
49
|
+
# `sum` and `avg` of non-null values are never NULL: an overflow raises
|
|
50
|
+
# (or widens the type) rather than returning NULL, and NaN or infinity is
|
|
51
|
+
# a value, not NULL (SQLite turns NaN into NULL).
|
|
52
|
+
checked_sum: bool = False
|
|
47
53
|
# An implicit cast that fails raises an error, so a comparison, LIKE,
|
|
48
54
|
# BETWEEN, NOT or bitwise operator of non-null operands is never NULL.
|
|
49
55
|
casts_raise: bool = True
|
|
50
|
-
# VARCHAR and TEXT
|
|
51
|
-
#
|
|
52
|
-
# `default_collation`) is out of scope
|
|
53
|
-
#
|
|
56
|
+
# VARCHAR and TEXT compare by identity under the engine's shipped default
|
|
57
|
+
# collation. A setting that changes that default (DuckDB's
|
|
58
|
+
# `default_collation`) is out of scope, and a COLLATE is unsupported: it
|
|
59
|
+
# is opaque, and a column declared with one is untyped (docs/dialects.md).
|
|
54
60
|
text_is_binary: bool = False
|
|
55
61
|
# A DECIMAL declared without a scale keeps each value's own scale, so
|
|
56
62
|
# equal values (1.0, 1.00) may differ: neither identity nor exact.
|
|
@@ -65,8 +71,14 @@ class DialectSemantics:
|
|
|
65
71
|
# What `concat_ws(sep, a, ...)` does with a NULL value (a NULL separator
|
|
66
72
|
# makes it NULL either way); None where it does not exist or is not modelled.
|
|
67
73
|
concat_ws: ConcatMeaning = None
|
|
74
|
+
greatest: GreatestMeaning = None
|
|
75
|
+
# `xs[i]` (an element of a list, array, map or struct) is NULL when `xs` is.
|
|
76
|
+
subscript_strict: bool = False
|
|
68
77
|
unique_keys: KeyTrust = "enforced"
|
|
69
78
|
foreign_keys: KeyTrust = "enforced"
|
|
79
|
+
# CHECK constraints. Where the dialect has none (Snowflake, BigQuery,
|
|
80
|
+
# Redshift, Trino), one in the SQL describes a table another engine holds.
|
|
81
|
+
check_constraints: KeyTrust = "enforced"
|
|
70
82
|
# A PRIMARY KEY column is NOT NULL.
|
|
71
83
|
primary_key_not_null: bool = True
|
|
72
84
|
# A column-level `REFERENCES` is enforced (MySQL before 9.0 parses and ignores it).
|
|
@@ -90,38 +102,53 @@ class DialectSemantics:
|
|
|
90
102
|
return "rely" in (self.unique_keys, self.foreign_keys)
|
|
91
103
|
|
|
92
104
|
|
|
105
|
+
# Spark 4 and Databricks under ANSI mode, their default (ADR 0006): overflow
|
|
106
|
+
# and a bad CAST raise. Apache Spark's docs say `div` by zero is NULL and do
|
|
107
|
+
# not say a failed implicit cast in a comparison raises; Databricks's say
|
|
108
|
+
# both raise (docs/dialect-provenance.json).
|
|
93
109
|
_SPARK = DialectSemantics(
|
|
94
|
-
|
|
95
|
-
# raise or return NULL; it is on by default only in recent versions.
|
|
110
|
+
checked_arithmetic=True,
|
|
96
111
|
casts_raise=False,
|
|
97
112
|
zoned_timestamp_is_instant=True,
|
|
98
113
|
pipes="strict",
|
|
99
114
|
concat="strict",
|
|
100
115
|
concat_ws="skips-null",
|
|
116
|
+
# Certified on Spark 4.3, not Databricks (`databricks` below drops them).
|
|
117
|
+
checked_sum=True,
|
|
118
|
+
greatest="skips-null",
|
|
119
|
+
subscript_strict=True,
|
|
101
120
|
unique_keys="rely",
|
|
102
121
|
foreign_keys="rely",
|
|
122
|
+
# Delta tables check them, other tables cannot declare them.
|
|
123
|
+
check_constraints="unenforced",
|
|
103
124
|
set_operations_all=True,
|
|
104
125
|
)
|
|
105
126
|
|
|
106
127
|
_SEMANTICS: dict[str, DialectSemantics] = {
|
|
107
128
|
"duckdb": DialectSemantics(
|
|
108
129
|
checked_arithmetic=True,
|
|
130
|
+
checked_sum=True,
|
|
109
131
|
text_is_binary=True,
|
|
110
132
|
zoned_timestamp_is_instant=True,
|
|
111
133
|
pipes="strict",
|
|
112
134
|
concat="skips-null",
|
|
113
135
|
concat_ws="skips-null",
|
|
136
|
+
greatest="skips-null",
|
|
137
|
+
subscript_strict=True,
|
|
114
138
|
set_operations_all=True,
|
|
115
139
|
),
|
|
116
140
|
"postgres": DialectSemantics(
|
|
117
141
|
checked_arithmetic=True,
|
|
118
142
|
checked_division=True,
|
|
143
|
+
checked_sum=True,
|
|
119
144
|
text_is_binary=True,
|
|
120
145
|
unscaled_decimal=True,
|
|
121
146
|
zoned_timestamp_is_instant=True,
|
|
122
147
|
pipes="lenient", # `ARRAY[1] || NULL` is `{1}`.
|
|
123
148
|
concat="skips-null",
|
|
124
149
|
concat_ws="skips-null",
|
|
150
|
+
greatest="skips-null",
|
|
151
|
+
subscript_strict=True,
|
|
125
152
|
set_operations_all=True,
|
|
126
153
|
),
|
|
127
154
|
"mysql": DialectSemantics(
|
|
@@ -129,12 +156,16 @@ _SEMANTICS: dict[str, DialectSemantics] = {
|
|
|
129
156
|
# a comparison of non-null operands is non-null. Not `checked_arithmetic`:
|
|
130
157
|
# `-x` of the least BIGINT is an exact DECIMAL rather than an error, and
|
|
131
158
|
# division by zero is NULL in any mode.
|
|
159
|
+
# `sum` of integers is an exact DECIMAL, and a DOUBLE holds no
|
|
160
|
+
# infinity or NaN (a DOUBLE sum that overflows is 0).
|
|
161
|
+
checked_sum=True,
|
|
132
162
|
# Not `text_is_binary`: the default collations ignore case (and
|
|
133
163
|
# accents, and some trailing spaces).
|
|
134
164
|
zoned_timestamp_is_instant=True, # TIMESTAMP is converted to UTC.
|
|
135
|
-
pipes="ambiguous",
|
|
136
165
|
concat="strict",
|
|
137
166
|
concat_ws="skips-null",
|
|
167
|
+
greatest="strict",
|
|
168
|
+
# Not `subscript_strict`: MySQL has no `xs[i]`.
|
|
138
169
|
inline_references=False,
|
|
139
170
|
foreign_key_engines=frozenset({"innodb", "ndb", "ndbcluster"}),
|
|
140
171
|
enum_strips_trailing_spaces=True,
|
|
@@ -148,28 +179,39 @@ _SEMANTICS: dict[str, DialectSemantics] = {
|
|
|
148
179
|
concat_ws="strict", # `concat_ws(',', 'a', NULL)` is NULL.
|
|
149
180
|
unique_keys="rely",
|
|
150
181
|
foreign_keys="rely",
|
|
182
|
+
check_constraints="unenforced",
|
|
151
183
|
),
|
|
152
184
|
"bigquery": DialectSemantics(
|
|
153
185
|
checked_arithmetic=True,
|
|
154
186
|
checked_division=True,
|
|
187
|
+
# Its docs: overflow raises, and NaN or an infinity makes NaN or an infinity.
|
|
188
|
+
checked_sum=True,
|
|
155
189
|
zoned_timestamp_is_instant=True,
|
|
156
190
|
pipes="strict",
|
|
157
191
|
concat="strict",
|
|
158
192
|
unique_keys="unenforced",
|
|
159
193
|
foreign_keys="unenforced",
|
|
194
|
+
check_constraints="unenforced",
|
|
160
195
|
),
|
|
161
196
|
"redshift": DialectSemantics(
|
|
162
197
|
checked_arithmetic=True,
|
|
163
198
|
checked_division=True,
|
|
199
|
+
# Not `checked_sum`: its docs say nothing of a sum that overflows or meets NaN.
|
|
164
200
|
zoned_timestamp_is_instant=True,
|
|
165
201
|
pipes="strict",
|
|
166
202
|
unique_keys="unenforced",
|
|
167
203
|
foreign_keys="unenforced",
|
|
204
|
+
check_constraints="unenforced",
|
|
205
|
+
),
|
|
206
|
+
"databricks": replace(
|
|
207
|
+
_SPARK, checked_division=True, casts_raise=True,
|
|
208
|
+
# Certified on Apache Spark only; Databricks's docs do not say a sum meets NaN as a value.
|
|
209
|
+
checked_sum=False, greatest=None, subscript_strict=False,
|
|
168
210
|
),
|
|
169
|
-
"databricks": _SPARK,
|
|
170
211
|
"spark": _SPARK,
|
|
171
|
-
"
|
|
172
|
-
|
|
212
|
+
"hive": DialectSemantics(casts_raise=False, pipes="strict", concat="strict", unique_keys="unenforced", foreign_keys="unenforced",
|
|
213
|
+
check_constraints="unenforced",
|
|
214
|
+
),
|
|
173
215
|
"sqlite": DialectSemantics(
|
|
174
216
|
pipes="strict",
|
|
175
217
|
concat_ws="skips-null",
|
|
@@ -186,6 +228,7 @@ _SEMANTICS: dict[str, DialectSemantics] = {
|
|
|
186
228
|
"trino": DialectSemantics(
|
|
187
229
|
checked_arithmetic=True,
|
|
188
230
|
checked_division=True,
|
|
231
|
+
checked_sum=True,
|
|
189
232
|
# VARCHAR compares by code point and Trino has no collations.
|
|
190
233
|
text_is_binary=True,
|
|
191
234
|
# Not `zoned_timestamp_is_instant`: a TIMESTAMP WITH TIME ZONE keeps
|
|
@@ -193,10 +236,14 @@ _SEMANTICS: dict[str, DialectSemantics] = {
|
|
|
193
236
|
# Unlike Postgres, a NULL array or element operand makes `||` NULL too.
|
|
194
237
|
pipes="strict",
|
|
195
238
|
concat="strict",
|
|
239
|
+
greatest="strict",
|
|
240
|
+
# NULL for a NULL array or map; an index out of range raises.
|
|
241
|
+
subscript_strict=True,
|
|
196
242
|
# Not modelled: it skips a NULL VARCHAR, but its ARRAY(VARCHAR)
|
|
197
243
|
# overload is NULL for a NULL array, and SQLGlot parses both alike.
|
|
198
244
|
unique_keys="unenforced",
|
|
199
245
|
foreign_keys="unenforced",
|
|
246
|
+
check_constraints="unenforced",
|
|
200
247
|
set_operations_all=True,
|
|
201
248
|
),
|
|
202
249
|
}
|
sqlassert/discovery/duckdb.py
CHANGED
|
@@ -46,7 +46,7 @@ WHERE {_TABLES}
|
|
|
46
46
|
ORDER BY table_name, column_index
|
|
47
47
|
"""
|
|
48
48
|
|
|
49
|
-
# duckdb_columns() drops
|
|
49
|
+
# duckdb_columns() drops a column's COLLATE; the stored CREATE TABLE keeps it.
|
|
50
50
|
_TABLE_SQL = f"SELECT table_name, sql FROM duckdb_tables() WHERE {_TABLES}"
|
|
51
51
|
|
|
52
52
|
# A foreign key's referenced table is in the referencing table's own catalog
|
|
@@ -110,9 +110,9 @@ class DuckDBKnowledgeFetcher(InformationSchemaKnowledgeFetcher):
|
|
|
110
110
|
|
|
111
111
|
def columns(self, catalog: str, schema: str, tables: Sequence[str]) -> list[tuple[str, DatabaseColumn]]:
|
|
112
112
|
lookup = (catalog, schema, list(tables))
|
|
113
|
-
|
|
113
|
+
collated = self._collated(catalog, schema, lookup)
|
|
114
114
|
return [
|
|
115
|
-
(table, DatabaseColumn(column, nullable,
|
|
115
|
+
(table, DatabaseColumn(column, nullable, None if (table, column.lower()) in collated else data_type))
|
|
116
116
|
for table, column, nullable, data_type in self._rows(_COLUMNS, lookup)
|
|
117
117
|
]
|
|
118
118
|
|
|
@@ -133,26 +133,22 @@ class DuckDBKnowledgeFetcher(InformationSchemaKnowledgeFetcher):
|
|
|
133
133
|
rows = self._rows(_VIEW, (relation.catalog, relation.schema, relation.name))
|
|
134
134
|
return rows[0][0] if rows else None
|
|
135
135
|
|
|
136
|
-
def
|
|
137
|
-
"""Each table
|
|
136
|
+
def _collated(self, catalog: str, schema: str, lookup: tuple[Any, ...]) -> set[tuple[str, str]]:
|
|
137
|
+
"""Each (table, lowercase column) declared with a COLLATE: sqlassert
|
|
138
|
+
supports the default collation only, so such a column is untyped. The
|
|
138
139
|
session's `default_collation` is not read: text without a COLLATE has
|
|
139
140
|
the engine's shipped (binary) default (docs/dialects.md)."""
|
|
140
|
-
|
|
141
|
+
collated: set[tuple[str, str]] = set()
|
|
141
142
|
for table, sql in self._rows(_TABLE_SQL, lookup):
|
|
142
143
|
try:
|
|
143
144
|
create = sqlglot.parse_one(sql, read="duckdb")
|
|
144
145
|
except SqlglotError as error:
|
|
145
146
|
raise DatabaseMetadataError(f"definition of table {catalog}.{schema}.{table} could not be parsed: {error}") from error
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
), None)
|
|
152
|
-
if collate is not None:
|
|
153
|
-
own[definition.name.lower()] = collate.this.name
|
|
154
|
-
collations[table] = own
|
|
155
|
-
return collations
|
|
147
|
+
collated.update(
|
|
148
|
+
(table, definition.name.lower()) for definition in create.find_all(exp.ColumnDef)
|
|
149
|
+
if any(isinstance(constraint.args.get("kind"), exp.CollateColumnConstraint) for constraint in definition.constraints)
|
|
150
|
+
)
|
|
151
|
+
return collated
|
|
156
152
|
|
|
157
153
|
def _rows(self, sql: str, parameters: tuple[Any, ...] = ()) -> list[tuple[Any, ...]]:
|
|
158
154
|
"""The rows of one catalog query, run on the connection (see the module
|