sqlassert-dbt 0.3.3__tar.gz → 0.4.1__tar.gz

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 (44) hide show
  1. {sqlassert_dbt-0.3.3/sqlassert_dbt.egg-info → sqlassert_dbt-0.4.1}/PKG-INFO +1 -1
  2. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/sqlassert_dbt/expectations.py +47 -6
  3. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/sqlassert_dbt/manifest.py +52 -2
  4. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/sqlassert_dbt/program.py +187 -125
  5. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/sqlassert_dbt/project.py +7 -1
  6. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1/sqlassert_dbt.egg-info}/PKG-INFO +1 -1
  7. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/sqlassert_dbt.egg-info/SOURCES.txt +1 -0
  8. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/sqlassert_dbt.egg-info/scm_file_list.json +1 -0
  9. sqlassert_dbt-0.4.1/sqlassert_dbt.egg-info/scm_version.json +8 -0
  10. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/tests/conftest.py +7 -0
  11. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/tests/test_dbt.py +52 -0
  12. sqlassert_dbt-0.4.1/tests/test_file_sources.py +114 -0
  13. sqlassert_dbt-0.3.3/sqlassert_dbt.egg-info/scm_version.json +0 -8
  14. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/LICENSE +0 -0
  15. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/README.md +0 -0
  16. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/pyproject.toml +0 -0
  17. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/setup.cfg +0 -0
  18. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/sqlassert_dbt/__init__.py +0 -0
  19. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/sqlassert_dbt/__main__.py +0 -0
  20. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/sqlassert_dbt/connect.py +0 -0
  21. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/sqlassert_dbt/jinja.py +0 -0
  22. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/sqlassert_dbt/report.py +0 -0
  23. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/sqlassert_dbt.egg-info/dependency_links.txt +0 -0
  24. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/sqlassert_dbt.egg-info/entry_points.txt +0 -0
  25. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/sqlassert_dbt.egg-info/requires.txt +0 -0
  26. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/sqlassert_dbt.egg-info/top_level.txt +0 -0
  27. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/tests/dbt_project/dbt_project.yml +0 -0
  28. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/tests/dbt_project/models/active_customers.sql +0 -0
  29. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/tests/dbt_project/models/customer_keys.sql +0 -0
  30. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/tests/dbt_project/models/customer_orders.sql +0 -0
  31. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/tests/dbt_project/models/customer_signups.sql +0 -0
  32. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/tests/dbt_project/models/customers.sql +0 -0
  33. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/tests/dbt_project/models/orders_appended.sql +0 -0
  34. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/tests/dbt_project/models/orders_incremental.sql +0 -0
  35. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/tests/dbt_project/models/schema.yml +0 -0
  36. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/tests/dbt_project/models/stg_customers.sql +0 -0
  37. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/tests/dbt_project/models/stg_orders.sql +0 -0
  38. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/tests/dbt_project/profiles.yml +0 -0
  39. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/tests/dbt_project/seeds/raw_payments.csv +0 -0
  40. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/tests/dbt_runs.py +0 -0
  41. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/tests/test_catalog.py +0 -0
  42. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/tests/test_connect.py +0 -0
  43. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/tests/test_contracts.py +0 -0
  44. {sqlassert_dbt-0.3.3 → sqlassert_dbt-0.4.1}/tests/test_suggest.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sqlassert-dbt
3
- Version: 0.3.3
3
+ Version: 0.4.1
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
@@ -91,18 +91,28 @@ def _test(test: Test, relations: Mapping[str, Relation]) -> Expectation | None:
91
91
  weakness = _weakness(test)
92
92
  unprovable = _threshold_unprovable(test)
93
93
  name = test.test_name if test.namespace is None else f"{test.namespace}.{test.test_name}"
94
+ kwargs = test.kwargs
95
+ # Written with or without its package's name, and whether the project
96
+ # overrides it or not: an override that keeps the name and signature is
97
+ # taken to keep the meaning.
98
+ expectation = f"dbt_expectations.{test.test_name}" if test.namespace in (None, "dbt_expectations") else None
99
+ if expectation in _DBT_EXPECTATIONS:
100
+ # The same checks as the core tests, unless a filter or ignored rows narrow them.
101
+ if kwargs.get("row_condition") or kwargs.get("ignore_row_if", "all_values_are_missing") not in _CHECKED_ROWS[expectation]:
102
+ return replace(base, asserted=None, declared=None, unprovable="it checks only the rows its row_condition or ignore_row_if keeps")
103
+ name, kwargs = _DBT_EXPECTATIONS[expectation], {**kwargs, **_expectation_kwargs(kwargs)}
94
104
  match name:
