sqlassert 0.3.3__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.
Files changed (65) hide show
  1. sqlassert/__init__.py +1 -2
  2. sqlassert/check.py +88 -13
  3. sqlassert/diagnostics.py +17 -6
  4. sqlassert/dialects.py +437 -7
  5. sqlassert/discovery/bigquery.py +3 -1
  6. sqlassert/discovery/databricks.py +25 -2
  7. sqlassert/discovery/duckdb.py +49 -7
  8. sqlassert/discovery/fetcher.py +130 -21
  9. sqlassert/discovery/information_schema.py +30 -2
  10. sqlassert/discovery/mysql.py +22 -1
  11. sqlassert/discovery/postgres.py +22 -5
  12. sqlassert/discovery/redshift.py +3 -2
  13. sqlassert/discovery/snowflake.py +3 -0
  14. sqlassert/discovery/trino.py +2 -2
  15. sqlassert/hazards.py +248 -87
  16. sqlassert/ir/__init__.py +4 -1
  17. sqlassert/ir/convert/__init__.py +13 -0
  18. sqlassert/ir/convert/aggregation.py +439 -0
  19. sqlassert/ir/convert/builtins.py +140 -0
  20. sqlassert/ir/convert/expressions.py +572 -0
  21. sqlassert/ir/convert/joins.py +264 -0
  22. sqlassert/ir/convert/markers.py +249 -0
  23. sqlassert/ir/convert/parser.py +253 -0
  24. sqlassert/ir/convert/queries.py +259 -0
  25. sqlassert/ir/convert/schema.py +606 -0
  26. sqlassert/ir/convert/scopes.py +205 -0
  27. sqlassert/ir/convert/selects.py +337 -0
  28. sqlassert/ir/convert/shared.py +429 -0
  29. sqlassert/ir/convert/sources.py +432 -0
  30. sqlassert/ir/convert/subqueries.py +364 -0
  31. sqlassert/ir/convert/value_types.py +223 -0
  32. sqlassert/ir/convert/windows.py +275 -0
  33. sqlassert/ir/model.py +125 -47
  34. sqlassert/ir/names.py +63 -0
  35. sqlassert/properties.py +12 -1
  36. sqlassert/provenance.py +5 -1
  37. sqlassert/python_engine.py +104 -44
  38. sqlassert/reporting.py +33 -32
  39. sqlassert/rewrites.py +111 -61
  40. sqlassert/rules/STYLEGUIDE.md +3 -2
  41. sqlassert/rules/causes/__init__.py +41 -0
  42. sqlassert/rules/causes/coverage.py +113 -0
  43. sqlassert/rules/causes/domain.py +123 -0
  44. sqlassert/rules/causes/joins.py +73 -0
  45. sqlassert/rules/causes/nulls.py +154 -0
  46. sqlassert/rules/causes/unique.py +523 -0
  47. sqlassert/rules/domain.py +8 -7
  48. sqlassert/rules/equality.py +6 -147
  49. sqlassert/rules/exactly_one.py +2 -1
  50. sqlassert/rules/foreign_key.py +8 -9
  51. sqlassert/rules/join_cardinality.py +282 -41
  52. sqlassert/rules/nullability.py +5 -5
  53. sqlassert/rules/uniqueness.py +171 -47
  54. sqlassert/rules/value_typing.py +337 -0
  55. sqlassert/sql_parse.py +28 -1
  56. sqlassert/suggest.py +11 -15
  57. sqlassert-0.4.1.dist-info/METADATA +235 -0
  58. sqlassert-0.4.1.dist-info/RECORD +69 -0
  59. sqlassert/ir/convert.py +0 -3509
  60. sqlassert-0.3.3.dist-info/METADATA +0 -807
  61. sqlassert-0.3.3.dist-info/RECORD +0 -46
  62. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/WHEEL +0 -0
  63. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/entry_points.txt +0 -0
  64. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/licenses/LICENSE +0 -0
  65. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/top_level.txt +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, RelationFacts, Report
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/check.py CHANGED
@@ -32,7 +32,7 @@ from sqlassert import diagnostics as diag
32
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. `evidence` is an `UNKNOWN`
70
- assertion's explained Evidence, printed only when asked for.
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)
@@ -102,7 +105,8 @@ def findings(path: str, sql: str, report: Report, *, ignore: Iterable[str] = ())
102
105
  path, Severity.ERROR, unproved(assertion.kind),
103
106
  f"{_written(sql, assertion.origin)} is not proved (UNKNOWN)"
104
107
  + (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,
108
+ assertion.origin, _evidence(path, assertion),
109
+ assertion.explanation.causes() if assertion.explanation is not None else (),
106
110
  )
107
111
  for assertion in report.assertions
108
112
  if assertion.outcome is Outcome.UNKNOWN
@@ -120,6 +124,53 @@ def findings(path: str, sql: str, report: Report, *, ignore: Iterable[str] = ())
120
124
  )
121
125
 
122
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
+
123
174
  def check(path: str, sql: str, *, dialect: str = DEFAULT_DIALECT, ignore: Iterable[str] = ()) -> Checked:
