sqlassert 0.1.2__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.
Files changed (50) hide show
  1. sqlassert/__init__.py +34 -9
  2. sqlassert/__main__.py +9 -0
  3. sqlassert/check.py +451 -0
  4. sqlassert/diagnostics.py +70 -0
  5. sqlassert/dialects.py +258 -0
  6. sqlassert/discovery/__init__.py +30 -0
  7. sqlassert/discovery/bigquery.py +71 -0
  8. sqlassert/discovery/databricks.py +18 -0
  9. sqlassert/discovery/duckdb.py +159 -0
  10. sqlassert/discovery/fetcher.py +418 -0
  11. sqlassert/discovery/information_schema.py +327 -0
  12. sqlassert/discovery/mysql.py +70 -0
  13. sqlassert/discovery/postgres.py +142 -0
  14. sqlassert/discovery/redshift.py +36 -0
  15. sqlassert/discovery/snowflake.py +63 -0
  16. sqlassert/discovery/trino.py +37 -0
  17. sqlassert/edits.py +240 -0
  18. sqlassert/hazards.py +574 -0
  19. sqlassert/ir/__init__.py +58 -0
  20. sqlassert/ir/convert.py +3509 -0
  21. sqlassert/ir/model.py +779 -0
  22. sqlassert/main.py +51 -0
  23. sqlassert/properties.py +121 -0
  24. sqlassert/provenance.py +73 -0
  25. sqlassert/python_engine.py +356 -0
  26. sqlassert/reporting.py +105 -0
  27. sqlassert/rewrites.py +1541 -0
  28. sqlassert/rules/STYLEGUIDE.md +19 -0
  29. sqlassert/rules/__init__.py +11 -0
  30. sqlassert/rules/column_set.py +34 -0
  31. sqlassert/rules/domain.py +472 -0
  32. sqlassert/rules/equality.py +442 -0
  33. sqlassert/rules/exactly_one.py +114 -0
  34. sqlassert/rules/foreign_key.py +319 -0
  35. sqlassert/rules/join_cardinality.py +116 -0
  36. sqlassert/rules/nullability.py +627 -0
  37. sqlassert/rules/uniqueness.py +904 -0
  38. sqlassert/sql_parse.py +1081 -0
  39. sqlassert/suggest.py +418 -0
  40. sqlassert-0.3.3.dist-info/METADATA +807 -0
  41. sqlassert-0.3.3.dist-info/RECORD +46 -0
  42. {sqlassert-0.1.2.dist-info → sqlassert-0.3.3.dist-info}/WHEEL +1 -1
  43. sqlassert-0.3.3.dist-info/entry_points.txt +2 -0
  44. sqlassert-0.3.3.dist-info/licenses/LICENSE +21 -0
  45. sqlassert-0.3.3.dist-info/top_level.txt +2 -0
  46. sqlassert_cli.py +130 -0
  47. sqlassert/unique.py +0 -605
  48. sqlassert-0.1.2.dist-info/METADATA +0 -173
  49. sqlassert-0.1.2.dist-info/RECORD +0 -6
  50. sqlassert-0.1.2.dist-info/top_level.txt +0 -1