95
105
  case None:
96
106
  return replace(base, asserted=None, declared=None, unprovable="a singular test states no Property")
97
107
  case "unique" | "not_null" | "accepted_values" | "relationships":
98
- column = _column(test.kwargs.get("column_name") or test.column_name)
108
+ column = _column(kwargs.get("column_name") or test.column_name)
99
109
  if column is None:
100
110
  return replace(
101
111
  base,
102
- unprovable=f"it tests the expression {test.kwargs.get('column_name') or test.column_name!r}, not a column",
112
+ unprovable=f"it tests the expression {kwargs.get('column_name') or test.column_name!r}, not a column",
103
113
  )
104
114
  case "dbt_utils.unique_combination_of_columns":
105
- names = test.kwargs.get("combination_of_columns")
115
+ names = kwargs.get("combination_of_columns")
106
116
  columns = tuple(_column(name) for name in names) if isinstance(names, list) and names else (None,)
107
117
  if None in columns:
108
118
  return replace(base, asserted=None, declared=None, unprovable="its columns are not all plain columns")
@@ -118,15 +128,15 @@ def _test(test: Test, relations: Mapping[str, Relation]) -> Expectation | None:
118
128
  case "not_null":
119
129
  return replace(base, asserted="not_null", declared="not_null", columns=(column,), unprovable=unprovable, not_a_fact=weakness)
120
130
  case "accepted_values":
121
- values = _accepted_values(test.kwargs.get("values"), test.kwargs.get("quote", True))
131
+ values = _accepted_values(kwargs.get("values"), kwargs.get("quote", True))
122
132
  if values is None:
123
133
  return replace(base, asserted=None, declared=None, unprovable="its values are not all string, numeric or boolean literals")
124
134
  return replace(
125
135
  base, asserted="enum", declared="enum", columns=(column,), values=values, unprovable=unprovable, not_a_fact=weakness,
126
136
  )
127
137
  case _:
128
- target = _resolve_call(test.kwargs.get("to"), test.depends_on, relations)
129
- field = _column(test.kwargs.get("field"))
138
+ target = _resolve_call(kwargs.get("to"), test.depends_on, relations)
139
+ field = _column(kwargs.get("field"))
130
140
  if target is None or field is None:
131
141
  return replace(base, asserted=None, declared=None, unprovable="its `to` or `field` cannot be resolved")
132
142
  return replace(
@@ -135,6 +145,37 @@ def _test(test: Test, relations: Mapping[str, Relation]) -> Expectation | None:
135
145
  )
136
146
 
137
147
 
148
+ # dbt_expectations tests that check at least what a core or dbt_utils test
149
+ # checks: compound uniqueness over the rows not all NULL (rows with some NULL
150
+ # are checked too, which only adds rows to compare) or over the rows with no
151
+ # NULL (a Unique Set exempts the others too), uniqueness, non-null, and a
152
+ # value set (which also rejects NULL, more than accepted_values asks).
153
+ _DBT_EXPECTATIONS = {
154
+ "dbt_expectations.expect_compound_columns_to_be_unique": "dbt_utils.unique_combination_of_columns",
155
+ "dbt_expectations.expect_column_values_to_be_unique": "unique",
156
+ "dbt_expectations.expect_column_values_to_not_be_null": "not_null",
157
+ "dbt_expectations.expect_column_values_to_be_in_set": "accepted_values",
158
+ }
159
+ # The `ignore_row_if` each leaves checking enough rows for its Property.
160
+ _CHECKED_ROWS = {
161
+ name: ("all_values_are_missing", "any_value_is_missing") if name.endswith("compound_columns_to_be_unique")
162
+ else ("all_values_are_missing",)
163
+ for name in _DBT_EXPECTATIONS
164
+ }
165
+
166
+
167
+ def _expectation_kwargs(kwargs: Mapping[str, object]) -> dict[str, object]:
168
+ """A dbt_expectations test's arguments under the names its core twin reads."""
169
+ renamed: dict[str, object] = {}
170
+ if "column_list" in kwargs:
171
+ renamed["combination_of_columns"] = kwargs["column_list"]
172
+ if "value_set" in kwargs:
173
+ renamed["values"] = kwargs["value_set"]
174
+ if "quote_values" in kwargs:
175
+ renamed["quote"] = kwargs["quote_values"]
176
+ return renamed
177
+
178
+
138
179
  def _attached(test: Test, relations: Mapping[str, Relation]) -> str | None:
