sqlassert-dbt 0.3.1__py3-none-any.whl → 0.4.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sqlassert_dbt/__init__.py CHANGED
@@ -3,17 +3,19 @@
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
5
5
  proved Properties no test states, and the outcome of every marker written in
6
- a model file, mapped back to that file's lines. `sqlassert-dbt` is its command
7
- line (`__main__.py`).
6
+ a model file, mapped back to that file's lines. `suggest_models(project_dir,
7
+ files)` lists what `sqlassert suggest` finds in those model files, with what
8
+ each model reads declared. `sqlassert-dbt` is its command line (`__main__.py`).
8
9
  """
9
10
 
10
- from sqlassert_dbt.project import SUPPORTED_DIALECTS, ProjectError, analyze_project
11
+ from sqlassert_dbt.project import SUPPORTED_DIALECTS, ProjectError, analyze_project, suggest_models
11
12
  from sqlassert_dbt.report import (
12
- DbtReport, Location, MarkerOutcome, Problem, Status, TestOutcome, Untested,
13
- exit_code, format_text,
13
+ DbtReport, Location, MarkerOutcome, ModelSuggestion, Problem, Status, SuggestReport, TestOutcome, Untested,
14
+ exit_code, format_suggestion_blocks, format_suggestion_summary, format_suggestions, format_text,
14
15
  )
15
16
 
16
17
  __all__ = [
17
- "SUPPORTED_DIALECTS", "DbtReport", "Location", "MarkerOutcome", "Problem",
18
- "ProjectError", "Status", "TestOutcome", "Untested", "analyze_project", "exit_code", "format_text",
18
+ "SUPPORTED_DIALECTS", "DbtReport", "Location", "MarkerOutcome", "ModelSuggestion", "Problem",
19
+ "ProjectError", "Status", "SuggestReport", "TestOutcome", "Untested", "analyze_project", "exit_code",
20
+ "format_suggestion_blocks", "format_suggestion_summary", "format_suggestions", "format_text", "suggest_models",
19
21
  ]
sqlassert_dbt/__main__.py CHANGED
@@ -8,28 +8,47 @@ checked too: `dbt compile`, then the check, then `dbt build` (or `dbt test`)
8
8
  with every test the SQL proves excluded. dbt runs the tests of what a model
9
9
  reads in the same invocation, so they are facts, unless DBT_ARGS select nodes
10
10
  (a selection may leave an upstream test out).
11
+
12
+ `sqlassert-dbt suggest PATH... [-- DBT_ARGS]` runs `dbt compile` on the
13
+ models in those files or directories and what they read, then lists what `sqlassert suggest` finds in
14
+ each: rewrites, markers to paste, hazards, at the model file's lines.
15
+
16
+ `--connect` (build, test, suggest) reads the tables models read from the
17
+ warehouse, through the connection dbt opens for the same profile and target
18
+ (`connect.py`). `check` stays connectionless.
11
19
  """
12
20
 
13
21
  from __future__ import annotations
14
22
 
15
23
  import argparse
24
+ import os
25
+ import secrets
26
+ import shutil
27
+ import tempfile
16
28
  import subprocess
17
29
  import sys
30
+ from contextlib import nullcontext
31
+ from dataclasses import replace
18
32
  from pathlib import Path
19
33
 
20
34
  from sqlassert.check import EXIT_FINDINGS, EXIT_OK, EXIT_USAGE
21
- from sqlassert_dbt.project import ProjectError, analyze_project
22
- from sqlassert_dbt.report import DbtReport, exit_code, format_text
35
+ from sqlassert_dbt.connect import ConnectError, dbt_fetcher
36
+ from sqlassert_dbt.project import ProjectError, analyze_project, suggest_models
37
+ from sqlassert_dbt.report import (
38
+ DEFAULT_WARNING_LIMIT, DbtReport, Location, SuggestReport, WarningLimit, exit_code, format_suggestion_blocks, format_suggestion_summary,
39
+ format_text,
40
+ )
23
41
 
24
42
  # The dbt flags that narrow which nodes run: under any of them, the tests of
25
43
  # what a model reads may not run, so they are no facts.
26
44
  SELECTION_FLAGS = frozenset({"-s", "--select", "-m", "--models", "--model", "--exclude", "--selector", "--resource-type", "--resource-types"})
27
45
 
28
46
 
29
- def run_dbt(arguments: list[str]) -> int:
30
- """Run dbt from PATH with `arguments`; its exit status."""
47
+ def run_dbt(arguments: list[str], *, to_stderr: bool = False) -> int:
48
+ """Run dbt from PATH with `arguments`; its exit status. `to_stderr` sends
49
+ its output there, leaving stdout to the report."""
31
50
  try:
32
- return subprocess.run(["dbt", *arguments], check=False).returncode
51
+ return subprocess.run(["dbt", *arguments], check=False, stdout=sys.stderr if to_stderr else None).returncode
33
52
  except FileNotFoundError:
34
53
  print("sqlassert-dbt: dbt is not on PATH", file=sys.stderr)
35
54
  return EXIT_USAGE
@@ -60,35 +79,221 @@ def main(argv: list[str] | None = None) -> int:
60
79
  f"UNKNOWN or a diagnostic is reported, else {EXIT_OK}.",
61
80
  )
62
81
  _common(command)
82
+ _connect(command)
63
83
  command.add_argument("dbt_arguments", nargs=argparse.REMAINDER, help="-- then arguments for dbt")
84
+ suggest = commands.add_parser(
85
+ "suggest",
86
+ help="`dbt compile`, then list the rewrites, markers and hazards sqlassert finds in model files",
87
+ description="Run `dbt compile` on the models and what they read, then list what sqlassert can prove about each "
88
+ "model file: rewrites that keep its result, markers to paste, hazards. Arguments after -- go to dbt. "
89
+ f"Exit status: {EXIT_OK}, or {EXIT_FINDINGS} when an error is reported, {EXIT_USAGE} on bad arguments.",
90
+ usage="sqlassert-dbt suggest [options] PATH... [-- DBT_ARGS]",
91
+ )
92
+ suggest.add_argument(
93
+ "files", nargs="+", metavar="PATH",
94
+ help="model .sql files or directories of models (the project's own directory: every model) of one dbt project",
95
+ )
96
+ suggest.add_argument(
97
+ "--project-dir", help="dbt project directory (default: the nearest one holding the first PATH)",
98
+ )
99
+ suggest.add_argument("--dialect", help="analyze under this dialect instead of the adapter's")
100
+ _catalog(suggest)
101
+ _connect(suggest)
102
+ _warning_limit(suggest)
103
+ suggest.add_argument(
104
+ "--dbt-compile-inplace", action="store_true",
105
+ help="let dbt compile into the project's own target/ and logs/ (keeping its partial-parse cache) "
106
+ "instead of a temporary directory",
107
+ )
108
+ suggest.add_argument("--explain", action="store_true", help="print each suggestion's evidence")
109
+ suggest.add_argument(
110
+ "--trust-upstream-tests", action="store_true",
111
+ help="take the passing tests of what each model reads as facts about it: true when they run first, as in `dbt build`",
112
+ )
113
+ argv = sys.argv[1:] if argv is None else argv
114
+ if argv[:1] == ["suggest"] and "--" in argv:
115
+ # Files take every positional, so the dbt arguments are split off by hand.
116
+ split = argv.index("--")
117
+ arguments = parser.parse_args(argv[:split])
118
+ return _suggest(arguments, argv[split + 1:])
64
119
  arguments = parser.parse_args(argv)
120
+ if arguments.command == "suggest":
121
+ return _suggest(arguments, [])
65
122
  project = Path(arguments.project)
66
123
 
67
124
  if arguments.command == "check":
68
- report = _analyze(project, arguments.manifest, arguments.dialect, arguments.trust_upstream_tests)
125
+ report = _analyze(project, arguments.manifest, arguments.dialect, arguments.trust_upstream_tests, arguments)
69
126
  if report is None:
70
127
  return EXIT_USAGE
71
- sys.stdout.write(format_text(report, explain=arguments.explain))
128
+ sys.stdout.write(format_text(report, explain=arguments.explain, warning_limit=arguments.warning_limit))
72
129
  return exit_code(report, require_proved=arguments.require_proved)
73
130
 
74
131
  passed = [argument for argument in arguments.dbt_arguments if argument != "--"]
75
- located = [*passed, "--project-dir", str(project)]
132
+ located = [*passed, "--project-dir", str(project), *_profiles(project.resolve(), passed)]
76
133
  compiled = run_dbt(["compile", *located])
77
134
  if compiled != 0:
78
135
  return compiled
79
136
  selecting = any(argument.split("=")[0] in SELECTION_FLAGS for argument in passed)
80
- report = _analyze(project, None, arguments.dialect, not selecting)
137
+ target = _option(passed, "--target-path") or os.environ.get("DBT_TARGET_PATH") or "target"
138
+ report = _analyze(project, str(project / target / "manifest.json"), arguments.dialect, not selecting, arguments, passed)
81
139
  if report is None:
82
140
  return EXIT_USAGE
83
- sys.stdout.write(format_text(report, explain=arguments.explain))
141
+ sys.stdout.write(format_text(report, explain=arguments.explain, warning_limit=arguments.warning_limit))
84
142
  proved = proved_tests(report)
85
143
  ran = run_dbt([arguments.command, *located, *(["--exclude", *proved] if proved else [])])
86
144
  return ran if ran != 0 else exit_code(report, require_proved=arguments.require_proved)
87
145
 
88
146
 
147
+ def _suggest(arguments: argparse.Namespace, passed: list[str]) -> int:
148
+ paths = [Path(path).resolve() for path in arguments.files]
149
+ if arguments.project_dir is not None:
150
+ project = Path(arguments.project_dir).resolve()
151
+ else:
152
+ first = paths[0]
153
+ candidates = [first, *first.parents] if first.is_dir() else list(first.parents)
154
+ project = next((folder for folder in candidates if (folder / "dbt_project.yml").is_file()), None)
155
+ if project is None:
156
+ print(f"sqlassert-dbt: no dbt_project.yml at or above {arguments.files[0]}; pass --project-dir", file=sys.stderr)
157
+ return EXIT_USAGE
158
+ relative = []
159
+ for given, path in zip(arguments.files, paths):
160
+ if not path.is_relative_to(project):
161
+ print(f"sqlassert-dbt: {given} is outside the dbt project {project}", file=sys.stderr)
162
+ return EXIT_USAGE
163
+ relative.append(path.relative_to(project).as_posix())
164
+ selecting = any(argument.split("=")[0] in SELECTION_FLAGS for argument in passed)
165
+ # Only the models and what they read need compiled code; the whole project, for its own directory.
166
+ selection = [] if selecting or "." in relative else ["--select", *(f"+path:{path}" for path in relative)]
167
+ located = [*passed, *selection, "--project-dir", str(project), *_profiles(project, passed)]
168
+ # dbt writes target/ and logs/ as it compiles; suggest leaves the project's
169
+ # own alone, unless the caller names where.
170
+ scratch = Path(tempfile.mkdtemp(prefix="sqlassert-dbt-"))
171
+ shortcut = None
172
+ try:
173
+ given = _option(passed, "--target-path")
174
+ inplace = arguments.dbt_compile_inplace
175
+ target = project / given if given is not None else project / "target" if inplace else scratch / "target"
176
+ if given is None and not inplace:
177
+ located += ["--target-path", str(target)]
178
+ shortcut = _Shortcut(target / "compiled")
179
+ if _option(passed, "--log-path") is None and not inplace:
180
+ located += ["--log-path", str(scratch / "logs")]
181
+ compiled = run_dbt(["compile", *located], to_stderr=True)
182
+ if compiled != 0:
183
+ return compiled
184
+ return _report_suggestions(arguments, project, relative, target / "manifest.json", shortcut, passed)
185
+ finally:
186
+ if shortcut is not None and shortcut.link is not None:
187
+ print(f"sqlassert-dbt: compiled code kept for the locations above: {shortcut.link} -> {shortcut.compiled}", file=sys.stderr)
188
+ else:
189
+ shutil.rmtree(scratch, ignore_errors=True)
190
+
191
+
192
+ # Where the link goes: /tmp is short; macOS's own temporary directory is not.
193
+ _SHORT_ROOT = Path("/tmp") if Path("/tmp").is_dir() else Path(tempfile.gettempdir())
194
+
195
+
196
+ class _Shortcut:
197
+ """A short link, made on first use, to the compiled code in suggest's own
198
+ temporary target: a location dbt's rendering cannot map back to the model
199
+ file points at the compiled file, and the link keeps that path short and
200
+ the file there after the run."""
201
+
202
+ def __init__(self, compiled: Path) -> None:
203
+ self.compiled = compiled
204
+ self.link: Path | None = None
205
+
206
+ def location(self, location: Location) -> Location:
207
+ path = Path(location.path)
208
+ if not path.is_absolute() or not path.is_relative_to(self.compiled):
209
+ return location
210
+ if self.link is None:
211
+ while True:
212
+ link = _SHORT_ROOT / f"sqlassert-{secrets.token_hex(3)}"
213
+ try:
214
+ link.symlink_to(self.compiled, target_is_directory=True)
215
+ break
216
+ except FileExistsError:
217
+ continue
218
+ self.link = link
219
+ return replace(location, path=str(self.link / path.relative_to(self.compiled)))
220
+
221
+ def report(self, report: SuggestReport) -> SuggestReport:
222
+ return replace(
223
+ report,
224
+ suggestions=tuple(replace(item, location=self.location(item.location)) for item in report.suggestions),
225
+ problems=tuple(
226
+ replace(problem, location=self.location(problem.location)) if problem.location is not None else problem
227
+ for problem in report.problems
228
+ ),
229
+ )
230
+
231
+
232
+ def _report_suggestions(
233
+ arguments: argparse.Namespace, project: Path, relative: list[str], manifest: Path, shortcut: _Shortcut | None = None,
234
+ dbt_arguments: list[str] | None = None,
235
+ ) -> int:
236
+ limit = WarningLimit(arguments.warning_limit)
237
+
238
+ def shown(part: SuggestReport) -> None:
239
+ part = shortcut.report(part) if shortcut is not None else part
240
+ print(format_suggestion_blocks(part, explain=arguments.explain, limit=limit), end="", flush=True)
241
+
242
+ try:
243
+ with _fetcher(arguments, project, dbt_arguments or []) as fetcher:
244
+ report = suggest_models(
245
+ project, relative, manifest_path=manifest, dialect=arguments.dialect,
246
+ trust_upstream_tests=arguments.trust_upstream_tests,
247
+ catalog_path=_path(arguments.catalog), read_catalog=not arguments.no_catalog,
248
+ on_model=shown, fetcher=fetcher,
249
+ )
250
+ except (ProjectError, ConnectError) as error:
251
+ print(f"sqlassert-dbt: {error}", file=sys.stderr)
252
+ return EXIT_USAGE
253
+ sys.stdout.write(format_suggestion_summary(report, limit))
254
+ return EXIT_FINDINGS if report.failed else EXIT_OK
255
+
256
+
257
+ _CATALOG_HELP = (
258
+ "read the columns and types of sources, seeds and other tables from this catalog.json instead of "
259
+ "PROJECT/target/catalog.json, which is read when present (`dbt docs generate` writes it)"
260
+ )
261
+
262
+
263
+ def _catalog(command: argparse.ArgumentParser) -> None:
264
+ reading = command.add_mutually_exclusive_group()
265
+ reading.add_argument("--catalog", help=_CATALOG_HELP)
266
+ reading.add_argument(
267
+ "--no-catalog", action="store_true", help="read no catalog.json: the manifest's columns only",
268
+ )
269
+
270
+
271
+ def _connect(command: argparse.ArgumentParser) -> None:
272
+ command.add_argument(
273
+ "--connect", action="store_true",
274
+ help="read the columns, types, keys and NOT NULLs of the tables models read from the warehouse, through the "
275
+ "connection dbt opens for the same profile and target (instead of catalog.json); DuckDB, Postgres, Redshift, "
276
+ "Snowflake, MySQL and Trino adapters",
277
+ )
278
+
279
+
280
+ def _fetcher(arguments: argparse.Namespace, project: Path, dbt_arguments: list[str]):
281
+ """dbt's connection under --connect, closed before dbt runs again; else none."""
282
+ return dbt_fetcher(project, dbt_arguments) if getattr(arguments, "connect", False) else nullcontext(None)
283
+
284
+
285
+ def _warning_limit(command: argparse.ArgumentParser) -> None:
286
+ command.add_argument(
287
+ "--warning-limit", type=int, default=DEFAULT_WARNING_LIMIT, metavar="N",
288
+ help=f"print at most N warnings of each code, then say the rest are suppressed (default {DEFAULT_WARNING_LIMIT}; 0: all)",
289
+ )
290
+
291
+
89
292
  def _common(command: argparse.ArgumentParser) -> None:
90
293
  command.add_argument("project", nargs="?", default=".", help="dbt project directory (default: .)")
294
+ _warning_limit(command)
91
295
  command.add_argument("--dialect", help="analyze under this dialect instead of the adapter's")
296
+ _catalog(command)
92
297
  command.add_argument("--explain", action="store_true", help="print each proof and failed proof")
93
298
  command.add_argument(
94
299
  "--require-proved", action="store_true",
@@ -101,15 +306,45 @@ def proved_tests(report: DbtReport) -> list[str]:
101
306
  return sorted({test.name for test in report.tests if test.skippable})
102
307
 
103
308
 
104
- def _analyze(project: Path, manifest: str | None, dialect: str | None, trust: bool) -> DbtReport | None:
309
+ def _analyze(
310
+ project: Path, manifest: str | None, dialect: str | None, trust: bool, arguments: argparse.Namespace,
311
+ dbt_arguments: list[str] | None = None,
312
+ ) -> DbtReport | None:
105
313
  try:
106
- return analyze_project(
107
- project, manifest_path=Path(manifest) if manifest else None, dialect=dialect, trust_upstream_tests=trust,
108
- )
109
- except ProjectError as error:
314
+ with _fetcher(arguments, project, dbt_arguments or []) as fetcher:
315
+ return analyze_project(
316
+ project, manifest_path=_path(manifest), dialect=dialect, trust_upstream_tests=trust,
317
+ catalog_path=_path(arguments.catalog), read_catalog=not arguments.no_catalog, fetcher=fetcher,
318
+ )
319
+ except (ProjectError, ConnectError) as error:
110
320
  print(f"sqlassert-dbt: {error}", file=sys.stderr)
111
321
  return None
112
322
 
113
323
 
324
+ def _profiles(project: Path, passed: list[str]) -> list[str]:
325
+ """`--profiles-dir PROJECT` when the project holds the profiles.yml dbt
326
+ would not otherwise find: dbt looks in the working directory, then
327
+ DBT_PROFILES_DIR, then ~/.dbt, never in the project."""
328
+ if any(argument.split("=")[0] == "--profiles-dir" for argument in passed) or os.environ.get("DBT_PROFILES_DIR"):
329
+ return []
330
+ if not (project / "profiles.yml").is_file() or (Path.cwd() / "profiles.yml").is_file():
331
+ return []
332
+ return ["--profiles-dir", str(project)]
333
+
334
+
335
+ def _option(passed: list[str], name: str) -> str | None:
336
+ """The value the caller gave dbt for `name` (`--name V` or `--name=V`)."""
337
+ for index, argument in enumerate(passed):
338
+ if argument == name and index + 1 < len(passed):
339
+ return passed[index + 1]
340
+ if argument.startswith(name + "="):
341
+ return argument.split("=", 1)[1]
342
+ return None
343
+
344
+
345
+ def _path(value: str | None) -> Path | None:
346
+ return Path(value) if value else None
347
+
348
+
114
349
  if __name__ == "__main__":
115
350
  sys.exit(main())
@@ -0,0 +1,135 @@
1
+ """`--connect`: the warehouse connection dbt itself would open.
2
+
3
+ The profile and target dbt ran with name the warehouse; dbt's adapter opens
4
+ the connection, and the driver's own handle feeds the matching core
5
+ `DatabaseKnowledgeFetcher`. This leans on dbt's adapter API
6
+ (`RuntimeConfig.from_args`, `register_adapter`, `connection_named`), which
7
+ is internal and changes across dbt versions: any failure is a
8
+ `ConnectError` naming the Python route, `analyze_project(fetcher=...)`.
9
+
10
+ Only the DuckDB adapter is tested end to end (`tests/test_connect.py`). The
11
+ others hand their driver's DB-API connection to the fetcher written for it.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ from argparse import Namespace
18
+ from collections.abc import Callable, Generator
19
+ from contextlib import contextmanager
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from sqlassert.discovery import DatabaseKnowledgeFetcher
24
+
25
+
26
+ class ConnectError(Exception):
27
+ """dbt's connection could not be opened, or its adapter has no fetcher."""
28
+
29
+
30
+ def _duckdb(handle: Any) -> DatabaseKnowledgeFetcher:
31
+ from sqlassert.discovery.duckdb import DuckDBKnowledgeFetcher
32
+
33
+ # dbt-duckdb wraps the connection; its cursor is a DuckDB connection.
34
+ return DuckDBKnowledgeFetcher(handle.cursor())
35
+
36
+
37
+ def _dbapi(module: str, name: str) -> Callable[[Any], DatabaseKnowledgeFetcher]:
38
+ def fetcher(handle: Any) -> DatabaseKnowledgeFetcher:
39
+ import importlib
40
+
41
+ return getattr(importlib.import_module(f"sqlassert.discovery.{module}"), name)(handle)
42
+
43
+ return fetcher
44
+
45
+
46
+ # dbt adapter type: the fetcher over its connection handle. BigQuery (a
47
+ # client, not a DB-API connection) and Databricks (a wrapped connection) are
48
+ # not mapped yet: pass a fetcher through `analyze_project` instead.
49
+ FETCHERS: dict[str, Callable[[Any], DatabaseKnowledgeFetcher]] = {
50
+ "duckdb": _duckdb,
51
+ "postgres": _dbapi("postgres", "PostgresKnowledgeFetcher"),
52
+ "redshift": _dbapi("redshift", "RedshiftKnowledgeFetcher"),
53
+ "snowflake": _dbapi("snowflake", "SnowflakeKnowledgeFetcher"),
54
+ "mysql": _dbapi("mysql", "MySQLKnowledgeFetcher"),
55
+ "trino": _dbapi("trino", "TrinoKnowledgeFetcher"),
56
+ }
57
+
58
+
59
+ @contextmanager
60
+ def dbt_fetcher(project: Path, dbt_arguments: list[str]) -> Generator[DatabaseKnowledgeFetcher]:
61
+ """A fetcher over the connection dbt opens for `project` with the
62
+ profile, target, profiles directory and vars in `dbt_arguments`, closed
63
+ on exit: a DuckDB file takes one writer, so close it before dbt runs again."""
64
+ try:
65
+ import yaml
66
+ from dbt.adapters.factory import cleanup_connections, get_adapter, register_adapter, reset_adapters
67
+ from dbt.config.runtime import RuntimeConfig
68
+ from dbt.flags import set_from_args
69
+ from dbt.mp_context import get_mp_context
70
+ except ImportError as error:
71
+ raise ConnectError(f"--connect needs dbt installed in sqlassert-dbt's Python ({error})") from error
72
+ try:
73
+ args = Namespace(
74
+ project_dir=str(project), profiles_dir=str(_profiles_dir(project, dbt_arguments)),
75
+ profile=_option(dbt_arguments, "--profile"), target=_option(dbt_arguments, "--target", "-t"),
76
+ vars=yaml.safe_load(_option(dbt_arguments, "--vars") or "{}") or {}, threads=None,
77
+ )
78
+ set_from_args(args, None)
79
+ config = RuntimeConfig.from_args(args)
80
+ # An adapter dbt registered earlier in this process (dbtRunner) stays
81
+ # registered under its type, with that run's profile: replace it.
82
+ reset_adapters()
83
+ register_adapter(config, get_mp_context())
84
+ adapter = get_adapter(config)
85
+ except Exception as error: # dbt's internals raise their own types, version by version.
86
+ raise ConnectError(f"dbt could not load the profile for --connect: {error}") from error
87
+ kind = adapter.type()
88
+ if kind not in FETCHERS:
89
+ raise ConnectError(
90
+ f"--connect does not support the {kind} adapter yet: call analyze_project(..., fetcher=...) with a "
91
+ f"sqlassert.discovery fetcher over your own connection"
92
+ )
93
+ try:
94
+ with adapter.connection_named("sqlassert"):
95
+ handle = adapter.connections.get_thread_connection().handle
96
+ yield FETCHERS[kind](handle)
97
+ finally:
98
+ cleanup_connections()
99
+ if kind == "duckdb":
100
+ _close_duckdb_environment()
101
+
102
+
103
+ def _close_duckdb_environment() -> None:
104
+ """dbt-duckdb keeps its database open past `cleanup_connections` (its
105
+ environment's `keep_open`), holding the file's lock against the next dbt
106
+ process; close it."""
107
+ from dbt.adapters.duckdb.connections import DuckDBConnectionManager
108
+
109
+ environment = DuckDBConnectionManager._ENV
110
+ DuckDBConnectionManager.close_all_connections()
111
+ if environment is not None:
112
+ environment.close()
113
+
114
+
115
+ def _profiles_dir(project: Path, arguments: list[str]) -> Path:
116
+ """Where dbt reads profiles.yml: --profiles-dir, DBT_PROFILES_DIR, the
117
+ working directory, then ~/.dbt; and the project, as `_profiles` passes it."""
118
+ given = _option(arguments, "--profiles-dir") or os.environ.get("DBT_PROFILES_DIR")
119
+ if given:
120
+ return Path(given)
121
+ for folder in (Path.cwd(), project):
122
+ if (folder / "profiles.yml").is_file():
123
+ return folder
124
+ return Path.home() / ".dbt"
125
+
126
+
127
+ def _option(arguments: list[str], *names: str) -> str | None:
128
+ """The value given for any of `names` (`--name V` or `--name=V`)."""
129
+ for index, argument in enumerate(arguments):
130
+ for name in names:
131
+ if argument == name and index + 1 < len(arguments):
132
+ return arguments[index + 1]
133
+ if argument.startswith(name + "="):
134
+ return argument.split("=", 1)[1]
135
+ return None
@@ -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