sqlassert/__init__.py CHANGED
@@ -1,13 +1,38 @@
1
- from sqlassert.unique import (
2
- UniqueJoinCheckResult,
3
- UniqueJoinValidationResult,
4
- unique_assertions,
5
- validate_unique_joins,
1
+ from sqlassert.main import analyze, analyze_database
2
+ from sqlassert.diagnostics import Diagnostic
3
+ from sqlassert.properties import (
4
+ EnumeratedDomain, ExactlyOneJoin, ExhaustiveCase, FunctionalDependency, ManyToOneJoin, NonNullColumn, NonNullColumns, NonNullElements, NonNullUniqueSet, OneToManyJoin,
5
+ OneToOneJoin, Property, UniqueJoin, UniqueSet,
6
6
  )
7
+ from sqlassert.provenance import AttachmentSite, Origin
8
+ from sqlassert.reporting import AssertionReport, Outcome, RelationFacts, Report
9
+ from sqlassert.suggest import Suggestion, SuggestionReport, suggest
7
10
 
8
11
  __all__ = [
9
- "UniqueJoinCheckResult",
10
- "UniqueJoinValidationResult",
11
- "unique_assertions",
12
- "validate_unique_joins",
12
+ "AssertionReport",
13
+ "AttachmentSite",
14
+ "Diagnostic",
15
+ "EnumeratedDomain",
16
+ "ExactlyOneJoin",
17
+ "ExhaustiveCase",
18
+ "FunctionalDependency",
19
+ "ManyToOneJoin",
20
+ "NonNullColumn",
21
+ "NonNullColumns",
22
+ "NonNullElements",
23
+ "NonNullUniqueSet",
24
+ "OneToManyJoin",
25
+ "OneToOneJoin",
26
+ "Origin",
27
+ "Outcome",
28
+ "Property",
29
+ "RelationFacts",
30
+ "Report",
31
+ "Suggestion",
32
+ "SuggestionReport",
33
+ "UniqueSet",
34
+ "UniqueJoin",
35
+ "analyze",
36
+ "analyze_database",
37
+ "suggest",
13
38
  ]
sqlassert/__main__.py ADDED
@@ -0,0 +1,9 @@
1
+ """Run the command line with `python -m sqlassert`."""
2
+
3
+ import sys
4
+
5
+ from sqlassert_cli import main as main
6
+
7
+
8
+ if __name__ == "__main__":
9
+ sys.exit(main())
sqlassert/check.py ADDED
@@ -0,0 +1,451 @@
1
+ """`sqlassert check`: analyze SQL Programs for CI, and render what they find.
2
+
3
+ Each file is one SQL Program, analyzed from its SQL alone (`analyze`). Every
4
+ `UNKNOWN` assertion and every Diagnostic becomes a Finding; a Connection
5
+ Warning is a warning-level Finding and never fails the check, as it never fails
6
+ a `Report`. The exit codes, Findings and formatters are this module's
7
+ interface for any command that checks SQL (the CLI, the `sqlassert-dbt` plugin);
8
+ `__main__.py` only parses arguments.
9
+
10
+ Configuration comes from `[tool.sqlassert]` in the nearest `pyproject.toml`
11
+ that has one, searched from the working directory upwards; command-line flags
12
+ replace its values.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import glob
18
+ import json
19
+ import os
20
+ import sys
21
+ import tomllib
22
+ from collections.abc import Callable, Iterable, Sequence
23
+ from dataclasses import dataclass, field
24
+ from enum import Enum
25
+ from importlib.metadata import PackageNotFoundError, version
26
+ from pathlib import Path
27
+ from urllib.parse import quote
28
+
29
+ from sqlglot.dialects.dialect import Dialect
30
+
31
+ from sqlassert import diagnostics as diag
32
+ from sqlassert.diagnostics import UNSUPPORTED_CONSTRUCT, Diagnostic
33
+ from sqlassert.main import DEFAULT_DIALECT, analyze
34
+ from sqlassert.provenance import Origin, Span
35
+ from sqlassert.reporting import ASSERTED_KINDS, Outcome, Report
36
+
37
+ # Exit codes, shared by every command that checks SQL.
38
+ EXIT_OK = 0 # every assertion PROVED and no Diagnostic (warnings allowed)
39
+ EXIT_FINDINGS = 1 # an assertion UNKNOWN or a Diagnostic reported
40
+ EXIT_USAGE = 2 # bad arguments or configuration, or SQL that could not be read
41
+
42
+
43
+ def unproved(kind: str) -> str:
44
+ """The code of the Finding an `UNKNOWN` assertion of this marker kind
45
+ produces: it names what was asserted and not proved, e.g. `unproved-unique`."""
46
+ return f"unproved-{kind}"
47
+
48
+
49
+ # Every code a Finding can carry, so a mistyped ignored code is reported rather than ignored.
50
+ UNPROVED_CODES = frozenset(unproved(kind) for kind in ASSERTED_KINDS.values())
51
+ CODES = frozenset(
52
+ UNPROVED_CODES | {value for name, value in vars(diag).items() if name.isupper() and isinstance(value, str)}
53
+ )
54
+
55
+ STDIN = "-"
56
+
57
+
58
+ class Severity(Enum):
59
+ """An `error` fails the check; a `warning` (a Connection Warning) never does."""
60
+
61
+ ERROR = "error"
62
+ WARNING = "warning"
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class Finding:
67
+ """One thing a check reports: an `UNKNOWN` assertion or a Diagnostic.
68
+
69
+ `path` is the file as shown to the user. `evidence` is an `UNKNOWN`
70
+ assertion's explained Evidence, printed only when asked for.
71
+ """
72
+
73
+ path: str
74
+ severity: Severity
75
+ code: str
76
+ message: str
77
+ origin: Origin | None = None
78
+ evidence: str | None = None
79
+
80
+
81
+ @dataclass(frozen=True)
82
+ class Checked:
83
+ """One SQL Program's Report and the Findings it produced, ignored codes removed."""
84
+
85
+ path: str
86
+ report: Report
87
+ findings: tuple[Finding, ...]
88
+
89
+
90
+ class UsageError(Exception):
91
+ """Arguments, configuration, or files that leave nothing to check: exit `EXIT_USAGE`."""
92
+
93
+
94
+ # Checking ------------------------------------------------------------------
95
+
96
+
97
+ def findings(path: str, sql: str, report: Report, *, ignore: Iterable[str] = ()) -> tuple[Finding, ...]:
98
+ """The Findings of one Report, in source order within each kind, codes in `ignore` left out."""
99
+ ignored = frozenset(ignore)
100
+ unknown = [
101
+ Finding(
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 ""),
105
+ assertion.origin, assertion.evidence.explain() if assertion.evidence is not None else None,
106
+ )
107
+ for assertion in report.assertions
108
+ if assertion.outcome is Outcome.UNKNOWN
109
+ ]
110
+ reported = [_diagnostic(path, diagnostic, Severity.ERROR) for diagnostic in report.diagnostics]
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
+ ]
117
+ return tuple(
118
+ finding for finding in sorted((*unknown, *reported, *warned), key=_source_order)
119
+ if finding.code not in ignored
120
+ )
121
+
122
+
123
+ def check(path: str, sql: str, *, dialect: str = DEFAULT_DIALECT, ignore: Iterable[str] = ()) -> Checked:
124
+ """Analyze one SQL Program from its SQL alone."""
125
+ report = analyze(sql, dialect=dialect)
126
+ return Checked(path, report, findings(path, sql, report, ignore=ignore))
127
+
128
+
129
+ def exit_code(checked: Iterable[Checked]) -> int:
130
+ """`EXIT_FINDINGS` when any error-level Finding remains, else `EXIT_OK`."""
131
+ failed = any(finding.severity is Severity.ERROR for result in checked for finding in result.findings)
132
+ return EXIT_FINDINGS if failed else EXIT_OK
133
+
134
+
135
+ def _diagnostic(path: str, diagnostic: Diagnostic, severity: Severity) -> Finding:
136
+ return Finding(path, severity, diagnostic.code, diagnostic.message, diagnostic.origin)
137
+
138
+
139
+ def _source_order(finding: Finding) -> tuple[int, int]:
140
+ """Findings without a line first, then by line and column."""
141
+ origin = finding.origin
142
+ if origin is None or origin.line is None:
143
+ return 0, 0
144
+ return origin.line, origin.span.column if origin.span is not None else 0
145
+
146
+
147
+ def _written(sql: str, origin: Origin) -> str:
148
+ """The marker as written at `origin`, whitespace collapsed; its detail when it has no span."""
149
+ if origin.span is None:
150
+ return origin.detail
151
+ return " ".join(_text(sql, origin.span).split())
152
+
153
+
154
+ def _text(sql: str, span: Span) -> str:
155
+ return sql[_offset(sql, span.line, span.column):_offset(sql, span.end_line, span.end_column)]
156
+
157
+
158
+ def _offset(sql: str, line: int, column: int) -> int:
159
+ """The inverse of `Span.of`: lines end at `\\n` only."""
160
+ start = 0
161
+ for _ in range(line - 1):
162
+ start = sql.index("\n", start) + 1
163
+ return start + column - 1
164
+
165
+
166
+ # Configuration ---------------------------------------------------------------
167
+
168
+
169
+ @dataclass(frozen=True)
170
+ class Config:
171
+ """`[tool.sqlassert]`: `dialect`, `paths` (files, directories, globs;
172
+ relative to `root`), and `ignore` (codes whose Findings are dropped)."""
173
+
174
+ root: Path
175
+ dialect: str = DEFAULT_DIALECT
176
+ paths: tuple[str, ...] = ()
177
+ ignore: frozenset[str] = field(default_factory=frozenset)
178
+
179
+
180
+ _CONFIG_KEYS = {"dialect": str, "paths": list, "ignore": list}
181
+
182
+
183
+ def load_config(start: Path) -> Config:
184
+ """The `[tool.sqlassert]` table of the nearest `pyproject.toml` that has
185
+ one, from `start` upwards; defaults rooted at `start` when none does."""
186
+ for directory in (start, *start.parents):
187
+ pyproject = directory / "pyproject.toml"
188
+ if not pyproject.is_file():
189
+ continue
190
+ try:
191
+ table = tomllib.loads(pyproject.read_text()).get("tool", {}).get("sqlassert")
192
+ except (OSError, tomllib.TOMLDecodeError) as error:
193
+ raise UsageError(f"{pyproject}: {error}") from error
194
+ if table is not None:
195
+ return _config(pyproject, table)
196
+ return Config(start)
197
+
198
+
199
+ def _config(pyproject: Path, table: object) -> Config:
200
+ if not isinstance(table, dict):
201
+ raise UsageError(f"{pyproject}: [tool.sqlassert] must be a table")
202
+ for key, value in table.items():
203
+ expected = _CONFIG_KEYS.get(key)
204
+ if expected is None:
205
+ raise UsageError(f"{pyproject}: unknown key {key!r} in [tool.sqlassert]; the keys are {', '.join(_CONFIG_KEYS)}")
206
+ if not isinstance(value, expected) or (expected is list and not all(isinstance(item, str) for item in value)):
207
+ shape = "a string" if expected is str else "a list of strings"
208
+ raise UsageError(f"{pyproject}: [tool.sqlassert] {key} must be {shape}")
209
+ return Config(
210
+ pyproject.parent,
211
+ dialect=table.get("dialect", DEFAULT_DIALECT),
212
+ paths=tuple(table.get("paths", ())),
213
+ ignore=frozenset(table.get("ignore", ())),
214
+ )
215
+
216
+
217
+ def validate(dialect: str, ignore: Iterable[str]) -> None:
218
+ """Reject a dialect SQLGlot does not know, and an ignored code no Finding carries."""
219
+ try:
220
+ Dialect.get_or_raise(dialect)
221
+ except ValueError as error:
222
+ raise UsageError(str(error)) from error
223
+ unknown = sorted(set(ignore) - CODES)
224
+ if unknown:
225
+ raise UsageError(f"unknown code(s) to ignore: {', '.join(unknown)}; the codes are {', '.join(sorted(CODES))}")
226
+
227
+
228
+ def expand(patterns: Sequence[str], root: Path) -> list[Path]:
229
+ """The SQL files `patterns` name, relative to `root`, in order and without repeats.
230
+
231
+ A file is itself; a directory is every `*.sql` under it; anything with a
232
+ glob character is a recursive glob (`**` crosses directories). A pattern
233
+ that names no file is a usage error: a check that silently checks nothing
234
+ would pass.
235
+ """
236
+ found: dict[Path, None] = {}
237
+ for pattern in patterns:
238
+ if pattern == STDIN:
239
+ found[Path(STDIN)] = None
240
+ continue
241
+ path = root / pattern
242
+ if glob.has_magic(pattern):
243
+ matches = sorted(Path(match) for match in glob.glob(str(path), recursive=True) if Path(match).is_file())
244
+ elif path.is_dir():
245
+ matches = sorted(path.rglob("*.sql"))
246
+ elif path.is_file():
247
+ matches = [path]
248
+ else:
249
+ raise UsageError(f"{pattern}: no such file or directory")
250
+ if not matches:
251
+ raise UsageError(f"{pattern} matches no SQL files")
252
+ found.update(dict.fromkeys(matches))
253
+ return list(found)
254
+
255
+
256
+ def display(path: Path) -> str:
257
+ """How a checked file is named in output: relative to the working directory when inside it."""
258
+ if path == Path(STDIN):
259
+ return "<stdin>"
260
+ try:
261
+ return path.resolve().relative_to(Path.cwd().resolve()).as_posix()
262
+ except ValueError:
263
+ return str(path)
264
+
265
+
266
+ def read_sql(path: Path) -> str:
267
+ """A SQL Program's text; `-` reads stdin."""
268
+ if path == Path(STDIN):
269
+ return sys.stdin.read()
270
+ try:
271
+ return path.read_text()
272
+ except (OSError, UnicodeDecodeError) as error:
273
+ raise UsageError(f"{path}: {error}") from error
274
+
275
+
276
+ # Output --------------------------------------------------------------------
277
+
278
+
279
+ def indented(text: str, prefix: str = " ") -> str:
280
+ """Explained Evidence, set under the line it explains."""
281
+ return "\n".join(prefix + line for line in text.splitlines())
282
+
283
+
284
+ def render_text(checked: Sequence[Checked], *, explain: bool = False) -> str:
285
+ """`path:line:column: severity code: message`, then a summary line."""
286
+ lines = []
287
+ for result in checked:
288
+ for finding in result.findings:
289
+ lines.append(f"{_place(finding)}: {finding.severity.value} {finding.code}: {finding.message}")
290
+ if explain and finding.evidence is not None:
291
+ lines.append(indented(finding.evidence))
292
+ lines.append(_summary_line(checked))
293
+ return "\n".join(lines) + "\n"
294
+
295
+
296
+ def render_json(checked: Sequence[Checked], *, explain: bool = False) -> str:
297
+ """Every assertion's outcome and every Finding, as one JSON document."""
298
+ def finding(item: Finding) -> dict:
299
+ shown = {
300
+ "path": item.path, "severity": item.severity.value, "code": item.code, "message": item.message,
301
+ "location": _location(item.origin),
302
+ }
303
+ if explain and item.evidence is not None:
304
+ shown["evidence"] = item.evidence
305
+ return shown
306
+
307
+ document = {
308
+ "assertions": [
309
+ {"path": result.path, "id": assertion.assertion_id, "outcome": assertion.outcome.value, "location": _location(assertion.origin)}
310
+ for result in checked for assertion in result.report.assertions
311
+ ],
312
+ "findings": [finding(item) for result in checked for item in result.findings],
313
+ "summary": _summary(checked),
314
+ }
315
+ return json.dumps(document, indent=2) + "\n"
316
+
317
+
318
+ def render_sarif(checked: Sequence[Checked], *, explain: bool = False) -> str:
319
+ """A SARIF 2.1.0 log, as GitHub code scanning reads it. Columns count characters."""
320
+ found = [finding for result in checked for finding in result.findings]
321
+ codes = sorted({finding.code for finding in found})
322
+ driver: dict = {"name": "sqlassert", "informationUri": "https://github.com/polvoazul/sqlassert", "rules": [
323
+ {"id": code, "shortDescription": {"text": _RULE_DESCRIPTIONS.get(code, code.replace("-", " "))}}
324
+ for code in codes
325
+ ]}
326
+ try:
327
+ driver["version"] = version("sqlassert")
328
+ except PackageNotFoundError:
329
+ pass
330
+
331
+ def result(finding: Finding) -> dict:
332
+ message = finding.message
333
+ if explain and finding.evidence is not None:
334
+ message += "\n\n" + finding.evidence
335
+ location: dict = {"artifactLocation": {"uri": _uri(finding.path)}}
336
+ origin = finding.origin
337
+ if origin is not None and origin.line is not None:
338
+ region: dict = {"startLine": origin.line}
339
+ if origin.span is not None:
340
+ region.update(
341
+ startColumn=origin.span.column, endLine=origin.span.end_line, endColumn=origin.span.end_column
342
+ )
343
+ location["region"] = region
344
+ return {
345
+ "ruleId": finding.code,
346
+ "ruleIndex": codes.index(finding.code),
347
+ "level": finding.severity.value,
348
+ "message": {"text": message},
349
+ "locations": [{"physicalLocation": location}],
350
+ }
351
+
352
+ log = {
353
+ "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
354
+ "version": "2.1.0",
355
+ "runs": [{"tool": {"driver": driver}, "columnKind": "unicodeCodePoints", "results": [result(f) for f in found]}],
356
+ }
357
+ return json.dumps(log, indent=2) + "\n"
358
+
359
+
360
+ def render_github(checked: Sequence[Checked], *, explain: bool = False) -> str:
361
+ """GitHub Actions workflow commands: one `::error` or `::warning` annotation per Finding."""
362
+ lines = []
363
+ for result in checked:
364
+ for finding in result.findings:
365
+ properties = {"file": finding.path}
366
+ origin = finding.origin
367
+ if origin is not None and origin.line is not None:
368
+ properties["line"] = str(origin.line)
369
+ span = origin.span
370
+ if span is not None:
371
+ properties["endLine"] = str(span.end_line)
372
+ # GitHub honours columns only within one line.
373
+ if span.end_line == span.line:
374
+ properties.update(col=str(span.column), endColumn=str(span.end_column))
375
+ properties["title"] = f"sqlassert {finding.code}"
376
+ message = finding.message
377
+ if explain and finding.evidence is not None:
378
+ message += "\n" + finding.evidence
379
+ shown = ",".join(f"{key}={_escape_property(value)}" for key, value in properties.items())
380
+ lines.append(f"::{finding.severity.value} {shown}::{_escape_data(message)}")
381
+ return "".join(line + "\n" for line in lines)
382
+
383
+
384
+ FORMATS: dict[str, Callable[..., str]] = {
385
+ "text": render_text,
386
+ "json": render_json,
387
+ "sarif": render_sarif,
388
+ "github": render_github,
389
+ }
390
+
391
+ _RULE_DESCRIPTIONS = {
392
+ unproved(kind): f"An asserted {kind.replace('-', ' ')} Property is not proved (UNKNOWN)" for kind in ASSERTED_KINDS.values()
393
+ }
394
+
395
+
396
+ def _place(finding: Finding) -> str:
397
+ origin = finding.origin
398
+ if origin is None or origin.line is None:
399
+ return finding.path
400
+ if origin.span is None:
401
+ return f"{finding.path}:{origin.line}"
402
+ return f"{finding.path}:{origin.line}:{origin.span.column}"
403
+
404
+
405
+ def _location(origin: Origin | None) -> dict | None:
406
+ if origin is None or origin.line is None:
407
+ return None
408
+ if origin.span is None:
409
+ return {"line": origin.line}
410
+ span = origin.span
411
+ return {"line": span.line, "column": span.column, "end_line": span.end_line, "end_column": span.end_column}
412
+
413
+
414
+ def _summary(checked: Sequence[Checked]) -> dict:
415
+ assertions = [assertion for result in checked for assertion in result.report.assertions]
416
+ found = [finding for result in checked for finding in result.findings]
417
+ return {
418
+ "files": len(checked),
419
+ "assertions": len(assertions),
420
+ "proved": sum(assertion.outcome is Outcome.PROVED for assertion in assertions),
421
+ "unknown": sum(assertion.outcome is Outcome.UNKNOWN for assertion in assertions),
422
+ "errors": sum(finding.severity is Severity.ERROR for finding in found),
423
+ "warnings": sum(finding.severity is Severity.WARNING for finding in found),
424
+ }
425
+
426
+
427
+ def _summary_line(checked: Sequence[Checked]) -> str:
428
+ counts = _summary(checked)
429
+
430
+ def plural(count: int, noun: str) -> str:
431
+ return f"{count} {noun}{'' if count == 1 else 's'}"
432
+
433
+ return (
434
+ f"{plural(counts['files'], 'file')} checked: {plural(counts['assertions'], 'assertion')} "
435
+ f"({counts['proved']} PROVED, {counts['unknown']} UNKNOWN), "
436
+ f"{plural(counts['errors'], 'error')}, {plural(counts['warnings'], 'warning')}"
437
+ )
438
+
439
+
440
+ def _uri(path: str) -> str:
441
+ if os.path.isabs(path):
442
+ return Path(path).as_uri()
443
+ return quote(path)
444
+
445
+
446
+ def _escape_data(text: str) -> str:
447
+ return text.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")
448
+
449
+
450
+ def _escape_property(text: str) -> str:
451
+ return _escape_data(text).replace(":", "%3A").replace(",", "%2C")
@@ -0,0 +1,70 @@
1
+ """Explicit statements about what analysis could not do.
2
+
3
+ A diagnostic reports a program the engine does not support. It is never a
4
+ Disproof and never an inference: it says that analysis stopped short, and why.
5
+
6
+ A warning is a Diagnostic too, reported apart (`Report.warnings`): the program
7
+ is supported, but a fact a connection would supply is missing, so analysis
8
+ treats it as unknown (ADR 0005). So are a constraint the dialect does not
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.
14
+ Warnings never make a Report fail.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from collections.abc import Iterable
20
+ from dataclasses import dataclass
21
+
22
+ from sqlassert.provenance import Origin
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
+
33
+ CATALOG_METADATA_UNAVAILABLE = "catalog-metadata-unavailable"
34
+ ALWAYS_NULL_COLUMN = "always-null-column"
35
+ AMBIGUOUS_COLUMN = "ambiguous-column"
36
+ CARDINALITY_ON_FILTERING_JOIN = "cardinality-on-filtering-join"
37
+ CATALOG_RELATION_NOT_FOUND = "catalog-relation-not-found"
38
+ COMPOSITE_COMPARISON = "composite-comparison"
39
+ CONSTRAINT_WITHOUT_TABLE = "constraint-without-table"
40
+ DUPLICATE_DECLARATION = "duplicate-declaration"
41
+ IGNORED_CHECK_CONSTRAINT = "ignored-check-constraint"
42
+ INCOMPLETE_CATALOG_METADATA = "incomplete-catalog-metadata"
43
+ INVALID_FOREIGN_KEY_CONSTRAINT = "invalid-foreign-key-constraint"
44
+ MULTIPLE_ROOT_SELECTS = "multiple-root-selects"
45
+ RECURSIVE_VIEW_DEFINITION = "recursive-view-definition"
46
+ SQL_PARSE_FAILED = "sql-parse-failed"
47
+ UNANALYZED_ASSERTION = "unanalyzed-assertion"
48
+ UNATTACHED_MARKER = "unattached-marker"
49
+ UNDECLARED_TABLE = "undeclared-table"
50
+ UNENFORCED_CONSTRAINT = "unenforced-constraint"
51
+ UNKNOWN_ASSERTED_COLUMN = "unknown-asserted-column"
52
+ UNRESOLVED_ASSERTED_COLUMN = "unresolved-asserted-column"
53
+ UNKNOWN_REFERENCED_COLUMN = "unknown-referenced-column"
54
+ UNRECOGNIZED_MARKER = "unrecognized-marker"
55
+ UNSUPPORTED_CONSTRUCT = "unsupported-construct"
56
+ UNSUPPORTED_CREATE_STATEMENT = "unsupported-create-statement"
57
+ UNSUPPORTED_NATURAL_JOIN = "unsupported-natural-join"
58
+ UNSUPPORTED_STATEMENT = "unsupported-statement"
59
+ ZONED_TIMESTAMP_CAST = "zoned-timestamp-cast"
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class Diagnostic:
64
+ code: str
65
+ message: str
66
+ origin: Origin | None = None
67
+
68
+
69
+ # Warnings about the SQL itself, which no connection answers: `analyze_database` keeps them.
70
+ SQL_WARNINGS = frozenset({ALWAYS_NULL_COLUMN, COMPOSITE_COMPARISON, IGNORED_CHECK_CONSTRAINT, ZONED_TIMESTAMP_CAST})