124
175
  """Analyze one SQL Program from its SQL alone."""
125
176
  report = analyze(sql, dialect=dialect)
@@ -287,6 +338,7 @@ def render_text(checked: Sequence[Checked], *, explain: bool = False) -> str:
287
338
  for result in checked:
288
339
  for finding in result.findings:
289
340
  lines.append(f"{_place(finding)}: {finding.severity.value} {finding.code}: {finding.message}")
341
+ lines.extend(indented(line) for line in cause_lines(finding))
290
342
  if explain and finding.evidence is not None:
291
343
  lines.append(indented(finding.evidence))
292
344
  lines.append(_summary_line(checked))
@@ -300,6 +352,11 @@ def render_json(checked: Sequence[Checked], *, explain: bool = False) -> str:
300
352
  "path": item.path, "severity": item.severity.value, "code": item.code, "message": item.message,
301
353
  "location": _location(item.origin),
302
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
+ ]
303
360
  if explain and item.evidence is not None:
304
361
  shown["evidence"] = item.evidence
305
362
  return shown
@@ -328,12 +385,8 @@ def render_sarif(checked: Sequence[Checked], *, explain: bool = False) -> str:
328
385
  except PackageNotFoundError:
329
386
  pass
330
387
 
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
388
+ def physical(path: str, origin: Origin | None) -> dict:
389
+ location: dict = {"artifactLocation": {"uri": _uri(path)}}
337
390
  if origin is not None and origin.line is not None:
338
391
  region: dict = {"startLine": origin.line}
339
392
  if origin.span is not None:
@@ -341,13 +394,27 @@ def render_sarif(checked: Sequence[Checked], *, explain: bool = False) -> str:
341
394
  startColumn=origin.span.column, endLine=origin.span.end_line, endColumn=origin.span.end_column
342
395
  )
343
396
  location["region"] = region
344
- 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 = {
345
404
  "ruleId": finding.code,
346
405
  "ruleIndex": codes.index(finding.code),
347
406
  "level": finding.severity.value,
348
407
  "message": {"text": message},
349
- "locations": [{"physicalLocation": location}],
408
+ "locations": [{"physicalLocation": physical(finding.path, finding.origin)}],
350
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
351
418
 
352
419
  log = {
353
420
  "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
@@ -373,11 +440,19 @@ def render_github(checked: Sequence[Checked], *, explain: bool = False) -> str:
373
440
  if span.end_line == span.line:
374
441
  properties.update(col=str(span.column), endColumn=str(span.end_column))
375
442
  properties["title"] = f"sqlassert {finding.code}"
376
- message = finding.message
443
+ message = "\n".join([finding.message, *cause_lines(finding)])
377
444
  if explain and finding.evidence is not None:
378
445
  message += "\n" + finding.evidence
379
446
  shown = ",".join(f"{key}={_escape_property(value)}" for key, value in properties.items())
380
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)}")
381
456
  return "".join(line + "\n" for line in lines)
382
457
 
383
458
 
sqlassert/diagnostics.py CHANGED
@@ -5,12 +5,15 @@ 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 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
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
11
12
  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
+ 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.
14
17
  Warnings never make a Report fail.
15
18
  """
16
19
 
@@ -33,6 +36,7 @@ def quoted_all(names: Iterable[str]) -> str:
33
36
  CATALOG_METADATA_UNAVAILABLE = "catalog-metadata-unavailable"
34
37
  ALWAYS_NULL_COLUMN = "always-null-column"
35
38
  AMBIGUOUS_COLUMN = "ambiguous-column"
39
+ AMBIGUOUS_DUPLICATE_COLUMN = "ambiguous-duplicate-column"
36
40
  CARDINALITY_ON_FILTERING_JOIN = "cardinality-on-filtering-join"
37
41
  CATALOG_RELATION_NOT_FOUND = "catalog-relation-not-found"
38
42
  COMPOSITE_COMPARISON = "composite-comparison"
@@ -46,9 +50,11 @@ RECURSIVE_VIEW_DEFINITION = "recursive-view-definition"
46
50
  SQL_PARSE_FAILED = "sql-parse-failed"
47
51
  UNANALYZED_ASSERTION = "unanalyzed-assertion"
48
52
  UNATTACHED_MARKER = "unattached-marker"
53
+ UNBOUND_FOREIGN_KEY = "unbound-foreign-key"
49
54
  UNDECLARED_TABLE = "undeclared-table"
50
55
  UNENFORCED_CONSTRAINT = "unenforced-constraint"
51
56
  UNKNOWN_ASSERTED_COLUMN = "unknown-asserted-column"
57
+ UNKNOWN_FUNCTION = "unknown-function"
52
58
  UNRESOLVED_ASSERTED_COLUMN = "unresolved-asserted-column"
53
59
  UNKNOWN_REFERENCED_COLUMN = "unknown-referenced-column"
54
60
  UNRECOGNIZED_MARKER = "unrecognized-marker"
@@ -67,4 +73,9 @@ class Diagnostic:
67
73
 
68
74
 
69
75
  # 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})
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
+ })