sqlassert-dbt 0.3.3__py3-none-any.whl → 0.4.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sqlassert_dbt/__init__.py +1 -1
- sqlassert_dbt/__main__.py +1 -1
- sqlassert_dbt/connect.py +6 -8
- sqlassert_dbt/expectations.py +49 -17
- sqlassert_dbt/manifest.py +52 -2
- sqlassert_dbt/program.py +187 -125
- sqlassert_dbt/project.py +8 -2
- {sqlassert_dbt-0.3.3.dist-info → sqlassert_dbt-0.4.2.dist-info}/METADATA +7 -9
- sqlassert_dbt-0.4.2.dist-info/RECORD +15 -0
- sqlassert_dbt-0.3.3.dist-info/RECORD +0 -15
- {sqlassert_dbt-0.3.3.dist-info → sqlassert_dbt-0.4.2.dist-info}/WHEEL +0 -0
- {sqlassert_dbt-0.3.3.dist-info → sqlassert_dbt-0.4.2.dist-info}/entry_points.txt +0 -0
- {sqlassert_dbt-0.3.3.dist-info → sqlassert_dbt-0.4.2.dist-info}/licenses/LICENSE +0 -0
- {sqlassert_dbt-0.3.3.dist-info → sqlassert_dbt-0.4.2.dist-info}/top_level.txt +0 -0
sqlassert_dbt/__init__.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""dbt integration: check a dbt project's tests and Property Markers from its manifest
|
|
1
|
+
"""dbt integration: check a dbt project's tests and Property Markers from its manifest.
|
|
2
2
|
|
|
3
3
|
`analyze_project(project_dir)` reads `target/manifest.json` and returns a
|
|
4
4
|
`DbtReport`: which tests the SQL proves (skippable), which it does not, which
|
sqlassert_dbt/__main__.py
CHANGED
|
@@ -59,7 +59,7 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
59
59
|
commands = parser.add_subparsers(dest="command", required=True)
|
|
60
60
|
check = commands.add_parser(
|
|
61
61
|
"check",
|
|
62
|
-
help="check the tests and markers of a compiled project
|
|
62
|
+
help="check the tests and markers of a compiled project",
|
|
63
63
|
description="Check a dbt project's tests and markers from its target/manifest.json (run `dbt compile` first). "
|
|
64
64
|
f"Exit status: {EXIT_OK} every marker PROVED, {EXIT_FINDINGS} a marker UNKNOWN or a diagnostic reported, "
|
|
65
65
|
f"{EXIT_USAGE} the manifest cannot be read.",
|
sqlassert_dbt/connect.py
CHANGED
|
@@ -61,14 +61,12 @@ def dbt_fetcher(project: Path, dbt_arguments: list[str]) -> Generator[DatabaseKn
|
|
|
61
61
|
"""A fetcher over the connection dbt opens for `project` with the
|
|
62
62
|
profile, target, profiles directory and vars in `dbt_arguments`, closed
|
|
63
63
|
on exit: a DuckDB file takes one writer, so close it before dbt runs again."""
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
except ImportError as error:
|
|
71
|
-
raise ConnectError(f"--connect needs dbt installed in sqlassert-dbt's Python ({error})") from error
|
|
64
|
+
import yaml
|
|
65
|
+
from dbt.adapters.factory import cleanup_connections, get_adapter, register_adapter, reset_adapters
|
|
66
|
+
from dbt.config.runtime import RuntimeConfig
|
|
67
|
+
from dbt.flags import set_from_args
|
|
68
|
+
from dbt.mp_context import get_mp_context
|
|
69
|
+
|
|
72
70
|
try:
|
|
73
71
|
args = Namespace(
|
|
74
72
|
project_dir=str(project), profiles_dir=str(_profiles_dir(project, dbt_arguments)),
|
sqlassert_dbt/expectations.py
CHANGED
|
@@ -30,14 +30,8 @@ from sqlassert.sql_parse import literal_value
|
|
|
30
30
|
# Referential Coverage (a dbt relationships test checks no Unique Set on its target).
|
|
31
31
|
type PropertyKind = Literal["unique", "key", "not_null", "enum", "coverage"]
|
|
32
32
|
|
|
33
|
-
#
|
|
34
|
-
# (
|
|
35
|
-
# NOT NULL only; their keys are informational. Constraints never apply to views.
|
|
36
|
-
_ENFORCED_CONSTRAINTS = {
|
|
37
|
-
"postgres": frozenset({"not_null", "unique", "primary_key", "foreign_key"}),
|
|
38
|
-
"duckdb": frozenset({"not_null", "unique", "primary_key", "foreign_key"}),
|
|
39
|
-
}
|
|
40
|
-
_NOT_NULL_ONLY = frozenset({"not_null"})
|
|
33
|
+
# Constraints a contracted table declares, whether or not the adapter enforces
|
|
34
|
+
# them (ADR 0012); they never apply to views.
|
|
41
35
|
_CONSTRAINED_MATERIALIZATIONS = {"table", "incremental"}
|
|
42
36
|
|
|
43
37
|
_IDENTIFIER = re.compile(r"[A-Za-z_][A-Za-z0-9_$]*")
|
|
@@ -91,18 +85,28 @@ def _test(test: Test, relations: Mapping[str, Relation]) -> Expectation | None:
|
|
|
91
85
|
weakness = _weakness(test)
|
|
92
86
|
unprovable = _threshold_unprovable(test)
|
|
93
87
|
name = test.test_name if test.namespace is None else f"{test.namespace}.{test.test_name}"
|
|
88
|
+
kwargs = test.kwargs
|
|
89
|
+
# Written with or without its package's name, and whether the project
|
|
90
|
+
# overrides it or not: an override that keeps the name and signature is
|
|
91
|
+
# taken to keep the meaning.
|
|
92
|
+
expectation = f"dbt_expectations.{test.test_name}" if test.namespace in (None, "dbt_expectations") else None
|
|
93
|
+
if expectation in _DBT_EXPECTATIONS:
|
|
94
|
+
# The same checks as the core tests, unless a filter or ignored rows narrow them.
|
|
95
|
+
if kwargs.get("row_condition") or kwargs.get("ignore_row_if", "all_values_are_missing") not in _CHECKED_ROWS[expectation]:
|
|
96
|
+
return replace(base, asserted=None, declared=None, unprovable="it checks only the rows its row_condition or ignore_row_if keeps")
|
|
97
|
+
name, kwargs = _DBT_EXPECTATIONS[expectation], {**kwargs, **_expectation_kwargs(kwargs)}
|
|
94
98
|
match name:
|
|
95
99
|
case None:
|
|
96
100
|
return replace(base, asserted=None, declared=None, unprovable="a singular test states no Property")
|
|
97
101
|
case "unique" | "not_null" | "accepted_values" | "relationships":
|
|
98
|
-
column = _column(
|
|
102
|
+
column = _column(kwargs.get("column_name") or test.column_name)
|
|
99
103
|
if column is None:
|
|
100
104
|
return replace(
|
|
101
105
|
base,
|
|
102
|
-
unprovable=f"it tests the expression {
|
|
106
|
+
unprovable=f"it tests the expression {kwargs.get('column_name') or test.column_name!r}, not a column",
|
|
103
107
|
)
|
|
104
108
|
case "dbt_utils.unique_combination_of_columns":
|
|
105
|
-
names =
|
|
109
|
+
names = kwargs.get("combination_of_columns")
|
|
106
110
|
columns = tuple(_column(name) for name in names) if isinstance(names, list) and names else (None,)
|
|
107
111
|
if None in columns:
|
|
108
112
|
return replace(base, asserted=None, declared=None, unprovable="its columns are not all plain columns")
|
|
@@ -118,15 +122,15 @@ def _test(test: Test, relations: Mapping[str, Relation]) -> Expectation | None:
|
|
|
118
122
|
case "not_null":
|
|
119
123
|
return replace(base, asserted="not_null", declared="not_null", columns=(column,), unprovable=unprovable, not_a_fact=weakness)
|
|
120
124
|
case "accepted_values":
|
|
121
|
-
values = _accepted_values(
|
|
125
|
+
values = _accepted_values(kwargs.get("values"), kwargs.get("quote", True))
|
|
122
126
|
if values is None:
|
|
123
127
|
return replace(base, asserted=None, declared=None, unprovable="its values are not all string, numeric or boolean literals")
|
|
124
128
|
return replace(
|
|
125
129
|
base, asserted="enum", declared="enum", columns=(column,), values=values, unprovable=unprovable, not_a_fact=weakness,
|
|
126
130
|
)
|
|
127
131
|
case _:
|
|
128
|
-
target = _resolve_call(
|
|
129
|
-
field = _column(
|
|
132
|
+
target = _resolve_call(kwargs.get("to"), test.depends_on, relations)
|
|
133
|
+
field = _column(kwargs.get("field"))
|
|
130
134
|
if target is None or field is None:
|
|
131
135
|
return replace(base, asserted=None, declared=None, unprovable="its `to` or `field` cannot be resolved")
|
|
132
136
|
return replace(
|
|
@@ -135,6 +139,37 @@ def _test(test: Test, relations: Mapping[str, Relation]) -> Expectation | None:
|
|
|
135
139
|
)
|
|
136
140
|
|
|
137
141
|
|
|
142
|
+
# dbt_expectations tests that check at least what a core or dbt_utils test
|
|
143
|
+
# checks: compound uniqueness over the rows not all NULL (rows with some NULL
|
|
144
|
+
# are checked too, which only adds rows to compare) or over the rows with no
|
|
145
|
+
# NULL (a Unique Set exempts the others too), uniqueness, non-null, and a
|
|
146
|
+
# value set (which also rejects NULL, more than accepted_values asks).
|
|
147
|
+
_DBT_EXPECTATIONS = {
|
|
148
|
+
"dbt_expectations.expect_compound_columns_to_be_unique": "dbt_utils.unique_combination_of_columns",
|
|
149
|
+
"dbt_expectations.expect_column_values_to_be_unique": "unique",
|
|
150
|
+
"dbt_expectations.expect_column_values_to_not_be_null": "not_null",
|
|
151
|
+
"dbt_expectations.expect_column_values_to_be_in_set": "accepted_values",
|
|
152
|
+
}
|
|
153
|
+
# The `ignore_row_if` each leaves checking enough rows for its Property.
|
|
154
|
+
_CHECKED_ROWS = {
|
|
155
|
+
name: ("all_values_are_missing", "any_value_is_missing") if name.endswith("compound_columns_to_be_unique")
|
|
156
|
+
else ("all_values_are_missing",)
|
|
157
|
+
for name in _DBT_EXPECTATIONS
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _expectation_kwargs(kwargs: Mapping[str, object]) -> dict[str, object]:
|
|
162
|
+
"""A dbt_expectations test's arguments under the names its core twin reads."""
|
|
163
|
+
renamed: dict[str, object] = {}
|
|
164
|
+
if "column_list" in kwargs:
|
|
165
|
+
renamed["combination_of_columns"] = kwargs["column_list"]
|
|
166
|
+
if "value_set" in kwargs:
|
|
167
|
+
renamed["values"] = kwargs["value_set"]
|
|
168
|
+
if "quote_values" in kwargs:
|
|
169
|
+
renamed["quote"] = kwargs["quote_values"]
|
|
170
|
+
return renamed
|
|
171
|
+
|
|
172
|
+
|
|
138
173
|
def _attached(test: Test, relations: Mapping[str, Relation]) -> str | None:
|
|
139
174
|
if test.attached_node in relations:
|
|
140
175
|
return test.attached_node
|
|
@@ -274,7 +309,6 @@ def resolve(
|
|
|
274
309
|
|
|
275
310
|
|
|
276
311
|
def _constraints(relation: Relation, manifest: Manifest) -> Iterator[Expectation]:
|
|
277
|
-
enforced = _ENFORCED_CONSTRAINTS.get(manifest.adapter_type or "", _NOT_NULL_ONLY)
|
|
278
312
|
for index, constraint in enumerate(relation.constraints):
|
|
279
313
|
kind: PropertyKind
|
|
280
314
|
match constraint.type:
|
|
@@ -292,8 +326,6 @@ def _constraints(relation: Relation, manifest: Manifest) -> Iterator[Expectation
|
|
|
292
326
|
not_a_fact = "the model's contract is not enforced"
|
|
293
327
|
elif relation.materialized not in _CONSTRAINED_MATERIALIZATIONS:
|
|
294
328
|
not_a_fact = f"constraints are not applied to a {relation.materialized} materialization"
|
|
295
|
-
elif constraint.type not in enforced:
|
|
296
|
-
not_a_fact = f"{manifest.adapter_type} does not enforce {constraint.type} constraints"
|
|
297
329
|
else:
|
|
298
330
|
not_a_fact = None
|
|
299
331
|
base = Expectation(
|
sqlassert_dbt/manifest.py
CHANGED
|
@@ -10,9 +10,10 @@ manifest that is not a JSON object of nodes is a `ManifestError`.
|
|
|
10
10
|
from __future__ import annotations
|
|
11
11
|
|
|
12
12
|
import json
|
|
13
|
+
import re
|
|
13
14
|
from collections.abc import Mapping
|
|
14
|
-
from dataclasses import dataclass, field
|
|
15
|
-
from pathlib import Path
|
|
15
|
+
from dataclasses import dataclass, field, replace
|
|
16
|
+
from pathlib import Path, PurePosixPath
|
|
16
17
|
from typing import Any
|
|
17
18
|
|
|
18
19
|
|
|
@@ -82,6 +83,9 @@ class Relation:
|
|
|
82
83
|
extra_ctes: tuple[InjectedCte, ...] = ()
|
|
83
84
|
source_name: str | None = None
|
|
84
85
|
version: str | None = None
|
|
86
|
+
# A source that reads files (dbt-duckdb `external_location`): the read dbt
|
|
87
|
+
# pasted where a table name goes; `relation_name` is then its stand-in.
|
|
88
|
+
file_read: str | None = None
|
|
85
89
|
|
|
86
90
|
@property
|
|
87
91
|
def label(self) -> str:
|
|
@@ -149,6 +153,7 @@ def load_manifest(path: Path) -> Manifest:
|
|
|
149
153
|
for unique_id, node in _mapping(document.get("sources")).items():
|
|
150
154
|
if isinstance(node, dict):
|
|
151
155
|
relations[unique_id] = _relation(unique_id, node)
|
|
156
|
+
relations = _name_file_reads(relations)
|
|
152
157
|
return Manifest(
|
|
153
158
|
adapter_type=_text(metadata.get("adapter_type")),
|
|
154
159
|
project_name=_text(metadata.get("project_name")),
|
|
@@ -158,6 +163,51 @@ def load_manifest(path: Path) -> Manifest:
|
|
|
158
163
|
)
|
|
159
164
|
|
|
160
165
|
|
|
166
|
+
# What dbt-duckdb pastes for a source with `external_location`: a DuckDB
|
|
167
|
+
# `read_*` table function, or a quoted path DuckDB reads by its extension.
|
|
168
|
+
_FILE_READ = re.compile(r"read_[a-z0-9_]+\s*\(.*\)|'(?:[^']|'')*'", re.IGNORECASE | re.DOTALL)
|
|
169
|
+
_QUOTED = re.compile(r"'((?:[^']|'')*)'")
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _name_file_reads(relations: dict[str, Relation]) -> dict[str, Relation]:
|
|
173
|
+
"""Give each source that reads files a table name, `__file_<file stem>`,
|
|
174
|
+
and write it where dbt pasted the read, so analysis declares and reads it
|
|
175
|
+
like any table. The read is one line, so no line moves."""
|
|
176
|
+
names: dict[str, str] = {} # read -> stand-in
|
|
177
|
+
for unique_id, relation in sorted(relations.items()):
|
|
178
|
+
read = relation.relation_name
|
|
179
|
+
if relation.resource_type != "source" or read is None or not _FILE_READ.fullmatch(read.strip()):
|
|
180
|
+
continue
|
|
181
|
+
if read in names:
|
|
182
|
+
relations[unique_id] = replace(relation, relation_name=names[read], file_read=read)
|
|
183
|
+
continue
|
|
184
|
+
path = _QUOTED.search(read)
|
|
185
|
+
stem = PurePosixPath(path.group(1).replace("''", "'")).name.split(".")[0] if path else ""
|
|
186
|
+
stem = re.sub(r"[^a-z0-9_]+", "_", stem.lower()).strip("_") or re.sub(r"[^a-z0-9_]+", "_", relation.name.lower())
|
|
187
|
+
name, count = f"__file_{stem}", 2
|
|
188
|
+
while name in names.values():
|
|
189
|
+
name, count = f"__file_{stem}_{count}", count + 1
|
|
190
|
+
names[read] = name
|
|
191
|
+
relations[unique_id] = replace(relation, relation_name=name, file_read=read)
|
|
192
|
+
if not names:
|
|
193
|
+
return relations
|
|
194
|
+
ordered = sorted(names, key=len, reverse=True) # A longer read first, should one contain another.
|
|
195
|
+
|
|
196
|
+
def rewrite(sql: str) -> str:
|
|
197
|
+
for read in ordered:
|
|
198
|
+
sql = sql.replace(read, names[read])
|
|
199
|
+
return sql
|
|
200
|
+
|
|
201
|
+
return {
|
|
202
|
+
unique_id: replace(
|
|
203
|
+
relation,
|
|
204
|
+
compiled_code=rewrite(relation.compiled_code) if relation.compiled_code else relation.compiled_code,
|
|
205
|
+
extra_ctes=tuple(replace(cte, sql=rewrite(cte.sql)) for cte in relation.extra_ctes),
|
|
206
|
+
) if relation.compiled_code or relation.extra_ctes else relation
|
|
207
|
+
for unique_id, relation in relations.items()
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
|
|
161
211
|
def _relation(unique_id: str, node: dict) -> Relation:
|
|
162
212
|
config = _mapping(node.get("config"))
|
|
163
213
|
columns = tuple(
|
sqlassert_dbt/program.py
CHANGED
|
@@ -4,16 +4,15 @@ everything those read, parsed and lowered once (`Builder`).
|
|
|
4
4
|
A model whose rows are its query (a view, a table rebuilt each run) is a
|
|
5
5
|
`CREATE VIEW` under its relation name whose body reads the model's SQL as a
|
|
6
6
|
FROM subquery, starting on a line of its own, so each line of the model's SQL
|
|
7
|
-
is one line of the Program
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
contract.
|
|
7
|
+
is one line of the Program. Any other relation (a source, seed, snapshot,
|
|
8
|
+
incremental model) is a table, with a `CREATE TABLE` when its columns are
|
|
9
|
+
known completely. An incremental model's `is_incremental()` branches, and an
|
|
10
|
+
ephemeral model's body, are views of their own under generated names.
|
|
11
|
+
|
|
12
|
+
Nothing here writes a marker: after conversion, each test of a body is bound
|
|
13
|
+
as an Assertion over that body's Output Columns, and each test that is a fact
|
|
14
|
+
as a Property Declaration of its relation, so the Property Markers in the
|
|
15
|
+
Program are the author's alone.
|
|
17
16
|
"""
|
|
18
17
|
|
|
19
18
|
from __future__ import annotations
|
|
@@ -39,15 +38,17 @@ from sqlassert.edits import unified_diff
|
|
|
39
38
|
from sqlassert.rewrites import Rewrite, SuggestType
|
|
40
39
|
from sqlassert.ir.convert import IrConversionResult, IrParser
|
|
41
40
|
from sqlassert.ir.model import LiteralValue
|
|
42
|
-
from sqlassert.
|
|
41
|
+
from sqlassert.ir.names import named_columns
|
|
42
|
+
from sqlassert.check import causes_lines, step_lines
|
|
43
|
+
from sqlassert.provenance import AttachmentSite, Origin
|
|
43
44
|
from sqlassert.properties import (
|
|
44
|
-
EnumeratedDomain,
|
|
45
|
+
EnumeratedDomain, NonNullColumn, NonNullColumns, NonNullUniqueSet, Property, ReferentialCoverage,
|
|
45
46
|
UniqueSet,
|
|
46
47
|
)
|
|
47
48
|
from sqlassert.python_engine import Engine
|
|
48
|
-
from sqlassert.reporting import Outcome, Report
|
|
49
|
+
from sqlassert.reporting import AssertionReport, Outcome, Report
|
|
49
50
|
from sqlassert.rules.domain import _domain
|
|
50
|
-
from sqlassert.rules.
|
|
51
|
+
from sqlassert.rules.value_typing import _binary_text, _comparison_type, _identity_comparison
|
|
51
52
|
from sqlassert.rules.uniqueness import minimal_keys
|
|
52
53
|
from sqlassert.hazards import Hazard
|
|
53
54
|
from sqlassert.sql_parse import ParsedProgram, SqlParser, _marker_shapes
|
|
@@ -56,7 +57,8 @@ from sqlassert.suggest import MAX_ENUM_VALUES, Suggester, Suggestion
|
|
|
56
57
|
# Materializations whose relation holds exactly the rows of the model's query
|
|
57
58
|
# when its children are built. An incremental model's table keeps rows of
|
|
58
59
|
# earlier runs, a snapshot's its history: those are tables, not their query.
|
|
59
|
-
|
|
60
|
+
# dbt-duckdb's `external` writes the query's rows to a file each run, like `table`.
|
|
61
|
+
QUERY_MATERIALIZATIONS = {"view", "table", "materialized_view", "dynamic_table", "external"}
|
|
60
62
|
|
|
61
63
|
# Parse results that leave a relation's SQL unusable as a view body.
|
|
62
64
|
_UNPARSEABLE = {diag.SQL_PARSE_FAILED, diag.MULTIPLE_ROOT_SELECTS, diag.UNSUPPORTED_STATEMENT, diag.UNATTACHED_MARKER}
|
|
@@ -329,9 +331,10 @@ class SuggestResult:
|
|
|
329
331
|
@dataclass(frozen=True)
|
|
330
332
|
class Statement:
|
|
331
333
|
"""One body of a model in the project's Program: a view named `name`
|
|
332
|
-
whose body reads the model's SQL as a FROM subquery
|
|
333
|
-
|
|
334
|
-
|
|
334
|
+
whose body reads the model's SQL as a FROM subquery. `first_line` and
|
|
335
|
+
`first_offset` are where the body starts in the Program. Once the Program
|
|
336
|
+
is converted, each of `tests` is either the Assertion over the body's
|
|
337
|
+
Output Columns that `asserted` maps to it, or `unplaced`, with why."""
|
|
335
338
|
|
|
336
339
|
model: Relation
|
|
337
340
|
body: Body
|
|
@@ -339,8 +342,9 @@ class Statement:
|
|
|
339
342
|
first_line: int
|
|
340
343
|
first_offset: int
|
|
341
344
|
last_line: int
|
|
342
|
-
|
|
343
|
-
|
|
345
|
+
tests: tuple[Expectation, ...]
|
|
346
|
+
asserted: dict[ir.Assertion, Expectation] = field(default_factory=dict)
|
|
347
|
+
unplaced: dict[str, TestResult] = field(default_factory=dict)
|
|
344
348
|
|
|
345
349
|
@property
|
|
346
350
|
def body_lines(self) -> int:
|
|
@@ -359,15 +363,6 @@ class Statement:
|
|
|
359
363
|
return 0 <= site.offset - self.first_offset <= len(self.body.text) and self.local(site.line) is not None
|
|
360
364
|
|
|
361
365
|
|
|
362
|
-
@dataclass(frozen=True)
|
|
363
|
-
class _Text:
|
|
364
|
-
"""A statement's text and where its parts land in it."""
|
|
365
|
-
|
|
366
|
-
text: str
|
|
367
|
-
placed: dict[int, Expectation]
|
|
368
|
-
unplaced: dict[str, TestResult]
|
|
369
|
-
|
|
370
|
-
|
|
371
366
|
def _previous(relation_name: str, dialect: str) -> str:
|
|
372
367
|
"""How an incremental model's batch reads its own table (`{{ this }}`):
|
|
373
368
|
a table of its own with unknown columns, never the model's table, whose
|
|
@@ -434,8 +429,8 @@ class Builder:
|
|
|
434
429
|
Every model a run analyzes, and every relation those read, enters one
|
|
435
430
|
Program, parsed and lowered once: a model whose rows are its query (a
|
|
436
431
|
view, a table rebuilt each run) as a view of its SQL, under its relation
|
|
437
|
-
name, with its tests as
|
|
438
|
-
with its columns when they are known completely. An incremental model is
|
|
432
|
+
name, with its tests bound as Assertions on it; any other relation as a
|
|
433
|
+
table, with its columns when they are known completely. An incremental model is
|
|
439
434
|
a table to what reads it, and each of its `is_incremental()` branches a
|
|
440
435
|
view of its own; so is an ephemeral model's body, which its readers have
|
|
441
436
|
inlined. The passing tests and constraints that are facts become
|
|
@@ -471,6 +466,8 @@ class Builder:
|
|
|
471
466
|
_ast: ParsedProgram | None = None
|
|
472
467
|
_conversion: IrConversionResult | None = None
|
|
473
468
|
_report: Report | None = None
|
|
469
|
+
# Each Assertion's report, once checked: the tests' are found by their Assertion.
|
|
470
|
+
_outcomes: dict[ir.Assertion, AssertionReport] = field(default_factory=dict)
|
|
474
471
|
_read: set[str] = field(default_factory=set)
|
|
475
472
|
|
|
476
473
|
def branches(self, model: Relation) -> Branches:
|
|
@@ -527,8 +524,7 @@ class Builder:
|
|
|
527
524
|
# A body whose SQL alone does not parse stays out of the Program.
|
|
528
525
|
for node, found in list(bodies.items()):
|
|
529
526
|
for body, name in found:
|
|
530
|
-
|
|
531
|
-
parsed = SqlParser(self.dialect).parse(text.text)
|
|
527
|
+
parsed = SqlParser(self.dialect).parse(self._text(self.relations[node], body, name))
|
|
532
528
|
if parsed.root_select is not None or len(parsed.create_statements) != 1 or any(
|
|
533
529
|
d.code in _UNPARSEABLE for d in parsed.diagnostics
|
|
534
530
|
):
|
|
@@ -578,21 +574,11 @@ class Builder:
|
|
|
578
574
|
def _holding(self, line: int) -> Statement | None:
|
|
579
575
|
return next((statement for statement in self._all() if statement.holds(line)), None)
|
|
580
576
|
|
|
581
|
-
def _text(self, model: Relation, body: Body, name: str
|
|
582
|
-
"""A body's statement
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
first = 2 + body.text.count("\n") + 1 # The `) as` line.
|
|
587
|
-
for expectation in tests:
|
|
588
|
-
marker = self._marker(expectation)
|
|
589
|
-
if marker is None:
|
|
590
|
-
unplaced[expectation.unique_id] = TestResult(False, "it references a relation with no name in the warehouse")
|
|
591
|
-
continue
|
|
592
|
-
lines.append(marker)
|
|
593
|
-
placed[first + len(placed) + 1] = expectation
|
|
594
|
-
lines.append(";")
|
|
595
|
-
return _Text("\n".join(lines), placed, unplaced)
|
|
577
|
+
def _text(self, model: Relation, body: Body, name: str) -> str:
|
|
578
|
+
"""A body's statement; the body starts on its second line."""
|
|
579
|
+
return "\n".join((
|
|
580
|
+
f"create view {name} as select * from (", body.text, f") as {_identifier(model.name, self.dialect)};",
|
|
581
|
+
))
|
|
596
582
|
|
|
597
583
|
def _assemble(self, reached: Mapping[str, Relation], bodies: Mapping[str, list[tuple[Body, str]]], tests: Mapping[str, list[Expectation]]) -> None:
|
|
598
584
|
parts: list[str] = []
|
|
@@ -614,32 +600,106 @@ class Builder:
|
|
|
614
600
|
for node, found in bodies.items():
|
|
615
601
|
model = self.relations[node]
|
|
616
602
|
for body, name in found:
|
|
617
|
-
text = self._text(model, body, name
|
|
603
|
+
text = self._text(model, body, name)
|
|
618
604
|
self._statements.setdefault(node, []).append(Statement(
|
|
619
|
-
model, body, name, line + 1, offset + text.
|
|
620
|
-
line + text.text.count("\n"), {line - 1 + local: e for local, e in text.placed.items()}, text.unplaced,
|
|
605
|
+
model, body, name, line + 1, offset + text.index("\n") + 1, line + text.count("\n"), tuple(tests.get(node, ())),
|
|
621
606
|
))
|
|
622
|
-
parts.append(text
|
|
623
|
-
line += text.
|
|
624
|
-
offset += len(text
|
|
607
|
+
parts.append(text)
|
|
608
|
+
line += text.count("\n") + 1
|
|
609
|
+
offset += len(text) + 1
|
|
625
610
|
self._sql = "\n".join(parts) + "\n"
|
|
626
611
|
self._ast = SqlParser(self.dialect).parse(self._sql)
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
612
|
+
# Each relation a relationships test references, reached with the
|
|
613
|
+
# columns it names, as a reference in the SQL would reach it.
|
|
614
|
+
required = tuple(dict.fromkeys(
|
|
615
|
+
(_qualified(target.relation_name, self.dialect), e.referenced_columns)
|
|
616
|
+
for statement in self._all() for e in statement.tests
|
|
617
|
+
if e.asserted == "coverage" and (target := self._referenced(e)) is not None and target.relation_name is not None
|
|
618
|
+
))
|
|
619
|
+
conversion = (
|
|
620
|
+
IrParser(self.dialect, required_relations=required).parse(self._ast) if self.fetcher is None
|
|
621
|
+
else self._hydrated(self._ast, required)
|
|
633
622
|
)
|
|
623
|
+
program = conversion.program
|
|
624
|
+
named = _named(program)
|
|
625
|
+
self._statements = {node: [self._bind(statement, named) for statement in found] for node, found in self._statements.items()}
|
|
626
|
+
assertions = (*program.assertions, *(assertion for statement in self._all() for assertion in statement.asserted))
|
|
634
627
|
declarations = (*program.declarations, *self._declarations(program, conversion.knowledge, reached))
|
|
635
628
|
self._conversion = replace(conversion, program=replace(program, assertions=assertions, declarations=declarations))
|
|
636
629
|
|
|
637
|
-
def
|
|
630
|
+
def _referenced(self, expectation: Expectation) -> Relation | None:
|
|
631
|
+
return self.relations.get(expectation.referenced or "")
|
|
632
|
+
|
|
633
|
+
def _bind(self, statement: Statement, named: Mapping[str, ir.NamedRelation]) -> Statement:
|
|
634
|
+
"""`statement` with each of its tests an Assertion over its body's
|
|
635
|
+
Output Columns, or unplaced with why it is none."""
|
|
636
|
+
view = named.get(_canonical(statement.name, self.dialect))
|
|
637
|
+
root = view.body if view is not None else None
|
|
638
|
+
asserted: dict[ir.Assertion, Expectation] = {}
|
|
639
|
+
unplaced: dict[str, TestResult] = {}
|
|
640
|
+
for expectation in statement.tests:
|
|
641
|
+
property = self._tested(expectation, root, named)
|
|
642
|
+
if isinstance(property, str):
|
|
643
|
+
unplaced[expectation.unique_id] = TestResult(False, property)
|
|
644
|
+
continue
|
|
645
|
+
origin = Origin(_TEST_ORIGIN, f"{expectation.kind} {expectation.name}")
|
|
646
|
+
asserted[ir.Assertion(origin=origin, property=property)] = expectation
|
|
647
|
+
return replace(statement, asserted=asserted, unplaced=unplaced)
|
|
648
|
+
|
|
649
|
+
def _tested(
|
|
650
|
+
self, expectation: Expectation, root: ir.RelationExpr | None, named: Mapping[str, ir.NamedRelation],
|
|
651
|
+
) -> Property | str:
|
|
652
|
+
"""The Property a proof of `expectation` over `root` proves, or why
|
|
653
|
+
there is none. A column is named as a marker names it."""
|
|
654
|
+
target = self._referenced(expectation)
|
|
655
|
+
if expectation.asserted == "coverage" and (target is None or target.relation_name is None):
|
|
656
|
+
return "it references a relation with no name in the warehouse"
|
|
657
|
+
if root is None:
|
|
658
|
+
return "it was not analyzed"
|
|
659
|
+
columns, ambiguous, unknown = _resolved(root, expectation.columns)
|
|
660
|
+
if ambiguous:
|
|
661
|
+
return f"{diag.UNRESOLVED_ASSERTED_COLUMN}: output names {diag.quoted_all(ambiguous)} are ambiguous; use distinct aliases"
|
|
662
|
+
if unknown and root.is_schema_complete:
|
|
663
|
+
return f"{diag.UNKNOWN_ASSERTED_COLUMN}: it names {diag.quoted_all(unknown)}, which is not among the model's output columns"
|
|
664
|
+
if unknown:
|
|
665
|
+
# The column may exist in a source whose columns are unknown.
|
|
666
|
+
return (
|
|
667
|
+
f"{diag.UNRESOLVED_ASSERTED_COLUMN}: it names {diag.quoted_all(unknown)}, which cannot be resolved: "
|
|
668
|
+
"the model reads a relation whose columns are unknown"
|
|
669
|
+
)
|
|
670
|
+
match expectation.asserted:
|
|
671
|
+
case "unique":
|
|
672
|
+
return UniqueSet(columns=frozenset(columns))
|
|
673
|
+
case "key":
|
|
674
|
+
return NonNullUniqueSet(columns=frozenset(columns))
|
|
675
|
+
case "not_null":
|
|
676
|
+
return NonNullColumns(columns=frozenset(columns))
|
|
677
|
+
case "enum":
|
|
678
|
+
return EnumeratedDomain(column=columns[0], values=frozenset(expectation.values))
|
|
679
|
+
case "coverage":
|
|
680
|
+
# Coverage only: a relationships test never checks the
|
|
681
|
+
# referenced Unique Set a Foreign Key also requires.
|
|
682
|
+
assert target is not None and target.relation_name is not None
|
|
683
|
+
relation = named.get(_canonical(target.relation_name, self.dialect))
|
|
684
|
+
if relation is None:
|
|
685
|
+
return f"it references {target.relation_name}, which the Program does not reach"
|
|
686
|
+
referenced, ambiguous, unknown = _resolved(relation, expectation.referenced_columns)
|
|
687
|
+
if ambiguous or unknown:
|
|
688
|
+
return (
|
|
689
|
+
f"{diag.UNKNOWN_REFERENCED_COLUMN}: it references {relation.name}"
|
|
690
|
+
f"({diag.quoted_all(expectation.referenced_columns)}), but {relation.name} has no column "
|
|
691
|
+
f"{diag.quoted_all(ambiguous or unknown)}"
|
|
692
|
+
)
|
|
693
|
+
return ReferentialCoverage(columns=columns, referenced_columns=referenced)
|
|
694
|
+
case None:
|
|
695
|
+
raise AssertionError("a test with no asserted Property is not bound")
|
|
696
|
+
|
|
697
|
+
def _hydrated(self, ast: ParsedProgram, required: tuple[tuple[str, tuple[str, ...]], ...]) -> IrConversionResult:
|
|
638
698
|
"""The Program with every table it reads declared from the warehouse
|
|
639
699
|
and its keys, NOT NULLs and foreign keys bound, as `analyze_database`
|
|
640
700
|
does (`DatabaseKnowledgeFetcher.convert`)."""
|
|
641
701
|
assert self.fetcher is not None
|
|
642
|
-
conversion, hydration = self.fetcher.convert(ast, dialect=self.dialect)
|
|
702
|
+
conversion, hydration = self.fetcher.convert(ast, dialect=self.dialect, required_relations=required)
|
|
643
703
|
# A table by its columns, a view by its stored query.
|
|
644
704
|
declared = set(hydration.tables) | {
|
|
645
705
|
relation.name.lower() for relation in conversion.program.named_relations if relation.role is ir.RelationRole.VIEW
|
|
@@ -668,7 +728,7 @@ class Builder:
|
|
|
668
728
|
*((d, False) for d in (*self._ast.diagnostics, *self._conversion.diagnostics)),
|
|
669
729
|
*((d, True) for d in self._conversion.warnings),
|
|
670
730
|
]:
|
|
671
|
-
if _about(diagnostic, names):
|
|
731
|
+
if _about(diagnostic, names) or _of_test(diagnostic):
|
|
672
732
|
continue
|
|
673
733
|
line = _line(diagnostic)
|
|
674
734
|
if line is None or self._holding(line) is None:
|
|
@@ -703,6 +763,7 @@ class Builder:
|
|
|
703
763
|
self._report = Engine().run(
|
|
704
764
|
conversion.program, conversion.knowledge, self._ast.diagnostics + conversion.diagnostics, conversion.warnings,
|
|
705
765
|
)
|
|
766
|
+
self._outcomes = dict(zip(conversion.program.assertions, self._report.assertions, strict=True))
|
|
706
767
|
|
|
707
768
|
def analyze(self, model: Relation) -> list[tuple[Body, BranchResult]]:
|
|
708
769
|
"""Each of `model`'s bodies and what checking it found. `check` first."""
|
|
@@ -713,13 +774,20 @@ class Builder:
|
|
|
713
774
|
found = []
|
|
714
775
|
for statement in self._statements.get(model.unique_id, []):
|
|
715
776
|
found.append((statement.body, BranchResult(
|
|
716
|
-
tests={**statement.unplaced, **_tests(
|
|
777
|
+
tests={**statement.unplaced, **self._tests(statement)},
|
|
717
778
|
markers=_markers(report, statement),
|
|
718
779
|
problems=_problems(report.diagnostics, report.warnings, statement, self._names()),
|
|
719
780
|
additions=self._additions(statement),
|
|
720
781
|
)))
|
|
721
782
|
return found
|
|
722
783
|
|
|
784
|
+
def _tests(self, statement: Statement) -> dict[str, TestResult]:
|
|
785
|
+
results: dict[str, TestResult] = {}
|
|
786
|
+
for assertion, expectation in statement.asserted.items():
|
|
787
|
+
outcome = self._outcomes[assertion]
|
|
788
|
+
results[expectation.unique_id] = TestResult(outcome.outcome is Outcome.PROVED, _explained(outcome, None))
|
|
789
|
+
return results
|
|
790
|
+
|
|
723
791
|
def suggester(self, models: Iterable[Relation]) -> Suggester:
|
|
724
792
|
"""A Suggester over the Program, for the bodies of `models` only."""
|
|
725
793
|
assert self._conversion is not None and self._ast is not None
|
|
@@ -787,26 +855,6 @@ class Builder:
|
|
|
787
855
|
))
|
|
788
856
|
return results
|
|
789
857
|
|
|
790
|
-
def _marker(self, expectation: Expectation) -> str | None:
|
|
791
|
-
columns = ", ".join(_identifier(column, self.dialect) for column in expectation.columns)
|
|
792
|
-
match expectation.asserted:
|
|
793
|
-
case "unique":
|
|
794
|
-
return f"/**ASSERT UNIQUE({columns})**/"
|
|
795
|
-
case "key":
|
|
796
|
-
return f"/**ASSERT NOT NULL UNIQUE({columns})**/"
|
|
797
|
-
case "not_null":
|
|
798
|
-
return f"/**ASSERT NOT NULL({columns})**/"
|
|
799
|
-
case "enum":
|
|
800
|
-
return f"/**ASSERT ENUM({columns} IN ({', '.join(value.sql() for value in expectation.values)}))**/"
|
|
801
|
-
case "coverage":
|
|
802
|
-
target = self.relations.get(expectation.referenced or "")
|
|
803
|
-
if target is None or target.relation_name is None:
|
|
804
|
-
return None
|
|
805
|
-
referenced = ", ".join(_identifier(column, self.dialect) for column in expectation.referenced_columns)
|
|
806
|
-
return f"/**ASSERT FOREIGN KEY({columns}) REFERENCES {target.relation_name}({referenced})**/"
|
|
807
|
-
case None:
|
|
808
|
-
return None
|
|
809
|
-
|
|
810
858
|
def _complete_columns(self, relation: Relation) -> list[str] | None:
|
|
811
859
|
"""Column definitions known to be all of a table's columns: an enforced
|
|
812
860
|
contract's, typed, else the catalog's, typed where SQLGlot reads the
|
|
@@ -843,10 +891,7 @@ class Builder:
|
|
|
843
891
|
|
|
844
892
|
def _declarations(self, program: ir.Program, knowledge: tuple[Property, ...], reached: Mapping[str, Relation]) -> list[Property]:
|
|
845
893
|
"""The fact tests and constraints of every relation, as Properties of its IR."""
|
|
846
|
-
named =
|
|
847
|
-
relation.name.lower(): relation for relation in program.named_relations
|
|
848
|
-
if relation.role in {ir.RelationRole.TABLE, ir.RelationRole.VIEW}
|
|
849
|
-
}
|
|
894
|
+
named = _named(program)
|
|
850
895
|
ctes: dict[str, list[ir.NamedRelation]] = {}
|
|
851
896
|
for relation in program.named_relations:
|
|
852
897
|
if relation.role is ir.RelationRole.CTE:
|
|
@@ -900,10 +945,7 @@ class Builder:
|
|
|
900
945
|
"""Unique Sets, Not Null columns and Enumerated Domains proved of a body."""
|
|
901
946
|
assert self._conversion is not None
|
|
902
947
|
program, knowledge = self._conversion.program, self._conversion.knowledge
|
|
903
|
-
view =
|
|
904
|
-
(relation for relation in program.named_relations if relation.name.lower() == _canonical(statement.name, self.dialect)),
|
|
905
|
-
None,
|
|
906
|
-
)
|
|
948
|
+
view = _named(program).get(_canonical(statement.name, self.dialect))
|
|
907
949
|
root = view.body if view is not None else None
|
|
908
950
|
if root is None:
|
|
909
951
|
return ()
|
|
@@ -941,10 +983,20 @@ def _synthetic(model: Relation, index: int, dialect: str) -> str:
|
|
|
941
983
|
return exp.to_identifier(f"{stem}__sqlassert_body_{index + 1}", quoted=True).sql(dialect=dialect)
|
|
942
984
|
|
|
943
985
|
|
|
986
|
+
# The Origin kind of a test's Assertion: it names the test, at no line of the Program.
|
|
987
|
+
_TEST_ORIGIN = "dbt-test"
|
|
988
|
+
|
|
989
|
+
|
|
944
990
|
def _line(diagnostic: Diagnostic) -> int | None:
|
|
945
991
|
return diagnostic.origin.line if diagnostic.origin is not None else None
|
|
946
992
|
|
|
947
993
|
|
|
994
|
+
def _of_test(diagnostic: Diagnostic) -> bool:
|
|
995
|
+
"""Whether `diagnostic` is about a test's Assertion (a Property holding
|
|
996
|
+
trivially, a construct it reaches): the test's result says what matters."""
|
|
997
|
+
return diagnostic.origin is not None and diagnostic.origin.kind == _TEST_ORIGIN
|
|
998
|
+
|
|
999
|
+
|
|
948
1000
|
def _about(diagnostic: Diagnostic, names: set[str]) -> bool:
|
|
949
1001
|
"""Whether `diagnostic` is a table with unknown columns among `names`,
|
|
950
1002
|
reported once for the project instead (or unknown by nature)."""
|
|
@@ -967,12 +1019,29 @@ def _markers(report: Report, statement: Statement) -> tuple[MarkerResult, ...]:
|
|
|
967
1019
|
on_line = [m.start() for m in _marker_shapes(body.text) if start <= m.start() < end]
|
|
968
1020
|
found.append(MarkerResult(
|
|
969
1021
|
line, raw_line_of(body, line, offset), on_line.index(offset) if offset in on_line else 0,
|
|
970
|
-
_marker_at(body, offset), assertion.outcome,
|
|
971
|
-
assertion.evidence.explain() if assertion.evidence is not None else "",
|
|
1022
|
+
_marker_at(body, offset), assertion.outcome, _explained(assertion, statement),
|
|
972
1023
|
))
|
|
973
1024
|
return tuple(found)
|
|
974
1025
|
|
|
975
1026
|
|
|
1027
|
+
def _explained(assertion: AssertionReport, statement: Statement | None) -> str:
|
|
1028
|
+
"""An assertion's Causes, then the walk to them; its Evidence when it has
|
|
1029
|
+
no Cause (a PROVED one). A Cause in `statement` is placed by the model
|
|
1030
|
+
file's line it was rendered from; one elsewhere is named only."""
|
|
1031
|
+
explanation = assertion.explanation
|
|
1032
|
+
if explanation is None:
|
|
1033
|
+
return assertion.evidence.explain() if assertion.evidence is not None else ""
|
|
1034
|
+
|
|
1035
|
+
def place(origin: Origin) -> str | None:
|
|
1036
|
+
# The model file's line: rendering may move columns, so none is given.
|
|
1037
|
+
if statement is None or origin.span is None or (local := statement.local(origin.span.line)) is None:
|
|
1038
|
+
return None
|
|
1039
|
+
raw = raw_line_of(statement.body, local, _line_start(statement.body, local) + origin.span.column - 1)
|
|
1040
|
+
return f"line {raw}" if raw is not None else None
|
|
1041
|
+
|
|
1042
|
+
return "\n".join((*causes_lines(explanation.causes(), place), *step_lines(explanation, place)))
|
|
1043
|
+
|
|
1044
|
+
|
|
976
1045
|
def _problems(
|
|
977
1046
|
diagnostics: Iterable[Diagnostic], warnings: Iterable[Diagnostic], statement: Statement, names: set[str],
|
|
978
1047
|
) -> tuple[Problem, ...]:
|
|
@@ -982,7 +1051,7 @@ def _problems(
|
|
|
982
1051
|
found = []
|
|
983
1052
|
for diagnostic, warning in [*((d, False) for d in diagnostics), *((d, True) for d in warnings)]:
|
|
984
1053
|
line = _line(diagnostic)
|
|
985
|
-
if line is None or not statement.holds(line) or
|
|
1054
|
+
if line is None or not statement.holds(line) or _about(diagnostic, names):
|
|
986
1055
|
continue
|
|
987
1056
|
local = statement.local(line)
|
|
988
1057
|
if local is not None and body.in_injected(_line_offset(body, local)):
|
|
@@ -995,15 +1064,26 @@ def _identifier(name: str, dialect: str) -> str:
|
|
|
995
1064
|
return exp.to_identifier(name).sql(dialect=dialect)
|
|
996
1065
|
|
|
997
1066
|
|
|
998
|
-
def
|
|
999
|
-
"""
|
|
1000
|
-
if relation_name is None:
|
|
1001
|
-
return ""
|
|
1067
|
+
def _qualified(relation_name: str, dialect: str) -> str:
|
|
1068
|
+
"""`relation_name` as SQL's dotted name of it, unquoted."""
|
|
1002
1069
|
try:
|
|
1003
1070
|
table = exp.to_table(relation_name, dialect=dialect)
|
|
1004
1071
|
except SqlglotError:
|
|
1005
|
-
return relation_name
|
|
1006
|
-
return ".".join(part for part in (table.catalog, table.db, table.name) if part)
|
|
1072
|
+
return relation_name
|
|
1073
|
+
return ".".join(part for part in (table.catalog, table.db, table.name) if part)
|
|
1074
|
+
|
|
1075
|
+
|
|
1076
|
+
def _canonical(relation_name: str | None, dialect: str) -> str:
|
|
1077
|
+
"""How the IR names a relation written as `relation_name`, lowercase."""
|
|
1078
|
+
return "" if relation_name is None else _qualified(relation_name, dialect).lower()
|
|
1079
|
+
|
|
1080
|
+
|
|
1081
|
+
def _named(program: ir.Program) -> dict[str, ir.NamedRelation]:
|
|
1082
|
+
"""The Program's tables and views, by lowercase name."""
|
|
1083
|
+
return {
|
|
1084
|
+
relation.name.lower(): relation for relation in program.named_relations
|
|
1085
|
+
if relation.role in {ir.RelationRole.TABLE, ir.RelationRole.VIEW}
|
|
1086
|
+
}
|
|
1007
1087
|
|
|
1008
1088
|
|
|
1009
1089
|
def _columns(relation: ir.NamedRelation, names: tuple[str, ...]) -> tuple[ir.OutputColumn, ...] | None:
|
|
@@ -1016,30 +1096,12 @@ def _columns(relation: ir.NamedRelation, names: tuple[str, ...]) -> tuple[ir.Out
|
|
|
1016
1096
|
return tuple(found)
|
|
1017
1097
|
|
|
1018
1098
|
|
|
1019
|
-
def
|
|
1020
|
-
"""
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
return ir.Assertion(origin=assertion.origin, property=coverage)
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
def _tests(report: Report, tested: Mapping[int, Expectation]) -> dict[str, TestResult]:
|
|
1029
|
-
results: dict[str, TestResult] = {}
|
|
1030
|
-
for assertion in report.assertions:
|
|
1031
|
-
expectation = tested.get(assertion.origin.line or 0)
|
|
1032
|
-
if expectation is not None:
|
|
1033
|
-
explanation = assertion.evidence.explain() if assertion.evidence is not None else ""
|
|
1034
|
-
results[expectation.unique_id] = TestResult(assertion.outcome is Outcome.PROVED, explanation)
|
|
1035
|
-
for diagnostic in (*report.diagnostics, *report.warnings):
|
|
1036
|
-
line = diagnostic.origin.line if diagnostic.origin is not None else None
|
|
1037
|
-
expectation = tested.get(line or 0)
|
|
1038
|
-
if expectation is not None and expectation.unique_id not in results:
|
|
1039
|
-
results[expectation.unique_id] = TestResult(False, f"{diagnostic.code}: {diagnostic.message}")
|
|
1040
|
-
for line, expectation in tested.items():
|
|
1041
|
-
results.setdefault(expectation.unique_id, TestResult(False, "it was not analyzed"))
|
|
1042
|
-
return results
|
|
1099
|
+
def _resolved(relation: ir.RelationExpr, names: Iterable[str]) -> tuple[tuple[ir.OutputColumn, ...], list[str], list[str]]:
|
|
1100
|
+
"""The columns of `relation` that `names` name, as a marker names them
|
|
1101
|
+
(`named_columns`); the names that are ambiguous, and those that name no column."""
|
|
1102
|
+
names = tuple(names)
|
|
1103
|
+
found, ambiguous, unknown = named_columns(relation.output_columns, names)
|
|
1104
|
+
return tuple(found[name.lower()] for name in names if name.lower() in found), ambiguous, unknown
|
|
1043
1105
|
|
|
1044
1106
|
|
|
1045
1107
|
def _holds_its_literals(column: ir.OutputColumn, values: Iterable[LiteralValue], dialect: str) -> bool:
|
sqlassert_dbt/project.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""Analyze a dbt project from its `target/manifest.json
|
|
1
|
+
"""Analyze a dbt project from its `target/manifest.json`.
|
|
2
2
|
|
|
3
3
|
The project is one Program (`program.py`), built once per run: each model's
|
|
4
4
|
tests are Assertions, the passing tests of what it reads are Property
|
|
@@ -255,6 +255,11 @@ class _Analysis:
|
|
|
255
255
|
f"an enforced model contract listing every column's data_type declares them, or {catalog}"
|
|
256
256
|
if relation.resource_type == "model" else catalog
|
|
257
257
|
)
|
|
258
|
+
if relation.file_read is not None:
|
|
259
|
+
supply = (
|
|
260
|
+
f"it reads files, {relation.file_read}, which `dbt docs generate` does not list: "
|
|
261
|
+
"add a catalog.json entry for its unique_id with every column and type"
|
|
262
|
+
)
|
|
258
263
|
problems.append(Problem(
|
|
259
264
|
UNKNOWN_COLUMNS,
|
|
260
265
|
f"the columns of {relation.resource_type} {relation.label} are not all known from the manifest, so its keys "
|
|
@@ -454,7 +459,8 @@ def _catalog_columns(
|
|
|
454
459
|
relation = manifest.relations.get(unique_id)
|
|
455
460
|
if relation is None:
|
|
456
461
|
continue
|
|
457
|
-
|
|
462
|
+
# A source that reads files has no warehouse name to compare; its entry is its unique_id's.
|
|
463
|
+
if relation.file_read is None and _canonical(relation.relation_name, dialect) != _name_of(table).lower():
|
|
458
464
|
other.append(f"{relation.resource_type} {relation.label} is {_name_of(table)} there, {relation.relation_name} here")
|
|
459
465
|
continue
|
|
460
466
|
listed = [column.name.lower() for column in table.columns]
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: sqlassert-dbt
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.2
|
|
4
4
|
Summary: Check a dbt project's tests and sqlassert markers from its compiled manifest.
|
|
5
5
|
Author: Fred Israel
|
|
6
6
|
License-Expression: MIT
|
|
@@ -14,10 +14,10 @@ Classifier: Topic :: Software Development :: Quality Assurance
|
|
|
14
14
|
Requires-Python: >=3.13
|
|
15
15
|
Description-Content-Type: text/markdown
|
|
16
16
|
License-File: LICENSE
|
|
17
|
+
Requires-Dist: dbt-core>=1.12
|
|
17
18
|
Requires-Dist: sqlassert>=0.3.1
|
|
18
19
|
Requires-Dist: sqlglot<31,>=30.30
|
|
19
20
|
Provides-Extra: test
|
|
20
|
-
Requires-Dist: dbt-core>=1.12; extra == "test"
|
|
21
21
|
Requires-Dist: dbt-duckdb>=1.11; extra == "test"
|
|
22
22
|
Requires-Dist: duckdb; extra == "test"
|
|
23
23
|
Requires-Dist: pytest; extra == "test"
|
|
@@ -64,10 +64,9 @@ A `profiles.yml` kept in the project directory is found without
|
|
|
64
64
|
`--profiles-dir` (by `build`, `test` and `suggest`), unless the working
|
|
65
65
|
directory has one or `DBT_PROFILES_DIR` is set.
|
|
66
66
|
|
|
67
|
-
## Check
|
|
67
|
+
## Check
|
|
68
68
|
|
|
69
|
-
`check` reads
|
|
70
|
-
where it runs (a CI step after `dbt compile`, say):
|
|
69
|
+
`check` reads `target/manifest.json`, so run it after `dbt compile`:
|
|
71
70
|
|
|
72
71
|
```bash
|
|
73
72
|
$ dbt compile
|
|
@@ -122,7 +121,7 @@ manifest cannot be read.
|
|
|
122
121
|
A model's own tests are what gets proved. Upstream tests are evidence, used
|
|
123
122
|
only when they fail on any failing row: not a test with `severity: warn`, a
|
|
124
123
|
`where:` config, or `error_if`/`fail_calc` thresholds. A constraint counts only
|
|
125
|
-
on a
|
|
124
|
+
on a table with an enforced contract, whether or not the adapter checks it.
|
|
126
125
|
|
|
127
126
|
## Suggest from the models you're editing
|
|
128
127
|
|
|
@@ -217,8 +216,7 @@ read then. An enforced contract's table is still declared from the contract,
|
|
|
217
216
|
since the build may not have made it yet; every other table comes from the
|
|
218
217
|
warehouse.
|
|
219
218
|
As with `analyze_database`, a connection only adds proofs. A key the
|
|
220
|
-
warehouse does not enforce is trusted
|
|
221
|
-
own are.
|
|
219
|
+
warehouse does not enforce is trusted, as the SQL's own are.
|
|
222
220
|
|
|
223
221
|
```bash
|
|
224
222
|
$ sqlassert-dbt build --connect .
|
|
@@ -238,7 +236,7 @@ report = analyze_project(project, fetcher=DuckDBKnowledgeFetcher(duckdb.connect(
|
|
|
238
236
|
```
|
|
239
237
|
|
|
240
238
|
`suggest_models(..., fetcher=...)` takes one too. `check` stays
|
|
241
|
-
connectionless
|
|
239
|
+
connectionless.
|
|
242
240
|
|
|
243
241
|
## Details
|
|
244
242
|
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
sqlassert_dbt/__init__.py,sha256=A21obXKXpKdrUMqCuzN7IgJYjpVVsVa_1MoTMIfjAfM,1242
|
|
2
|
+
sqlassert_dbt/__main__.py,sha256=jnPtWYRElxavsoMGZ0R0N06TnO1awo3SvlpGR2_FIPY,16869
|
|
3
|
+
sqlassert_dbt/connect.py,sha256=nDwEfXqsYy8juctv5f1lLqc72anyIutZxGxf231uggg,5584
|
|
4
|
+
sqlassert_dbt/expectations.py,sha256=LgnH6xp-CoginIrMNXVF-JDKk6h4vgqnX2HLwHVdBoU,17176
|
|
5
|
+
sqlassert_dbt/jinja.py,sha256=uT-XJv54yhWie-Oi8jN8WpTFpE97N8KvSL-tGjYgi0w,12238
|
|
6
|
+
sqlassert_dbt/manifest.py,sha256=gEw-CrzotOpivVfJMJmUbWX80QfKQRwKu0kDLoFnG5w,14316
|
|
7
|
+
sqlassert_dbt/program.py,sha256=S8lOCbHmPdcJTLkAlolHecj5ZLkvJ8WLrVQeungkoAI,59555
|
|
8
|
+
sqlassert_dbt/project.py,sha256=8DHCCXxy26pxMQDp5JGVHJpDQoTS_aQJQZl7PD4gKpY,32772
|
|
9
|
+
sqlassert_dbt/report.py,sha256=q4z789ZDlulIonPAEJVh5TpU0uC-fdVY5tYb0CZE2Bs,10359
|
|
10
|
+
sqlassert_dbt-0.4.2.dist-info/licenses/LICENSE,sha256=KCR0_j-gr5ufUNxamIKNzeyyiI6g-S69oecRjZ07l_A,1068
|
|
11
|
+
sqlassert_dbt-0.4.2.dist-info/METADATA,sha256=VntgYjtpEt9dhXPyIFI2Rob4BNgyT4jFrnB4LUFfY4s,11443
|
|
12
|
+
sqlassert_dbt-0.4.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
13
|
+
sqlassert_dbt-0.4.2.dist-info/entry_points.txt,sha256=4J9EK9q9ozlR8A8fJj7oPJmYtvl5HzM0oXX49HDB_vk,62
|
|
14
|
+
sqlassert_dbt-0.4.2.dist-info/top_level.txt,sha256=w2-3Vq1UafNmPEBbCwdq4aZ-hsvRaBwKvouODJDNc1M,14
|
|
15
|
+
sqlassert_dbt-0.4.2.dist-info/RECORD,,
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
sqlassert_dbt/__init__.py,sha256=28jsIwXiNt_my5AQMGNQtsRC9tZs-4zmN_Tjum14bQ0,1255
|
|
2
|
-
sqlassert_dbt/__main__.py,sha256=Hh3rTq-RLTdAqcLdWUZ416FG9nvE8c2hqVTwPVUBXnk,16882
|
|
3
|
-
sqlassert_dbt/connect.py,sha256=7y2fIXFa1ICJDqTEMnuIauGpyrf9oztZVZurJw0WSUw,5753
|
|
4
|
-
sqlassert_dbt/expectations.py,sha256=6mubjTwnwpPDBl1P5V2ImB7FwpFKK0grL6oHp7eOoWg,15480
|
|
5
|
-
sqlassert_dbt/jinja.py,sha256=uT-XJv54yhWie-Oi8jN8WpTFpE97N8KvSL-tGjYgi0w,12238
|
|
6
|
-
sqlassert_dbt/manifest.py,sha256=OCtVeOv2HW6L9Pwi_6ma4T9GJjlwDLq3nWmkkte19N4,11856
|
|
7
|
-
sqlassert_dbt/program.py,sha256=-7aeODHTOYDBSRhUAgshB4gTJEBq-u-HLnoUH94SC7g,55475
|
|
8
|
-
sqlassert_dbt/project.py,sha256=fCxWSsbL4cZV4OZs4Tt6YtnOtZpU8WLeYx1t9kcpP-Y,32367
|
|
9
|
-
sqlassert_dbt/report.py,sha256=q4z789ZDlulIonPAEJVh5TpU0uC-fdVY5tYb0CZE2Bs,10359
|
|
10
|
-
sqlassert_dbt-0.3.3.dist-info/licenses/LICENSE,sha256=KCR0_j-gr5ufUNxamIKNzeyyiI6g-S69oecRjZ07l_A,1068
|
|
11
|
-
sqlassert_dbt-0.3.3.dist-info/METADATA,sha256=OJW1jT0GoKuqGxOpZinfHd1aGUNAPEDTAh8qIMvdm1g,11570
|
|
12
|
-
sqlassert_dbt-0.3.3.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
13
|
-
sqlassert_dbt-0.3.3.dist-info/entry_points.txt,sha256=4J9EK9q9ozlR8A8fJj7oPJmYtvl5HzM0oXX49HDB_vk,62
|
|
14
|
-
sqlassert_dbt-0.3.3.dist-info/top_level.txt,sha256=w2-3Vq1UafNmPEBbCwdq4aZ-hsvRaBwKvouODJDNc1M,14
|
|
15
|
-
sqlassert_dbt-0.3.3.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|