sqlassert 0.3.1__py3-none-any.whl → 0.4.1__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/__init__.py +1 -2
- sqlassert/__main__.py +2 -131
- sqlassert/check.py +98 -16
- sqlassert/diagnostics.py +31 -7
- sqlassert/dialects.py +504 -27
- sqlassert/discovery/bigquery.py +3 -1
- sqlassert/discovery/databricks.py +25 -2
- sqlassert/discovery/duckdb.py +61 -23
- sqlassert/discovery/fetcher.py +170 -45
- sqlassert/discovery/information_schema.py +34 -5
- sqlassert/discovery/mysql.py +22 -1
- sqlassert/discovery/postgres.py +28 -12
- sqlassert/discovery/redshift.py +3 -2
- sqlassert/discovery/snowflake.py +3 -0
- sqlassert/discovery/trino.py +2 -2
- sqlassert/edits.py +240 -0
- sqlassert/hazards.py +735 -0
- sqlassert/ir/__init__.py +6 -1
- sqlassert/ir/convert/__init__.py +13 -0
- sqlassert/ir/convert/aggregation.py +439 -0
- sqlassert/ir/convert/builtins.py +140 -0
- sqlassert/ir/convert/expressions.py +572 -0
- sqlassert/ir/convert/joins.py +264 -0
- sqlassert/ir/convert/markers.py +249 -0
- sqlassert/ir/convert/parser.py +253 -0
- sqlassert/ir/convert/queries.py +259 -0
- sqlassert/ir/convert/schema.py +606 -0
- sqlassert/ir/convert/scopes.py +205 -0
- sqlassert/ir/convert/selects.py +337 -0
- sqlassert/ir/convert/shared.py +429 -0
- sqlassert/ir/convert/sources.py +432 -0
- sqlassert/ir/convert/subqueries.py +364 -0
- sqlassert/ir/convert/value_types.py +223 -0
- sqlassert/ir/convert/windows.py +275 -0
- sqlassert/ir/model.py +247 -66
- sqlassert/ir/names.py +63 -0
- sqlassert/main.py +3 -9
- sqlassert/properties.py +12 -1
- sqlassert/provenance.py +5 -1
- sqlassert/python_engine.py +167 -50
- sqlassert/reporting.py +36 -32
- sqlassert/rewrites.py +1591 -0
- sqlassert/rules/STYLEGUIDE.md +3 -2
- sqlassert/rules/causes/__init__.py +41 -0
- sqlassert/rules/causes/coverage.py +113 -0
- sqlassert/rules/causes/domain.py +123 -0
- sqlassert/rules/causes/joins.py +73 -0
- sqlassert/rules/causes/nulls.py +154 -0
- sqlassert/rules/causes/unique.py +523 -0
- sqlassert/rules/domain.py +123 -26
- sqlassert/rules/equality.py +153 -85
- sqlassert/rules/exactly_one.py +42 -2
- sqlassert/rules/foreign_key.py +15 -13
- sqlassert/rules/join_cardinality.py +302 -39
- sqlassert/rules/nullability.py +244 -35
- sqlassert/rules/uniqueness.py +513 -86
- sqlassert/rules/value_typing.py +337 -0
- sqlassert/sql_parse.py +224 -90
- sqlassert/suggest.py +132 -57
- sqlassert-0.4.1.dist-info/METADATA +235 -0
- sqlassert-0.4.1.dist-info/RECORD +69 -0
- sqlassert-0.4.1.dist-info/entry_points.txt +2 -0
- sqlassert-0.4.1.dist-info/top_level.txt +2 -0
- sqlassert_cli.py +130 -0
- sqlassert/improvements.py +0 -528
- sqlassert/ir/convert.py +0 -2377
- sqlassert/smells.py +0 -306
- sqlassert-0.3.1.dist-info/METADATA +0 -725
- 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.4.1.dist-info}/WHEEL +0 -0
- {sqlassert-0.3.1.dist-info → sqlassert-0.4.1.dist-info}/licenses/LICENSE +0 -0
sqlassert/__init__.py
CHANGED
|
@@ -5,7 +5,7 @@ from sqlassert.properties import (
|
|
|
5
5
|
OneToOneJoin, Property, UniqueJoin, UniqueSet,
|
|
6
6
|
)
|
|
7
7
|
from sqlassert.provenance import AttachmentSite, Origin
|
|
8
|
-
from sqlassert.reporting import AssertionReport, Outcome,
|
|
8
|
+
from sqlassert.reporting import AssertionReport, Outcome, Report
|
|
9
9
|
from sqlassert.suggest import Suggestion, SuggestionReport, suggest
|
|
10
10
|
|
|
11
11
|
__all__ = [
|
|
@@ -26,7 +26,6 @@ __all__ = [
|
|
|
26
26
|
"Origin",
|
|
27
27
|
"Outcome",
|
|
28
28
|
"Property",
|
|
29
|
-
"RelationFacts",
|
|
30
29
|
"Report",
|
|
31
30
|
"Suggestion",
|
|
32
31
|
"SuggestionReport",
|
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,10 +29,10 @@ 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
|
-
from sqlassert.reporting import ASSERTED_KINDS, Outcome, Report
|
|
35
|
+
from sqlassert.reporting import ASSERTED_KINDS, AssertionReport, Outcome, Report, Step
|
|
36
36
|
|
|
37
37
|
# Exit codes, shared by every command that checks SQL.
|
|
38
38
|
EXIT_OK = 0 # every assertion PROVED and no Diagnostic (warnings allowed)
|
|
@@ -66,8 +66,10 @@ class Severity(Enum):
|
|
|
66
66
|
class Finding:
|
|
67
67
|
"""One thing a check reports: an `UNKNOWN` assertion or a Diagnostic.
|
|
68
68
|
|
|
69
|
-
`path` is the file as shown to the user. `
|
|
70
|
-
assertion
|
|
69
|
+
`path` is the file as shown to the user. `causes` are where an `UNKNOWN`
|
|
70
|
+
Unique Set assertion is lost (`Step.causes`), always shown. `evidence` is
|
|
71
|
+
an `UNKNOWN` assertion's explanation: the relations it passes through
|
|
72
|
+
when it has Causes, else its explained Evidence; printed only when asked for.
|
|
71
73
|
"""
|
|
72
74
|
|
|
73
75
|
path: str
|
|
@@ -76,6 +78,7 @@ class Finding:
|
|
|
76
78
|
message: str
|
|
77
79
|
origin: Origin | None = None
|
|
78
80
|
evidence: str | None = None
|
|
81
|
+
causes: tuple[Step, ...] = ()
|
|
79
82
|
|
|
80
83
|
|
|
81
84
|
@dataclass(frozen=True)
|
|
@@ -99,20 +102,75 @@ def findings(path: str, sql: str, report: Report, *, ignore: Iterable[str] = ())
|
|
|
99
102
|
ignored = frozenset(ignore)
|
|
100
103
|
unknown = [
|
|
101
104
|
Finding(
|
|
102
|
-
path, Severity.ERROR, unproved(assertion.kind),
|
|
103
|
-
|
|
105
|
+
path, Severity.ERROR, unproved(assertion.kind),
|
|
106
|
+
f"{_written(sql, assertion.origin)} is not proved (UNKNOWN)"
|
|
107
|
+
+ (f": {assertion.unsupported} is not supported by sqlassert yet, which may be why" if assertion.unsupported else ""),
|
|
108
|
+
assertion.origin, _evidence(path, assertion),
|
|
109
|
+
assertion.explanation.causes() if assertion.explanation is not None else (),
|
|
104
110
|
)
|
|
105
111
|
for assertion in report.assertions
|
|
106
112
|
if assertion.outcome is Outcome.UNKNOWN
|
|
107
113
|
]
|
|
108
114
|
reported = [_diagnostic(path, diagnostic, Severity.ERROR) for diagnostic in report.diagnostics]
|
|
109
|
-
|
|
115
|
+
# An unsupported construct an UNKNOWN assertion reached is already named on it.
|
|
116
|
+
named = {assertion.origin for assertion in report.assertions if assertion.unsupported is not None}
|
|
117
|
+
warned = [
|
|
118
|
+
_diagnostic(path, warning, Severity.WARNING) for warning in report.warnings
|
|
119
|
+
if not (warning.code == UNSUPPORTED_CONSTRUCT and warning.origin in named)
|
|
120
|
+
]
|
|
110
121
|
return tuple(
|
|
111
122
|
finding for finding in sorted((*unknown, *reported, *warned), key=_source_order)
|
|
112
123
|
if finding.code not in ignored
|
|
113
124
|
)
|
|
114
125
|
|
|
115
126
|
|
|
127
|
+
def _evidence(path: str, assertion: AssertionReport) -> str | None:
|
|
128
|
+
"""The explanation of an UNKNOWN assertion: the walk to its Causes when
|
|
129
|
+
there is one, else its Evidence."""
|
|
130
|
+
if assertion.explanation is not None:
|
|
131
|
+
return "\n".join(step_lines(assertion.explanation, _in_file(path)))
|
|
132
|
+
return assertion.evidence.explain() if assertion.evidence is not None else None
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
# Where an Origin is written, as a reader finds it (`path:line:column`), or None.
|
|
136
|
+
type Placing = Callable[[Origin], str | None]
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _in_file(path: str) -> Placing:
|
|
140
|
+
return lambda origin: f"{path}:{origin.span.line}:{origin.span.column}" if origin.span is not None else None
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def step_lines(step: Step, place: Placing, depth: int = 0) -> list[str]:
|
|
144
|
+
"""A Step and the Steps under it, one per line, details indented below each."""
|
|
145
|
+
indent = " " * depth
|
|
146
|
+
lines = [indent + _step_line(step, place)]
|
|
147
|
+
lines.extend(f"{indent} {detail}" for detail in step.details)
|
|
148
|
+
for inner in step.steps:
|
|
149
|
+
lines.extend(step_lines(inner, place, depth + 1))
|
|
150
|
+
return lines
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def causes_lines(causes: Iterable[Step], place: Placing) -> list[str]:
|
|
154
|
+
"""Each Cause and its details, one per line."""
|
|
155
|
+
lines = []
|
|
156
|
+
for cause in causes:
|
|
157
|
+
lines.append(_step_line(cause, place))
|
|
158
|
+
lines.extend(f" {detail}" for detail in cause.details)
|
|
159
|
+
return lines
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _step_line(step: Step, place: Placing) -> str:
|
|
163
|
+
"""`where: text`, and `[tag] code` for a Cause."""
|
|
164
|
+
where = place(step.origin) if step.origin is not None else None
|
|
165
|
+
tagged = f" [{step.tag}] {step.code}" if step.tag is not None else ""
|
|
166
|
+
return f"{where}: {step.text}{tagged}" if where else f"{step.text}{tagged}"
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def cause_lines(finding: Finding) -> list[str]:
|
|
170
|
+
"""Each Cause of a Finding and its details, one per line."""
|
|
171
|
+
return causes_lines(finding.causes, _in_file(finding.path))
|
|
172
|
+
|
|
173
|
+
|
|
116
174
|
def check(path: str, sql: str, *, dialect: str = DEFAULT_DIALECT, ignore: Iterable[str] = ()) -> Checked:
|
|
117
175
|
"""Analyze one SQL Program from its SQL alone."""
|
|
118
176
|
report = analyze(sql, dialect=dialect)
|
|
@@ -280,6 +338,7 @@ def render_text(checked: Sequence[Checked], *, explain: bool = False) -> str:
|
|
|
280
338
|
for result in checked:
|
|
281
339
|
for finding in result.findings:
|
|
282
340
|
lines.append(f"{_place(finding)}: {finding.severity.value} {finding.code}: {finding.message}")
|
|
341
|
+
lines.extend(indented(line) for line in cause_lines(finding))
|
|
283
342
|
if explain and finding.evidence is not None:
|
|
284
343
|
lines.append(indented(finding.evidence))
|
|
285
344
|
lines.append(_summary_line(checked))
|
|
@@ -293,6 +352,11 @@ def render_json(checked: Sequence[Checked], *, explain: bool = False) -> str:
|
|
|
293
352
|
"path": item.path, "severity": item.severity.value, "code": item.code, "message": item.message,
|
|
294
353
|
"location": _location(item.origin),
|
|
295
354
|
}
|
|
355
|
+
if item.causes:
|
|
356
|
+
shown["causes"] = [
|
|
357
|
+
{"tag": cause.tag, "code": cause.code, "message": cause.text, "details": list(cause.details), "location": _location(cause.origin)}
|
|
358
|
+
for cause in item.causes
|
|
359
|
+
]
|
|
296
360
|
if explain and item.evidence is not None:
|
|
297
361
|
shown["evidence"] = item.evidence
|
|
298
362
|
return shown
|
|
@@ -321,12 +385,8 @@ def render_sarif(checked: Sequence[Checked], *, explain: bool = False) -> str:
|
|
|
321
385
|
except PackageNotFoundError:
|
|
322
386
|
pass
|
|
323
387
|
|
|
324
|
-
def
|
|
325
|
-
|
|
326
|
-
if explain and finding.evidence is not None:
|
|
327
|
-
message += "\n\n" + finding.evidence
|
|
328
|
-
location: dict = {"artifactLocation": {"uri": _uri(finding.path)}}
|
|
329
|
-
origin = finding.origin
|
|
388
|
+
def physical(path: str, origin: Origin | None) -> dict:
|
|
389
|
+
location: dict = {"artifactLocation": {"uri": _uri(path)}}
|
|
330
390
|
if origin is not None and origin.line is not None:
|
|
331
391
|
region: dict = {"startLine": origin.line}
|
|
332
392
|
if origin.span is not None:
|
|
@@ -334,13 +394,27 @@ def render_sarif(checked: Sequence[Checked], *, explain: bool = False) -> str:
|
|
|
334
394
|
startColumn=origin.span.column, endLine=origin.span.end_line, endColumn=origin.span.end_column
|
|
335
395
|
)
|
|
336
396
|
location["region"] = region
|
|
337
|
-
return
|
|
397
|
+
return location
|
|
398
|
+
|
|
399
|
+
def result(finding: Finding) -> dict:
|
|
400
|
+
message = "\n".join([finding.message, *cause_lines(finding)])
|
|
401
|
+
if explain and finding.evidence is not None:
|
|
402
|
+
message += "\n\n" + finding.evidence
|
|
403
|
+
shown: dict = {
|
|
338
404
|
"ruleId": finding.code,
|
|
339
405
|
"ruleIndex": codes.index(finding.code),
|
|
340
406
|
"level": finding.severity.value,
|
|
341
407
|
"message": {"text": message},
|
|
342
|
-
"locations": [{"physicalLocation":
|
|
408
|
+
"locations": [{"physicalLocation": physical(finding.path, finding.origin)}],
|
|
343
409
|
}
|
|
410
|
+
# Where each Cause is written, so a review sees it there too.
|
|
411
|
+
related = [
|
|
412
|
+
{"id": index, "physicalLocation": physical(finding.path, cause.origin), "message": {"text": cause.text}}
|
|
413
|
+
for index, cause in enumerate(finding.causes, 1) if cause.origin is not None and cause.origin.line is not None
|
|
414
|
+
]
|
|
415
|
+
if related:
|
|
416
|
+
shown["relatedLocations"] = related
|
|
417
|
+
return shown
|
|
344
418
|
|
|
345
419
|
log = {
|
|
346
420
|
"$schema": "https://json.schemastore.org/sarif-2.1.0.json",
|
|
@@ -366,11 +440,19 @@ def render_github(checked: Sequence[Checked], *, explain: bool = False) -> str:
|
|
|
366
440
|
if span.end_line == span.line:
|
|
367
441
|
properties.update(col=str(span.column), endColumn=str(span.end_column))
|
|
368
442
|
properties["title"] = f"sqlassert {finding.code}"
|
|
369
|
-
message = finding.message
|
|
443
|
+
message = "\n".join([finding.message, *cause_lines(finding)])
|
|
370
444
|
if explain and finding.evidence is not None:
|
|
371
445
|
message += "\n" + finding.evidence
|
|
372
446
|
shown = ",".join(f"{key}={_escape_property(value)}" for key, value in properties.items())
|
|
373
447
|
lines.append(f"::{finding.severity.value} {shown}::{_escape_data(message)}")
|
|
448
|
+
# A notice where each Cause is written, so the fix is annotated where it is made.
|
|
449
|
+
for cause in finding.causes:
|
|
450
|
+
if cause.origin is None or cause.origin.span is None:
|
|
451
|
+
continue
|
|
452
|
+
span = cause.origin.span
|
|
453
|
+
noticed = {"file": finding.path, "line": str(span.line), "col": str(span.column), "title": f"sqlassert cause of {finding.code}"}
|
|
454
|
+
text = "\n".join([cause.text, *cause.details])
|
|
455
|
+
lines.append(f"::notice {','.join(f'{key}={_escape_property(value)}' for key, value in noticed.items())}::{_escape_data(text)}")
|
|
374
456
|
return "".join(line + "\n" for line in lines)
|
|
375
457
|
|
|
376
458
|
|
sqlassert/diagnostics.py
CHANGED
|
@@ -5,28 +5,44 @@ Disproof and never an inference: it says that analysis stopped short, and why.
|
|
|
5
5
|
|
|
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
|
-
treats it as unknown (ADR 0005). So are a
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
8
|
+
treats it as unknown (ADR 0005). So are a catalog foreign key onto a
|
|
9
|
+
table the SQL declares that cannot be bound to that declaration, and, about
|
|
10
|
+
the SQL itself (`SQL_WARNINGS`), a constraint the dialect does not enforce,
|
|
11
|
+
a CHECK constraint that states no Enumerated Domain, a comparison that depends on something the
|
|
12
|
+
values do not show, like a zoned timestamp's zone (`dialects.py`), a
|
|
13
|
+
comparison of composites whose elements may be NULL, a proved Property
|
|
14
|
+
that holds only because a column it names is always NULL, a name that may
|
|
15
|
+
be one the engine gave a repeated column of a derived table, and a function
|
|
16
|
+
call whose result type sqlassert does not know for the dialect.
|
|
13
17
|
Warnings never make a Report fail.
|
|
14
18
|
"""
|
|
15
19
|
|
|
16
20
|
from __future__ import annotations
|
|
17
21
|
|
|
22
|
+
from collections.abc import Iterable
|
|
18
23
|
from dataclasses import dataclass
|
|
19
24
|
|
|
20
25
|
from sqlassert.provenance import Origin
|
|
21
26
|
|
|
27
|
+
def quoted(name: str) -> str:
|
|
28
|
+
"""A column name, or a term naming one, as messages write it: 'job'."""
|
|
29
|
+
return f"'{name}'"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def quoted_all(names: Iterable[str]) -> str:
|
|
33
|
+
return ", ".join(quoted(name) for name in names)
|
|
34
|
+
|
|
35
|
+
|
|
22
36
|
CATALOG_METADATA_UNAVAILABLE = "catalog-metadata-unavailable"
|
|
37
|
+
ALWAYS_NULL_COLUMN = "always-null-column"
|
|
23
38
|
AMBIGUOUS_COLUMN = "ambiguous-column"
|
|
24
|
-
|
|
39
|
+
AMBIGUOUS_DUPLICATE_COLUMN = "ambiguous-duplicate-column"
|
|
25
40
|
CARDINALITY_ON_FILTERING_JOIN = "cardinality-on-filtering-join"
|
|
26
41
|
CATALOG_RELATION_NOT_FOUND = "catalog-relation-not-found"
|
|
27
42
|
COMPOSITE_COMPARISON = "composite-comparison"
|
|
28
43
|
CONSTRAINT_WITHOUT_TABLE = "constraint-without-table"
|
|
29
44
|
DUPLICATE_DECLARATION = "duplicate-declaration"
|
|
45
|
+
IGNORED_CHECK_CONSTRAINT = "ignored-check-constraint"
|
|
30
46
|
INCOMPLETE_CATALOG_METADATA = "incomplete-catalog-metadata"
|
|
31
47
|
INVALID_FOREIGN_KEY_CONSTRAINT = "invalid-foreign-key-constraint"
|
|
32
48
|
MULTIPLE_ROOT_SELECTS = "multiple-root-selects"
|
|
@@ -34,12 +50,15 @@ RECURSIVE_VIEW_DEFINITION = "recursive-view-definition"
|
|
|
34
50
|
SQL_PARSE_FAILED = "sql-parse-failed"
|
|
35
51
|
UNANALYZED_ASSERTION = "unanalyzed-assertion"
|
|
36
52
|
UNATTACHED_MARKER = "unattached-marker"
|
|
53
|
+
UNBOUND_FOREIGN_KEY = "unbound-foreign-key"
|
|
37
54
|
UNDECLARED_TABLE = "undeclared-table"
|
|
38
55
|
UNENFORCED_CONSTRAINT = "unenforced-constraint"
|
|
39
56
|
UNKNOWN_ASSERTED_COLUMN = "unknown-asserted-column"
|
|
57
|
+
UNKNOWN_FUNCTION = "unknown-function"
|
|
40
58
|
UNRESOLVED_ASSERTED_COLUMN = "unresolved-asserted-column"
|
|
41
59
|
UNKNOWN_REFERENCED_COLUMN = "unknown-referenced-column"
|
|
42
60
|
UNRECOGNIZED_MARKER = "unrecognized-marker"
|
|
61
|
+
UNSUPPORTED_CONSTRUCT = "unsupported-construct"
|
|
43
62
|
UNSUPPORTED_CREATE_STATEMENT = "unsupported-create-statement"
|
|
44
63
|
UNSUPPORTED_NATURAL_JOIN = "unsupported-natural-join"
|
|
45
64
|
UNSUPPORTED_STATEMENT = "unsupported-statement"
|
|
@@ -54,4 +73,9 @@ class Diagnostic:
|
|
|
54
73
|
|
|
55
74
|
|
|
56
75
|
# Warnings about the SQL itself, which no connection answers: `analyze_database` keeps them.
|
|
57
|
-
|
|
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
|
+
SQL_WARNINGS = frozenset({
|
|
79
|
+
ALWAYS_NULL_COLUMN, AMBIGUOUS_DUPLICATE_COLUMN, COMPOSITE_COMPARISON, IGNORED_CHECK_CONSTRAINT, UNENFORCED_CONSTRAINT, UNKNOWN_FUNCTION,
|
|
80
|
+
ZONED_TIMESTAMP_CAST,
|
|
81
|
+
})
|