dbt-s-layer 1.0.0__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.
@@ -0,0 +1,3 @@
1
+ """dbt Cloud semantic-layer features for dbt Core / Fusion users."""
2
+
3
+ __all__: list[str] = []
@@ -0,0 +1,8 @@
1
+ """Entry point for `python -m dbt_s_layer`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dbt_s_layer.cli import app
6
+
7
+ if __name__ == "__main__":
8
+ app()
@@ -0,0 +1,148 @@
1
+ """
2
+ The `generate` and `check` commands (CLI-01, CLI-02, CLI-04).
3
+
4
+ Both load the project through `check_artifacts` (CLI-05), pick the SQL dialect,
5
+ render every generated file in memory, and then either write it (`generate`) or
6
+ compare it with the output directory (`check`).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import sys
12
+ from dataclasses import dataclass
13
+ from typing import TYPE_CHECKING
14
+
15
+ from dbt_s_layer._paths import resolve_output_dir
16
+ from dbt_s_layer.errors import ArtifactIncompleteError, DbtSLayerError
17
+ from dbt_s_layer.output import apply_output, diff_output, project_model_paths, render_output
18
+ from dbt_s_layer.profiles import adapter_for_target
19
+ from dbt_s_layer.staleness import check_artifacts
20
+
21
+ if TYPE_CHECKING:
22
+ from pathlib import Path
23
+
24
+ from dbt_s_layer.output import OutputDiff, RenderedOutput
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class Options:
29
+ """What `generate` and `check` share."""
30
+
31
+ project_dir: Path
32
+ output_dir: Path
33
+ target: str | None = None
34
+ adapter: str | None = None
35
+ profiles_dir: Path | None = None
36
+ # Refuse to write when the engine that wrote semantic_manifest.json left out a
37
+ # declared semantic model, instead of warning: the pre-commit hook would
38
+ # otherwise remove its files.
39
+ missing_is_error: bool = False
40
+
41
+
42
+ def _out(message: str) -> None:
43
+ print(message, file=sys.stdout)
44
+
45
+
46
+ def _err(message: str) -> None:
47
+ print(message, file=sys.stderr)
48
+
49
+
50
+ def _render(options: Options) -> tuple[RenderedOutput, Path]:
51
+ checked = check_artifacts(options.project_dir)
52
+ refused = checked.dropped if options.missing_is_error else ()
53
+ for warning in checked.warnings:
54
+ if warning not in refused:
55
+ _err(f"WARN {warning}")
56
+ if refused:
57
+ raise ArtifactIncompleteError(
58
+ "; ".join(refused) + ". Nothing was written, so no generated file is removed "
59
+ "for it; parse the project with an engine that reads it."
60
+ )
61
+ project = checked.project
62
+ output_dir = resolve_output_dir(project.project_dir, options.output_dir)
63
+ model_paths = project_model_paths(project.project_dir)
64
+ if not any(output_dir.is_relative_to(p) for p in model_paths):
65
+ shown = ", ".join(str(p) for p in model_paths)
66
+ _err(
67
+ f"WARN output directory {output_dir} is not under the project's model-paths "
68
+ f"({shown}), so dbt will not build the generated models."
69
+ )
70
+ adapter = options.adapter
71
+ if adapter is None and options.target is not None:
72
+ adapter = adapter_for_target(
73
+ project.project_dir, options.target, profiles_dir=options.profiles_dir
74
+ )
75
+ files = render_output(project, adapter=adapter, output_dir=output_dir)
76
+ for warning in files.warnings:
77
+ _err(f"WARN {warning}")
78
+ return files, output_dir
79
+
80
+
81
+ def _count(n: int) -> str:
82
+ return f"{n} file{'' if n == 1 else 's'}"
83
+
84
+
85
+ def _summary(diff: OutputDiff) -> str:
86
+ parts = [
87
+ f"{len(names)} {label}"
88
+ for names, label in (
89
+ (diff.missing, "new"),
90
+ (diff.changed, "changed"),
91
+ (diff.stale, "removed"),
92
+ )
93
+ if names
94
+ ]
95
+ return ", ".join(parts)
96
+
97
+
98
+ def generate_project(options: Options) -> tuple[Path, OutputDiff] | None:
99
+ """
100
+ Write the generated files and print the summary line.
101
+
102
+ Return the output directory and what changed, or None after printing an error.
103
+ """
104
+ try:
105
+ files, output_dir = _render(options)
106
+ diff = apply_output(files, output_dir)
107
+ except DbtSLayerError as exc:
108
+ _err(f"ERROR: {exc}")
109
+ return None
110
+ except OSError as exc:
111
+ _err(f"ERROR: could not write to the output directory: {exc}")
112
+ return None
113
+ if diff.clean:
114
+ _out(f"{output_dir} is up to date ({_count(len(files))}).")
115
+ else:
116
+ _out(f"Generated {_count(len(files))} in {output_dir} ({_summary(diff)}).")
117
+ return output_dir, diff
118
+
119
+
120
+ def run_generate(options: Options) -> int:
121
+ """Write the generated files; return the exit code."""
122
+ return 1 if generate_project(options) is None else 0
123
+
124
+
125
+ def run_check(options: Options) -> int:
126
+ """Compare the output directory with a fresh render; return 1 when they differ."""
127
+ try:
128
+ files, output_dir = _render(options)
129
+ diff = diff_output(files, output_dir)
130
+ except DbtSLayerError as exc:
131
+ _err(f"ERROR: {exc}")
132
+ return 1
133
+ except OSError as exc:
134
+ _err(f"ERROR: could not read the output directory: {exc}")
135
+ return 1
136
+ if diff.clean:
137
+ _out(f"{output_dir} is up to date ({_count(len(files))}).")
138
+ return 0
139
+ _out(f"{output_dir} is out of date:")
140
+ for label, names in (
141
+ ("changed", diff.changed),
142
+ ("missing", diff.missing),
143
+ ("stale", diff.stale),
144
+ ):
145
+ for name in names:
146
+ _out(f" {label}: {name}")
147
+ _out("Run `dbt-s-layer generate` with the same options to update it.")
148
+ return 1
dbt_s_layer/_doctor.py ADDED
@@ -0,0 +1,314 @@
1
+ """
2
+ Environment diagnostics for dbt-s-layer.
3
+
4
+ Phase 0 scope (per CONTEXT.md, revised at the Phase 0 close-out):
5
+ - Detects a dbt engine that can write `semantic_manifest.json`: dbt Fusion
6
+ (as `dbtf`, or as `dbt` 2.x, which is how the Fusion installer names it) or
7
+ dbt Core >= 1.7. dbt Core 1.12 parses both the legacy and the new YAML spec;
8
+ Fusion only parses the new one.
9
+ - Reports installed `metricflow` version via `importlib.metadata.version`
10
+
11
+ With `--project-dir` (Phase 1): checks the project's parse artifacts exist, load,
12
+ and are newer than its semantic YAML (CLI-05), and warns about semantic models
13
+ the engine left out.
14
+
15
+ With `--project-dir` or `--output-dir` (Phase 3): checks the output directory
16
+ (default `models/semantic` under the project) can be written, along with the
17
+ parent directory `generate` stages files in.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import os
23
+ import re
24
+ import shutil
25
+ import subprocess
26
+ import sys
27
+ from dataclasses import dataclass
28
+ from importlib.metadata import PackageNotFoundError, version
29
+ from pathlib import Path
30
+ from typing import Literal
31
+
32
+ FUSION_INSTALL_URL = "https://docs.getdbt.com/docs/fusion/install-fusion"
33
+ DBT_CORE_INSTALL_URL = "https://docs.getdbt.com/docs/core/installation-overview"
34
+
35
+ # dbt Core gained semantic_manifest.json in 1.7 (semantic models GA).
36
+ MIN_DBT_CORE_VERSION = (1, 7, 0)
37
+ _VERSION_TIMEOUT_SECONDS = 30
38
+
39
+ # Stable and dev Fusion builds print `dbt 2.0.8`; preview builds print
40
+ # `dbt-fusion 2.0.0-preview.212`.
41
+ _FUSION_RE = re.compile(r"^dbt(?:-fusion)? (\d+)\.(\d+)\.(\d+)", re.MULTILINE)
42
+ _CORE_RE = re.compile(r"^Core:\s*\n\s*-\s*installed:\s*(\d+)\.(\d+)\.(\d+)", re.MULTILINE)
43
+ # dbt Core before 1.0 printed `installed version: 0.21.0`.
44
+ _CORE_PRE_1_0_RE = re.compile(r"^installed version:\s*(\d+)\.(\d+)\.(\d+)", re.MULTILINE)
45
+
46
+ EngineKind = Literal["Fusion", "dbt Core"]
47
+
48
+
49
+ class VersionProbeError(Exception):
50
+ """`<binary> --version` could not be run or did not succeed."""
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class Engine:
55
+ """A dbt engine found on PATH."""
56
+
57
+ kind: EngineKind
58
+ version: tuple[int, int, int]
59
+ path: str
60
+
61
+ @property
62
+ def label(self) -> str:
63
+ """Human-readable name and version, e.g. `Fusion 2.0.8`."""
64
+ return f"{self.kind} {'.'.join(map(str, self.version))}"
65
+
66
+ @property
67
+ def supported(self) -> bool:
68
+ """Whether this engine can write a usable semantic_manifest.json."""
69
+ return self.kind == "Fusion" or self.version >= MIN_DBT_CORE_VERSION
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class Rejected:
74
+ """A `dbtf`/`dbt` on PATH that is not a usable engine, and why."""
75
+
76
+ path: str
77
+ reason: str
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class Detection:
82
+ """Everything `detect_engines` found on PATH."""
83
+
84
+ engines: tuple[Engine, ...]
85
+ rejected: tuple[Rejected, ...]
86
+
87
+
88
+ def _version_tuple(match: re.Match[str]) -> tuple[int, int, int]:
89
+ major, minor, patch = (int(g) for g in match.groups())
90
+ return (major, minor, patch)
91
+
92
+
93
+ def parse_engine_version(output: str, path: str) -> Engine | None:
94
+ """Classify `<binary> --version` output as Fusion or dbt Core, or None."""
95
+ fusion = _FUSION_RE.search(output)
96
+ if fusion is not None and int(fusion.group(1)) >= 2:
97
+ return Engine("Fusion", _version_tuple(fusion), path)
98
+ for pattern in (_CORE_RE, _CORE_PRE_1_0_RE):
99
+ core = pattern.search(output)
100
+ if core is not None:
101
+ return Engine("dbt Core", _version_tuple(core), path)
102
+ return None
103
+
104
+
105
+ def _version_output(path: str) -> str:
106
+ """Return `<path> --version` stdout, raising VersionProbeError on any failure."""
107
+ try:
108
+ result = subprocess.run(
109
+ [path, "--version"],
110
+ capture_output=True,
111
+ text=True,
112
+ timeout=_VERSION_TIMEOUT_SECONDS,
113
+ check=False,
114
+ )
115
+ except subprocess.TimeoutExpired as exc:
116
+ raise VersionProbeError(f"`--version` timed out after {_VERSION_TIMEOUT_SECONDS}s") from exc
117
+ except OSError as exc:
118
+ raise VersionProbeError(f"could not run it ({exc})") from exc
119
+ if result.returncode != 0:
120
+ raise VersionProbeError(f"`--version` exited with code {result.returncode}")
121
+ return result.stdout
122
+
123
+
124
+ def detect_engines() -> Detection:
125
+ """Find every dbt engine on PATH, checking `dbtf` then `dbt`."""
126
+ engines: list[Engine] = []
127
+ rejected: list[Rejected] = []
128
+ seen: set[str] = set()
129
+ for name in ("dbtf", "dbt"):
130
+ path = shutil.which(name)
131
+ if path is None:
132
+ continue
133
+ real = os.path.realpath(path)
134
+ if real in seen:
135
+ continue
136
+ seen.add(real)
137
+ try:
138
+ output = _version_output(path)
139
+ except VersionProbeError as exc:
140
+ rejected.append(Rejected(path, str(exc)))
141
+ continue
142
+ engine = parse_engine_version(output, path)
143
+ if engine is None:
144
+ first_line = output.strip().splitlines()[0] if output.strip() else "(no output)"
145
+ rejected.append(
146
+ Rejected(path, f"it is not dbt Fusion or dbt Core (`--version`: {first_line})")
147
+ )
148
+ else:
149
+ engines.append(engine)
150
+ return Detection(tuple(engines), tuple(rejected))
151
+
152
+
153
+ def _check_project(project_dir: Path) -> int:
154
+ """Print the artifact check for `project_dir`; return 1 if it failed, else 0."""
155
+ from dbt_s_layer.errors import DbtSLayerError
156
+ from dbt_s_layer.staleness import check_artifacts
157
+
158
+ try:
159
+ result = check_artifacts(project_dir)
160
+ except DbtSLayerError as exc:
161
+ print(f"ERROR artifacts: {exc}", file=sys.stdout)
162
+ return 1
163
+ print(f"OK artifacts: fresh ({result.project.producer})", file=sys.stdout)
164
+ for warning in result.warnings:
165
+ print(f"WARN {warning}", file=sys.stdout)
166
+ manifest = result.project.dbt_manifest
167
+ if manifest.metadata.adapter_type == "snowflake":
168
+ from dbt_s_layer import snowflake
169
+
170
+ if snowflake.MATERIALIZATION_MACRO in manifest.macros:
171
+ print(f"OK {snowflake.PACKAGE}: installed", file=sys.stdout)
172
+ else:
173
+ print(
174
+ f"WARN {snowflake.PACKAGE}: not installed, so `dbt run` fails on the generated "
175
+ f"sem__ models. Add Snowflake-Labs/{snowflake.PACKAGE} to packages.yml and run "
176
+ "`dbt deps`.",
177
+ file=sys.stdout,
178
+ )
179
+ if manifest.metadata.adapter_type == "databricks":
180
+ from dbt_s_layer import databricks
181
+
182
+ if databricks.MATERIALIZATION_MACRO in manifest.macros:
183
+ print("OK dbt-databricks metric views: installed", file=sys.stdout)
184
+ else:
185
+ print(
186
+ "WARN dbt-databricks metric views: no metric_view materialization, so `dbt run` "
187
+ "fails on the generated sem__ models. Install dbt-databricks >= 1.12.0.",
188
+ file=sys.stdout,
189
+ )
190
+ if manifest.metadata.adapter_type == "duckdb":
191
+ from dbt_s_layer import duckdb_views
192
+
193
+ if duckdb_views.MATERIALIZATION_MACRO in manifest.macros:
194
+ print(f"OK {duckdb_views.PACKAGE}: installed", file=sys.stdout)
195
+ else:
196
+ print(
197
+ f"WARN {duckdb_views.PACKAGE}: not installed, so `dbt run` fails on the "
198
+ f"generated sem__ models. Add {duckdb_views.REPOSITORY} to packages.yml and run "
199
+ "`dbt deps`.",
200
+ file=sys.stdout,
201
+ )
202
+ return 0
203
+
204
+
205
+ def _check_output_dir(output_dir: Path) -> int:
206
+ """Print whether `generate` could write `output_dir`; return 1 if not, else 0."""
207
+ if output_dir.exists() and not output_dir.is_dir():
208
+ print(f"ERROR output directory: {output_dir} is not a directory", file=sys.stdout)
209
+ return 1
210
+ # `generate` stages files beside the output directory, then moves them in.
211
+ needed = [output_dir, output_dir.parent] if output_dir.exists() else [output_dir.parent]
212
+ existing = [p for p in needed if p.exists()]
213
+ if not existing:
214
+ ancestor = output_dir.parent
215
+ while not ancestor.exists():
216
+ ancestor = ancestor.parent
217
+ existing = [ancestor]
218
+ for path in existing:
219
+ if not path.is_dir() or not os.access(path, os.W_OK | os.X_OK):
220
+ print(
221
+ f"ERROR output directory: {path} is not writable, so `generate` cannot "
222
+ f"write {output_dir}",
223
+ file=sys.stdout,
224
+ )
225
+ return 1
226
+ if output_dir.exists():
227
+ print(f"OK output directory: {output_dir} is writable", file=sys.stdout)
228
+ else:
229
+ print(
230
+ f"OK output directory: {output_dir} does not exist yet; `generate` will "
231
+ f"create it in {existing[0]}",
232
+ file=sys.stdout,
233
+ )
234
+ return 0
235
+
236
+
237
+ def run_doctor(project_dir: Path | None = None, output_dir: Path | None = None) -> int:
238
+ """
239
+ Report environment diagnostics and return an exit code.
240
+
241
+ With `project_dir`, also check that project's parse artifacts. With
242
+ `project_dir` or `output_dir`, also check the output directory (relative to
243
+ the project, or to the working directory without one).
244
+
245
+ Exit codes:
246
+ 0 - all checks passed (a supported dbt engine AND metricflow importable,
247
+ and, with `project_dir`, fresh artifacts; warnings do not fail)
248
+ 1 - no supported dbt engine (blocking; user must install Fusion or dbt Core),
249
+ or the project's artifacts are missing, stale or unreadable, or the
250
+ output directory cannot be written
251
+ 2 - metricflow package not installed (dbt-s-layer install is broken)
252
+
253
+ When multiple checks fail, the higher-severity code wins (2 > 1 > 0).
254
+ """
255
+ exit_code = 0
256
+
257
+ found = detect_engines()
258
+ for engine in found.engines:
259
+ if engine.supported:
260
+ print(f"OK dbt engine: {engine.label} at {engine.path}", file=sys.stdout)
261
+ else:
262
+ print(
263
+ f"WARN dbt engine: {engine.label} at {engine.path} is too old "
264
+ "(dbt-s-layer needs dbt Core >= 1.7 or dbt Fusion)",
265
+ file=sys.stdout,
266
+ )
267
+ for rejected in found.rejected:
268
+ print(f"WARN found {rejected.path} but {rejected.reason}", file=sys.stdout)
269
+
270
+ supported = [e for e in found.engines if e.supported]
271
+ if not supported:
272
+ print(
273
+ "ERROR: no supported dbt engine found on PATH (looked for `dbtf` and `dbt`).",
274
+ file=sys.stdout,
275
+ )
276
+ print(f"Install dbt Fusion: {FUSION_INSTALL_URL}", file=sys.stdout)
277
+ print(f"Or dbt Core >= 1.7: {DBT_CORE_INSTALL_URL}", file=sys.stdout)
278
+ exit_code = max(exit_code, 1)
279
+ elif all(e.kind == "Fusion" for e in supported):
280
+ print(
281
+ "NOTE Fusion only parses the new YAML spec. Legacy-spec projects "
282
+ f"(`semantic_models:` with `measures:`) need dbt Core >= 1.7: {DBT_CORE_INSTALL_URL}",
283
+ file=sys.stdout,
284
+ )
285
+
286
+ metricflow_ok = True
287
+ try:
288
+ mf_version = version("metricflow")
289
+ print(f"OK metricflow version: {mf_version}", file=sys.stdout)
290
+ except PackageNotFoundError:
291
+ metricflow_ok = False
292
+ print(
293
+ "ERROR: metricflow is not installed (dbt-s-layer install is broken).",
294
+ file=sys.stdout,
295
+ )
296
+ exit_code = max(exit_code, 2)
297
+
298
+ if project_dir is not None:
299
+ if metricflow_ok:
300
+ exit_code = max(exit_code, _check_project(project_dir))
301
+ else:
302
+ # Loading the artifacts needs metricflow.
303
+ print(
304
+ "SKIP artifacts: not checked because metricflow is not installed", file=sys.stdout
305
+ )
306
+
307
+ if project_dir is not None or output_dir is not None:
308
+ from dbt_s_layer._paths import DEFAULT_OUTPUT_DIR, resolve_output_dir
309
+
310
+ base = project_dir if project_dir is not None else Path.cwd()
311
+ resolved = resolve_output_dir(base.resolve(), output_dir or DEFAULT_OUTPUT_DIR)
312
+ exit_code = max(exit_code, _check_output_dir(resolved))
313
+
314
+ return exit_code