139
180
  if test.attached_node in relations:
140
181
  return test.attached_node
@@ -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(
@@ -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; its tests follow as Assertion Markers on that
8
- body, one per line. Any other relation (a source, seed, snapshot, incremental
9
- model) is a table, with a `CREATE TABLE` when its columns are known
10
- completely. An incremental model's `is_incremental()` branches, and an
11
- ephemeral model's body, are views of their own under generated names. Tests
12
- that are facts become Property Declarations, bound to the IR after linking.
13
-
14
- Nothing here writes a marker the author did not: the generated markers live on
15
- the generated bodies only, so the Property Markers stay the one user-facing
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.provenance import AttachmentSite
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, ForeignKey, NonNullColumn, NonNullColumns, NonNullUniqueSet, Property, ReferentialCoverage,
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.equality import _binary_text, _comparison_type, _identity_comparison
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
- QUERY_MATERIALIZATIONS = {"view", "table", "materialized_view", "dynamic_table"}
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, its tests as markers
333
- after it. `first_line` and `first_offset` are where the body starts in the
334
- Program; `placed` maps a Program line to the test whose marker it holds."""
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
- placed: dict[int, Expectation]
343
- unplaced: dict[str, TestResult]
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 Assertion Markers; any other relation as a table,
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
- text = self._text(self.relations[node], body, name, tests.get(node, []))
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, tests: list[Expectation]) -> _Text:
582
- """A body's statement, `placed` keyed by its own lines (the first is 1)."""
583
- lines = [f"create view {name} as select * from (", body.text, f") as {_identifier(model.name, self.dialect)}"]
584
- placed: dict[int, Expectation] = {}
585
- unplaced: dict[str, TestResult] = {}
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, tests.get(node, []))
603
+ text = self._text(model, body, name)
618
604
  self._statements.setdefault(node, []).append(Statement(
619
- model, body, name, line + 1, offset + text.text.index("\n") + 1,
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.text)
623
- line += text.text.count("\n") + 1
624
- offset += len(text.text) + 1
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
- conversion = IrParser(self.dialect).parse(self._ast) if self.fetcher is None else self._hydrated(self._ast)
628
- program = conversion.program
629
- placed = {line for statement in self._all() for line in statement.placed}
630
- assertions = tuple(
631
- _coverage(assertion) if assertion.origin.line in placed and isinstance(assertion.property, ForeignKey) else assertion
632
- for assertion in program.assertions
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 _hydrated(self, ast: ParsedProgram) -> IrConversionResult:
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(report, statement.placed)},
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 = next(
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 line in statement.placed or _about(diagnostic, names):
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 _canonical(relation_name: str | None, dialect: str) -> str:
999
- """How the IR names a relation written as `relation_name`."""
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.lower()
1006
- return ".".join(part for part in (table.catalog, table.db, table.name) if part).lower()
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 _coverage(assertion: ir.Assertion) -> ir.Assertion:
1020
- """A relationships test checks Referential Coverage only, never the
1021
- referenced Unique Set a Foreign Key Assertion also requires."""
1022
- property = assertion.property
1023
- assert isinstance(property, ForeignKey)
1024
- coverage = ReferentialCoverage(columns=property.columns, referenced_columns=property.referenced_columns)
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:
@@ -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
- if _canonical(relation.relation_name, dialect) != _name_of(table).lower():
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.3
3
+ Version: 0.4.1
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
@@ -24,6 +24,7 @@ tests/test_catalog.py
24
24
  tests/test_connect.py
25
25
  tests/test_contracts.py
26
26
  tests/test_dbt.py
27
+ tests/test_file_sources.py
27
28
  tests/test_suggest.py
28
29
  tests/dbt_project/dbt_project.yml
29
30
  tests/dbt_project/profiles.yml
@@ -31,6 +31,7 @@
31
31
  "tests/test_connect.py",
32
32
  "tests/test_contracts.py",
33
33
  "tests/test_dbt.py",
34
+ "tests/test_file_sources.py",
34
35
  "tests/test_suggest.py"
35
36
  ]
36
37
  }
