sqlassert-dbt 0.3.1__py3-none-any.whl → 0.3.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sqlassert_dbt/__init__.py +9 -7
- sqlassert_dbt/__main__.py +250 -15
- sqlassert_dbt/connect.py +135 -0
- sqlassert_dbt/jinja.py +130 -0
- sqlassert_dbt/manifest.py +56 -2
- sqlassert_dbt/program.py +611 -158
- sqlassert_dbt/project.py +324 -42
- sqlassert_dbt/report.py +114 -4
- {sqlassert_dbt-0.3.1.dist-info → sqlassert_dbt-0.3.3.dist-info}/METADATA +108 -2
- sqlassert_dbt-0.3.3.dist-info/RECORD +15 -0
- sqlassert_dbt-0.3.1.dist-info/RECORD +0 -14
- {sqlassert_dbt-0.3.1.dist-info → sqlassert_dbt-0.3.3.dist-info}/WHEEL +0 -0
- {sqlassert_dbt-0.3.1.dist-info → sqlassert_dbt-0.3.3.dist-info}/entry_points.txt +0 -0
- {sqlassert_dbt-0.3.1.dist-info → sqlassert_dbt-0.3.3.dist-info}/licenses/LICENSE +0 -0
- {sqlassert_dbt-0.3.1.dist-info → sqlassert_dbt-0.3.3.dist-info}/top_level.txt +0 -0
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. `
|
|
7
|
-
|
|
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",
|
|
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.
|
|
22
|
-
from sqlassert_dbt.
|
|
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
|
-
|
|
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(
|
|
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
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
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())
|
sqlassert_dbt/connect.py
ADDED
|
@@ -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
|
sqlassert_dbt/jinja.py
CHANGED
|
@@ -181,3 +181,133 @@ def _condition(text: str, incremental: bool) -> bool:
|
|
|
181
181
|
return not incremental
|
|
182
182
|
case _:
|
|
183
183
|
raise Unrenderable(f"{{% if {text} %}} is not is_incremental()")
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
# Statements that open a block, closed by `end` + the keyword. `set` opens one
|
|
187
|
+
# only without `=` (`{% set x %}...{% endset %}`).
|
|
188
|
+
_BLOCKS = frozenset({"for", "if", "macro", "call", "filter", "raw", "set", "block"})
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def align(raw: str, compiled: str, *, incremental: bool) -> tuple[int, ...] | None:
|
|
192
|
+
"""For each character of `compiled` (dbt's rendering of `raw`), the
|
|
193
|
+
raw-code offset it came from: copied text maps to itself, and text a tag
|
|
194
|
+
wrote (a macro call, a loop, a `{% set %}`) to the tag's first character,
|
|
195
|
+
whatever it wrote. None when `raw`'s text between tags does not appear in
|
|
196
|
+
`compiled` in order.
|
|
197
|
+
|
|
198
|
+
Unlike `render`, any tag is allowed: its output is not rendered but taken
|
|
199
|
+
from `compiled`, so it says only where text came from, never what text is.
|
|
200
|
+
`{% if [not] is_incremental() %}` follows `incremental`; any other block is
|
|
201
|
+
one tag, from its opening to its closing tag."""
|
|
202
|
+
try:
|
|
203
|
+
pieces = _pieces(raw, incremental)
|
|
204
|
+
except Unrenderable:
|
|
205
|
+
return None
|
|
206
|
+
sources: list[int] = []
|
|
207
|
+
cursor = 0
|
|
208
|
+
hole: int | None = None
|
|
209
|
+
for index, piece in enumerate(pieces):
|
|
210
|
+
if isinstance(piece, int):
|
|
211
|
+
hole = piece if hole is None else hole
|
|
212
|
+
continue
|
|
213
|
+
text = "".join(raw[i] for i in piece)
|
|
214
|
+
if index == len(pieces) - 1:
|
|
215
|
+
text = text.rstrip().rstrip(";").rstrip()
|
|
216
|
+
piece = piece[:len(text)]
|
|
217
|
+
if not text:
|
|
218
|
+
continue
|
|
219
|
+
if hole is None:
|
|
220
|
+
found = cursor if compiled.startswith(text, cursor) else -1
|
|
221
|
+
elif index == len(pieces) - 1:
|
|
222
|
+
found = len(compiled) - len(text) if compiled.endswith(text) and len(compiled) - len(text) >= cursor else -1
|
|
223
|
+
else:
|
|
224
|
+
found = compiled.find(text, cursor)
|
|
225
|
+
if found < 0:
|
|
226
|
+
return None
|
|
227
|
+
sources.extend([hole] * (found - cursor) if hole is not None else [])
|
|
228
|
+
sources.extend(piece)
|
|
229
|
+
cursor, hole = found + len(text), None
|
|
230
|
+
if hole is not None:
|
|
231
|
+
sources.extend([hole] * (len(compiled) - cursor))
|
|
232
|
+
elif cursor != len(compiled):
|
|
233
|
+
return None
|
|
234
|
+
return tuple(sources)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _pieces(raw: str, incremental: bool) -> list[range | list[int] | int]:
|
|
238
|
+
"""`raw` as the data it copies (raw offsets) and its tags (each as its offset)."""
|
|
239
|
+
pieces: list[range | list[int] | int] = []
|
|
240
|
+
branches: list[bool] = []
|
|
241
|
+
strip_next = False
|
|
242
|
+
position = 0
|
|
243
|
+
while True:
|
|
244
|
+
start = _next_tag(raw, position)
|
|
245
|
+
data_end = len(raw) if start < 0 else start
|
|
246
|
+
left_strip = start >= 0 and raw.startswith("-", start + 2)
|
|
247
|
+
data = range(position, data_end)
|
|
248
|
+
if strip_next:
|
|
249
|
+
data = range(_skip_space(raw, position, data_end), data_end)
|
|
250
|
+
if left_strip:
|
|
251
|
+
data = range(data.start, _trim_space(raw, data.start, data.stop))
|
|
252
|
+
if all(branches) and len(data):
|
|
253
|
+
pieces.append(list(data))
|
|
254
|
+
if start < 0:
|
|
255
|
+
break
|
|
256
|
+
opener = raw[start:start + 2]
|
|
257
|
+
end = _tag_end(raw, start, _CLOSERS[opener])
|
|
258
|
+
body = raw[start + 2:end].removeprefix("-")
|
|
259
|
+
strip_next = body.endswith("-")
|
|
260
|
+
body = body.removesuffix("-").strip()
|
|
261
|
+
position = end + 2
|
|
262
|
+
if opener == "{#":
|
|
263
|
+
continue
|
|
264
|
+
if opener == "{{":
|
|
265
|
+
if all(branches):
|
|
266
|
+
pieces.append(start)
|
|
267
|
+
continue
|
|
268
|
+
keyword, _, rest = body.partition(" ")
|
|
269
|
+
if keyword == "if":
|
|
270
|
+
try:
|
|
271
|
+
branches.append(_condition(rest.strip(), incremental))
|
|
272
|
+
continue
|
|
273
|
+
except Unrenderable:
|
|
274
|
+
pass
|
|
275
|
+
elif keyword == "else" and branches and not rest.strip():
|
|
276
|
+
branches[-1] = not branches[-1]
|
|
277
|
+
continue
|
|
278
|
+
elif keyword == "endif" and branches and not rest.strip():
|
|
279
|
+
branches.pop()
|
|
280
|
+
continue
|
|
281
|
+
elif keyword in {"elif", "else", "endif"}:
|
|
282
|
+
raise Unrenderable(f"{{% {body} %}} inside an is_incremental() branch")
|
|
283
|
+
if keyword in _BLOCKS and not (keyword == "set" and "=" in rest):
|
|
284
|
+
position, strip_next = _block_end(raw, position, keyword)
|
|
285
|
+
if all(branches):
|
|
286
|
+
pieces.append(start)
|
|
287
|
+
if branches:
|
|
288
|
+
raise Unrenderable("an {% if %} is never closed")
|
|
289
|
+
return pieces
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _block_end(raw: str, position: int, keyword: str) -> tuple[int, bool]:
|
|
293
|
+
"""Past the tag closing a `keyword` block whose body starts at `position`,
|
|
294
|
+
and whether that tag strips the space after it."""
|
|
295
|
+
depth = 1
|
|
296
|
+
while True:
|
|
297
|
+
start = _next_tag(raw, position)
|
|
298
|
+
if start < 0:
|
|
299
|
+
raise Unrenderable(f"a {{% {keyword} %}} is never closed")
|
|
300
|
+
opener = raw[start:start + 2]
|
|
301
|
+
end = _tag_end(raw, start, _CLOSERS[opener])
|
|
302
|
+
position = end + 2
|
|
303
|
+
if opener != "{%":
|
|
304
|
+
continue
|
|
305
|
+
body = raw[start + 2:end].removeprefix("-")
|
|
306
|
+
strip = body.endswith("-")
|
|
307
|
+
word, _, rest = body.removesuffix("-").strip().partition(" ")
|
|
308
|
+
if word == keyword and not (word == "set" and "=" in rest):
|
|
309
|
+
depth += 1
|
|
310
|
+
elif word == f"end{keyword}":
|
|
311
|
+
depth -= 1
|
|
312
|
+
if depth == 0:
|
|
313
|
+
return position, strip
|