@@ -0,0 +1,8 @@
1
+ {
2
+ "tag": "0.4.1",
3
+ "distance": 0,
4
+ "node": "g666215205ed0331abed3f8b529c7defb0d82d7b4",
5
+ "dirty": false,
6
+ "branch": "HEAD",
7
+ "node_date": "2026-11-28"
8
+ }
@@ -5,12 +5,19 @@ test reads what dbt writes, never a hand-written manifest or catalog."""
5
5
 
6
6
  from __future__ import annotations
7
7
 
8
+ import os
9
+ import sys
8
10
  from pathlib import Path
9
11
 
10
12
  import duckdb
11
13
  import pytest
12
14
  from dbt_runs import copy_source, dbt
13
15
 
16
+ # The `dbt` a test runs as a process (and `sqlassert-dbt`'s `run_dbt`, which
17
+ # takes it from PATH) is this interpreter's, not another environment's on PATH:
18
+ # a dbt with another DuckDB cannot read the warehouse file this one writes.
19
+ os.environ["PATH"] = f"{Path(sys.executable).parent}{os.pathsep}{os.environ.get('PATH', '')}"
20
+
14
21
 
15
22
  @pytest.fixture(scope="session")
16
23
  def compiled(tmp_path_factory: pytest.TempPathFactory) -> Path:
@@ -428,6 +428,52 @@ def test_unique_combination_is_proved_by_a_non_null_unique_set_and_declares_a_un
428
428
  assert (expectation.asserted, expectation.declared, expectation.columns) == ("key", "unique", ("customer_id", "first_name"))
429
429
 
430
430
 
431
+ @pytest.mark.parametrize(("test", "kwargs", "expected"), [
432
+ ("expect_compound_columns_to_be_unique", {"column_list": ["customer_id", "first_name"]}, ("key", ("customer_id", "first_name"))),
433
+ ("expect_column_values_to_be_unique", {"column_name": "customer_id"}, ("unique", ("customer_id",))),
434
+ ("expect_column_values_to_not_be_null", {"column_name": "customer_id"}, ("not_null", ("customer_id",))),
435
+ ("expect_column_values_to_be_in_set", {"column_name": "first_name", "value_set": ["a", "b"]}, ("enum", ("first_name",))),
436
+ ])
437
+ @pytest.mark.parametrize("namespace", ["dbt_expectations", None]) # None: written without the package, or overridden by the project.
438
+ def test_dbt_expectations_tests_map_like_their_core_twins(copy_project, test, kwargs, expected, namespace):
439
+ expectation = manifest_with_test(copy_project, test, kwargs, namespace=namespace)
440
+ assert (expectation.asserted, expectation.columns) == expected
441
+
442
+
443
+ def test_a_compound_test_over_the_rows_with_no_null_still_maps_to_a_key(copy_project):
444
+ # `any_value_is_missing` checks exactly the tuples a Unique Set does not exempt.
445
+ expectation = manifest_with_test(
446
+ copy_project, "expect_compound_columns_to_be_unique", {"column_list": ["customer_id"], "ignore_row_if": "any_value_is_missing"},
447
+ )
448
+ assert (expectation.asserted, expectation.declared) == ("key", "unique")
449
+
450
+
451
+ def test_another_packages_test_of_the_same_name_maps_to_no_property(copy_project):
452
+ expectation = manifest_with_test(copy_project, "expect_compound_columns_to_be_unique", {"column_list": ["customer_id"]}, namespace="other")
453
+ assert expectation.asserted is None
454
+
455
+
456
+ @pytest.mark.parametrize("kwargs", [
457
+ {"column_list": ["customer_id"], "row_condition": "customer_id > 0"},
458
+ {"column_list": ["customer_id"], "ignore_row_if": "never"},
459
+ ])
460
+ def test_a_filtered_dbt_expectations_test_maps_to_no_property(copy_project, kwargs):
461
+ expectation = manifest_with_test(copy_project, "expect_compound_columns_to_be_unique", kwargs, namespace="dbt_expectations")
462
+ assert expectation.asserted is None and "row_condition" in expectation.unprovable
463
+
464
+
465
+ @pytest.mark.parametrize(("quote", "values"), [
466
+ (True, (LiteralValue("string", "1"),)),
467
+ (False, (LiteralValue("numeric", "1"),)),
468
+ ])
469
+ def test_in_set_values_are_strings_unless_unquoted(copy_project, quote, values):
470
+ expectation = manifest_with_test(
471
+ copy_project, "expect_column_values_to_be_in_set", {"column_name": "first_name", "value_set": [1], "quote_values": quote},
472
+ namespace="dbt_expectations",
473
+ )
474
+ assert expectation.values == values
475
+
476
+
431
477
  @pytest.mark.parametrize(("quote", "values"), [
432
478
  (True, (LiteralValue("string", "1"), LiteralValue("string", "a"))),
433
479
  (False, None),
@@ -648,3 +694,9 @@ def test_build_and_test_analyze_the_forwarded_target_path(copy_project, monkeypa
648
694
  assert main([command, str(project), "--", "--target-path", "alternate"]) == 1
649
695
  assert "UNKNOWN /**ASSERT NOT NULL(first_name)**/" in capsys.readouterr().out
650
696
  assert [call[0] for call in calls] == ["compile", command]
697
+
698
+
699
+ def test_an_unknown_markers_explanation_leads_with_its_causes_on_model_lines(report):
700
+ marker = next(m for m in report.markers if m.model == "customers" and "MANY TO ONE" in m.marker)
701
+ first = marker.explanation.splitlines()[0]
702
+ assert first.startswith("line 11: LEFT JOIN orders ON orders.customer_id = customers.customer_id is not many-to-one"), first
@@ -0,0 +1,114 @@
1
+ """Sources that read files (dbt-duckdb `external_location`): dbt pastes the read,
2
+ `read_csv('…/people.csv', header = true)` or `'…/kinds.csv'`, where a
3
+ table name would go. The plugin names each such source after its file, so it
4
+ can be declared like a table and given the columns a catalog lists for it."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ from pathlib import Path
10
+
11
+ import duckdb
12
+ import pytest
13
+ from dbt_runs import copy_source, dbt
14
+
15
+ from sqlassert_dbt import analyze_project
16
+ from sqlassert_dbt.manifest import load_manifest
17
+ from sqlassert.reporting import Outcome
18
+
19
+ SOURCES = """version: 2
20
+ sources:
21
+ - name: files
22
+ meta: {external_location: "DATA/{identifier}.csv"}
23
+ tables:
24
+ - name: kinds
25
+ columns:
26
+ - name: id
27
+ data_tests: [unique, not_null]
28
+ - name: people
29
+ meta: {external_location: "read_csv('DATA/people.csv', header = true)"}
30
+ """
31
+ MODEL = (
32
+ "select people.id, kinds.name from {{ source('files', 'people') }} as people\n"
33
+ "/**ASSERT MANY TO ONE**/ left join {{ source('files', 'kinds') }} as kinds on people.kind_id = kinds.id\n"
34
+ )
35
+ # An `external` model writes its rows to a file each run; readers read its query.
36
+ EXTERNAL = (
37
+ "{{ config(materialized='external', location='KINDS_PARQUET') }}\n"
38
+ "select id, name from {{ source('files', 'kinds') }}\n"
39
+ )
40
+ THROUGH_EXTERNAL = (
41
+ "select people.id, kinds.name from {{ source('files', 'people') }} as people\n"
42
+ "/**ASSERT MANY TO ONE**/ left join {{ ref('kinds_external') }} as kinds on people.kind_id = kinds.id\n"
43
+ )
44
+ MARKER = "models/people_kinds.sql:2 /**ASSERT MANY TO ONE**/"
45
+ EXTERNAL_MARKER = "models/people_external_kinds.sql:2 /**ASSERT MANY TO ONE**/"
46
+ COLUMNS = {
47
+ "source.jaffle.files.kinds": [("id", "INTEGER"), ("name", "VARCHAR")],
48
+ "source.jaffle.files.people": [("id", "INTEGER"), ("kind_id", "INTEGER")],
49
+ }
50
+
51
+
52
+ @pytest.fixture(scope="module")
53
+ def project(tmp_path_factory: pytest.TempPathFactory) -> Path:
54
+ directory = tmp_path_factory.mktemp("files")
55
+ project = copy_source(directory)
56
+ (project / "data").mkdir()
57
+ (project / "data" / "kinds.csv").write_text("id,name\n1,a\n2,b\n")
58
+ (project / "data" / "people.csv").write_text("id,kind_id\n10,1\n11,2\n")
59
+ # dbt-duckdb reads relative paths from the working directory; these are absolute.
60
+ (project / "models" / "files.yml").write_text(SOURCES.replace("DATA", str(project / "data")))
61
+ (project / "models" / "people_kinds.sql").write_text(MODEL)
62
+ (project / "models" / "kinds_external.sql").write_text(EXTERNAL.replace("KINDS_PARQUET", str(directory / "kinds.parquet")))
63
+ (project / "models" / "people_external_kinds.sql").write_text(THROUGH_EXTERNAL)
64
+ database = directory / "warehouse.duckdb"
65
+ profiles = project / "profiles.yml"
66
+ profiles.write_text(profiles.read_text().replace('":memory:"', f'"{database}"'))
67
+ with duckdb.connect(str(database)) as connection:
68
+ connection.execute("create schema raw")
69
+ for table in ("customers (id integer, first_name varchar)",
70
+ "orders (id integer, user_id integer, status varchar, amount decimal(10, 2))",
71
+ "signups (id integer, code varchar)"):
72
+ connection.execute(f"create table raw.{table}")
73
+ for command in ("seed", "run", "docs generate"):
74
+ assert dbt(project, *command.split()), f"dbt {command} failed"
75
+ return project
76
+
77
+
78
+ def outcome(report, marker: str) -> Outcome:
79
+ return next(found.outcome for found in report.markers if f"{found.location} {found.marker}" == marker)
80
+
81
+
82
+ def test_a_file_source_is_named_after_its_file(project):
83
+ relations = load_manifest(project / "target" / "manifest.json").relations
84
+ assert relations["source.jaffle.files.people"].relation_name == "__file_people"
85
+ assert relations["source.jaffle.files.kinds"].relation_name == "__file_kinds"
86
+ compiled = relations["model.jaffle.people_kinds"].compiled_code or ""
87
+ assert "from __file_people as people" in compiled and "join __file_kinds as kinds" in compiled
88
+ # One line each, as dbt wrote them: marker lines still match the model file.
89
+ written = json.loads((project / "target" / "manifest.json").read_text())["nodes"]["model.jaffle.people_kinds"]
90
+ assert compiled.count("\n") == written["compiled_code"].count("\n")
91
+
92
+
93
+ def test_without_columns_a_file_source_warns_with_its_read(project):
94
+ report = analyze_project(project, trust_upstream_tests=True)
95
+ assert outcome(report, MARKER) is Outcome.UNKNOWN
96
+ unknown = [problem.message for problem in report.problems if problem.code == "dbt-unknown-columns"]
97
+ assert any("read_csv(" in message and "people.csv" in message for message in unknown)
98
+
99
+
100
+ def test_catalog_columns_of_a_file_source_prove_its_join(project, tmp_path):
101
+ catalog = json.loads((project / "target" / "catalog.json").read_text())
102
+ # dbt docs generate lists no file source; give them entries as base facts would.
103
+ for unique_id, columns in COLUMNS.items():
104
+ catalog["sources"][unique_id] = {
105
+ "metadata": {"type": "BASE TABLE", "schema": "main", "name": unique_id.rsplit(".", 1)[1], "database": "warehouse"},
106
+ "columns": {name: {"type": kind, "index": index, "name": name} for index, (name, kind) in enumerate(columns, 1)},
107
+ "stats": {}, "unique_id": unique_id,
108
+ }
109
+ path = tmp_path / "catalog.json"
110
+ path.write_text(json.dumps(catalog))
111
+ report = analyze_project(project, trust_upstream_tests=True, catalog_path=path)
112
+ assert outcome(report, MARKER) is Outcome.PROVED
113
+ assert outcome(report, EXTERNAL_MARKER) is Outcome.PROVED
114
+ assert "dbt-catalog-other-relation" not in [problem.code for problem in report.problems]
@@ -1,8 +0,0 @@
1
- {
2
- "tag": "0.3.3",
3
- "distance": 0,
4
- "node": "ge759f64bea040b10e5482ec3e35f8d9688ad9139",
5
- "dirty": false,
6
- "branch": "HEAD",
7
- "node_date": "2026-11-13"
8
- }
File without changes
File without changes
File without changes