sqllocks-shape-dbt 0.9.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.
- sqllocks_shape_dbt-0.9.1/LICENSE +21 -0
- sqllocks_shape_dbt-0.9.1/PKG-INFO +52 -0
- sqllocks_shape_dbt-0.9.1/README.md +28 -0
- sqllocks_shape_dbt-0.9.1/pyproject.toml +43 -0
- sqllocks_shape_dbt-0.9.1/setup.cfg +4 -0
- sqllocks_shape_dbt-0.9.1/src/shape_dbt/__init__.py +21 -0
- sqllocks_shape_dbt-0.9.1/src/shape_dbt/commands.py +374 -0
- sqllocks_shape_dbt-0.9.1/src/shape_dbt/fromdbt.py +363 -0
- sqllocks_shape_dbt-0.9.1/src/shape_dbt/project.py +314 -0
- sqllocks_shape_dbt-0.9.1/src/shape_dbt/report.py +258 -0
- sqllocks_shape_dbt-0.9.1/src/shape_dbt/seeds.py +277 -0
- sqllocks_shape_dbt-0.9.1/src/shape_dbt/totests.py +680 -0
- sqllocks_shape_dbt-0.9.1/src/sqllocks_shape_dbt.egg-info/PKG-INFO +52 -0
- sqllocks_shape_dbt-0.9.1/src/sqllocks_shape_dbt.egg-info/SOURCES.txt +22 -0
- sqllocks_shape_dbt-0.9.1/src/sqllocks_shape_dbt.egg-info/dependency_links.txt +1 -0
- sqllocks_shape_dbt-0.9.1/src/sqllocks_shape_dbt.egg-info/entry_points.txt +8 -0
- sqllocks_shape_dbt-0.9.1/src/sqllocks_shape_dbt.egg-info/requires.txt +2 -0
- sqllocks_shape_dbt-0.9.1/src/sqllocks_shape_dbt.egg-info/top_level.txt +1 -0
- sqllocks_shape_dbt-0.9.1/tests/test_dbt_build.py +264 -0
- sqllocks_shape_dbt-0.9.1/tests/test_from_dbt.py +410 -0
- sqllocks_shape_dbt-0.9.1/tests/test_report.py +263 -0
- sqllocks_shape_dbt-0.9.1/tests/test_seeds.py +243 -0
- sqllocks_shape_dbt-0.9.1/tests/test_skeleton.py +30 -0
- sqllocks_shape_dbt-0.9.1/tests/test_to_dbt_tests.py +391 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025-2026 SQLLocks (Jonathan Stewart)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sqllocks-shape-dbt
|
|
3
|
+
Version: 0.9.1
|
|
4
|
+
Summary: Shape plugin: dbt integration (import a dbt project, compile contracts to dbt tests, dbt seeds sink)
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/sqllocks/shape
|
|
7
|
+
Project-URL: Repository, https://github.com/sqllocks/shape
|
|
8
|
+
Project-URL: Issues, https://github.com/sqllocks/shape/issues
|
|
9
|
+
Project-URL: Documentation, https://github.com/sqllocks/shape/tree/main/plugins/shape-dbt
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Topic :: Database
|
|
18
|
+
Requires-Python: >=3.11
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Requires-Dist: sqllocks-shape==0.9.1
|
|
22
|
+
Requires-Dist: pyyaml>=6
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# sqllocks-shape-dbt
|
|
26
|
+
|
|
27
|
+
Shape plugin: dbt integration. File-based and dbt-Core-generic: it reads and writes dbt's files and
|
|
28
|
+
never imports or runs dbt (`dbt-core` is not a dependency).
|
|
29
|
+
|
|
30
|
+
```
|
|
31
|
+
pip install sqllocks-shape-dbt
|
|
32
|
+
|
|
33
|
+
shape from-dbt my_dbt_project -o shop.gen.json # a dbt project as a generation schema
|
|
34
|
+
shape to-dbt-tests contract.json --model orders -o models/_shape_tests.yml
|
|
35
|
+
shape dbt-seeds shop.gen.json --project my_dbt_project # generated data as dbt seeds
|
|
36
|
+
shape dbt-report --run-results target/run_results.json --manifest target/manifest.json
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
| Entry point | Name | |
|
|
40
|
+
|---|---|---|
|
|
41
|
+
| `shape.commands` | `from-dbt` | `manifest.json`, `schema.yml` or `sources.yml` to a generation schema: `unique` and `not_null` give keys, `relationships` give foreign keys, `accepted_values` give enums, `data_type` gives types (decimal precision and scale too) |
|
|
42
|
+
| `shape.commands` | `to-dbt-tests` | a v1 contract or a profile to `schema.yml` data tests (`dbt_utils`, `dbt_expectations`), with `--merge` into an existing file |
|
|
43
|
+
| `shape.commands` | `dbt-seeds` | generate a schema's tables as `seeds/*.csv` with a `seeds:` block of column types |
|
|
44
|
+
| `shape.commands` | `dbt-report` | one report for a dbt run (`run_results.json`, `manifest.json`) and a Shape check and drift comparison |
|
|
45
|
+
| `shape.sinks` | `dbt-seeds` | `dbt://PROJECT_DIR`: one table as a seed |
|
|
46
|
+
|
|
47
|
+
Everything is described in [docs/DBT.md](../../docs/DBT.md): the mapping tables, what dbt tests
|
|
48
|
+
cannot express, seed size guidance, and the Fabric pipeline pattern. A runnable sample project
|
|
49
|
+
is in `examples/dbt_jaffle_shop`.
|
|
50
|
+
|
|
51
|
+
Tests: `pytest -m "not dbt" plugins/shape-dbt/tests`; with `dbt-duckdb` installed,
|
|
52
|
+
`pytest -m dbt plugins/shape-dbt/tests` builds the sample against DuckDB.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# sqllocks-shape-dbt
|
|
2
|
+
|
|
3
|
+
Shape plugin: dbt integration. File-based and dbt-Core-generic: it reads and writes dbt's files and
|
|
4
|
+
never imports or runs dbt (`dbt-core` is not a dependency).
|
|
5
|
+
|
|
6
|
+
```
|
|
7
|
+
pip install sqllocks-shape-dbt
|
|
8
|
+
|
|
9
|
+
shape from-dbt my_dbt_project -o shop.gen.json # a dbt project as a generation schema
|
|
10
|
+
shape to-dbt-tests contract.json --model orders -o models/_shape_tests.yml
|
|
11
|
+
shape dbt-seeds shop.gen.json --project my_dbt_project # generated data as dbt seeds
|
|
12
|
+
shape dbt-report --run-results target/run_results.json --manifest target/manifest.json
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
| Entry point | Name | |
|
|
16
|
+
|---|---|---|
|
|
17
|
+
| `shape.commands` | `from-dbt` | `manifest.json`, `schema.yml` or `sources.yml` to a generation schema: `unique` and `not_null` give keys, `relationships` give foreign keys, `accepted_values` give enums, `data_type` gives types (decimal precision and scale too) |
|
|
18
|
+
| `shape.commands` | `to-dbt-tests` | a v1 contract or a profile to `schema.yml` data tests (`dbt_utils`, `dbt_expectations`), with `--merge` into an existing file |
|
|
19
|
+
| `shape.commands` | `dbt-seeds` | generate a schema's tables as `seeds/*.csv` with a `seeds:` block of column types |
|
|
20
|
+
| `shape.commands` | `dbt-report` | one report for a dbt run (`run_results.json`, `manifest.json`) and a Shape check and drift comparison |
|
|
21
|
+
| `shape.sinks` | `dbt-seeds` | `dbt://PROJECT_DIR`: one table as a seed |
|
|
22
|
+
|
|
23
|
+
Everything is described in [docs/DBT.md](../../docs/DBT.md): the mapping tables, what dbt tests
|
|
24
|
+
cannot express, seed size guidance, and the Fabric pipeline pattern. A runnable sample project
|
|
25
|
+
is in `examples/dbt_jaffle_shop`.
|
|
26
|
+
|
|
27
|
+
Tests: `pytest -m "not dbt" plugins/shape-dbt/tests`; with `dbt-duckdb` installed,
|
|
28
|
+
`pytest -m dbt plugins/shape-dbt/tests` builds the sample against DuckDB.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "sqllocks-shape-dbt"
|
|
7
|
+
# Lockstep with core (T-09): scripts/check_plugin_skeletons.py fails when this drifts.
|
|
8
|
+
version = "0.9.1"
|
|
9
|
+
description = "Shape plugin: dbt integration (import a dbt project, compile contracts to dbt tests, dbt seeds sink)"
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
license = "MIT"
|
|
13
|
+
license-files = ["LICENSE"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
17
|
+
"Programming Language :: Python :: 3.11",
|
|
18
|
+
"Programming Language :: Python :: 3.12",
|
|
19
|
+
"Programming Language :: Python :: 3.13",
|
|
20
|
+
"Programming Language :: Python :: 3.14",
|
|
21
|
+
"Operating System :: OS Independent",
|
|
22
|
+
"Topic :: Database",
|
|
23
|
+
]
|
|
24
|
+
# dbt itself is not a dependency: the plugin reads and writes dbt's files and never runs dbt.
|
|
25
|
+
dependencies = ["sqllocks-shape==0.9.1", "pyyaml>=6"]
|
|
26
|
+
|
|
27
|
+
[project.urls]
|
|
28
|
+
Homepage = "https://github.com/sqllocks/shape"
|
|
29
|
+
Repository = "https://github.com/sqllocks/shape"
|
|
30
|
+
Issues = "https://github.com/sqllocks/shape/issues"
|
|
31
|
+
Documentation = "https://github.com/sqllocks/shape/tree/main/plugins/shape-dbt"
|
|
32
|
+
|
|
33
|
+
[project.entry-points."shape.commands"]
|
|
34
|
+
from-dbt = "shape_dbt:FromDbt"
|
|
35
|
+
to-dbt-tests = "shape_dbt:ToDbtTests"
|
|
36
|
+
dbt-seeds = "shape_dbt:DbtSeeds"
|
|
37
|
+
dbt-report = "shape_dbt:DbtReport"
|
|
38
|
+
|
|
39
|
+
[project.entry-points."shape.sinks"]
|
|
40
|
+
dbt-seeds = "shape_dbt:DbtSeedsSink"
|
|
41
|
+
|
|
42
|
+
[tool.setuptools.packages.find]
|
|
43
|
+
where = ["src"]
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Shape plugin: dbt.
|
|
2
|
+
|
|
3
|
+
File-based and dbt-Core-generic: nothing here imports or runs dbt.
|
|
4
|
+
|
|
5
|
+
* ``shape.commands``: ``from-dbt`` (a dbt project's sources, seeds or models and their tests as
|
|
6
|
+
a generation schema), ``to-dbt-tests`` (a contract or a profile as ``schema.yml`` data tests),
|
|
7
|
+
``dbt-seeds`` (generate a schema's tables as dbt seeds) and ``dbt-report`` (one report for a
|
|
8
|
+
dbt run and a Shape check and drift comparison).
|
|
9
|
+
|
|
10
|
+
* ``shape.sinks``: ``dbt-seeds`` writes a table as ``seeds/<table>.csv`` with a ``seeds:`` block
|
|
11
|
+
of column types (``dbt://PROJECT_DIR``).
|
|
12
|
+
|
|
13
|
+
PyYAML loads only when a ``schema.yml`` is read or written.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from .commands import DbtReport, DbtSeeds, FromDbt, ToDbtTests
|
|
17
|
+
from .seeds import DbtSeedsSink
|
|
18
|
+
|
|
19
|
+
SHAPE_API = "1.0"
|
|
20
|
+
|
|
21
|
+
__all__ = ["SHAPE_API", "DbtReport", "DbtSeeds", "DbtSeedsSink", "FromDbt", "ToDbtTests"]
|
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
"""The ``shape`` subcommands of the plugin (``shape.commands``): ``from-dbt``, ``to-dbt-tests``,
|
|
2
|
+
``dbt-seeds`` and ``dbt-report``. Exit codes follow Shape's: 0 success, 1 a failed check, 2 a
|
|
3
|
+
usage or input error."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _fail(message: str) -> int:
|
|
14
|
+
print(f"shape: error: {message}", file=sys.stderr)
|
|
15
|
+
return 2
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _write(path: Path, text: str) -> None:
|
|
19
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
20
|
+
path.write_text(text, encoding="utf-8", newline="\n")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _json(path: Path, doc: Any) -> None:
|
|
24
|
+
_write(path, json.dumps(doc, indent=2, ensure_ascii=False, default=str) + "\n")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _errors() -> tuple[type[Exception], ...]:
|
|
28
|
+
from shape.contracts.v1 import ContractError
|
|
29
|
+
from shape.errors import ShapeError
|
|
30
|
+
|
|
31
|
+
from .project import DbtProjectError
|
|
32
|
+
from .report import ReportError
|
|
33
|
+
from .seeds import SeedError
|
|
34
|
+
|
|
35
|
+
return (DbtProjectError, ReportError, SeedError, ContractError, ShapeError, OSError)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class _Guarded:
|
|
39
|
+
"""Runs the command and turns an input error into exit code 2 with a one-line message."""
|
|
40
|
+
|
|
41
|
+
name = ""
|
|
42
|
+
help = ""
|
|
43
|
+
|
|
44
|
+
def configure(self, parser: Any) -> None:
|
|
45
|
+
raise NotImplementedError
|
|
46
|
+
|
|
47
|
+
def execute(self, args: Any) -> int:
|
|
48
|
+
raise NotImplementedError
|
|
49
|
+
|
|
50
|
+
def run(self, args: Any) -> int:
|
|
51
|
+
try:
|
|
52
|
+
return self.execute(args)
|
|
53
|
+
except _errors() as exc:
|
|
54
|
+
return _fail(str(exc))
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class FromDbt(_Guarded):
|
|
58
|
+
name = "from-dbt"
|
|
59
|
+
help = "read a dbt project (manifest.json, schema.yml, sources.yml) into a generation schema"
|
|
60
|
+
|
|
61
|
+
def configure(self, parser: Any) -> None:
|
|
62
|
+
parser.description = (
|
|
63
|
+
"Reads sources, seeds and models with their tests: unique and not_null give keys, "
|
|
64
|
+
"relationships give foreign keys, accepted_values give weighted enums, and a model "
|
|
65
|
+
"contract's data_type gives the column type (decimal precision and scale included)."
|
|
66
|
+
)
|
|
67
|
+
parser.add_argument(
|
|
68
|
+
"inputs",
|
|
69
|
+
nargs="+",
|
|
70
|
+
metavar="PATH",
|
|
71
|
+
help="manifest.json, schema.yml or sources.yml files, or a dbt project directory",
|
|
72
|
+
)
|
|
73
|
+
parser.add_argument("-o", "--output", metavar="OUT", help="default: ./dbt_import.gen.json")
|
|
74
|
+
parser.add_argument("--domain", default="custom", help="domain name for the schema")
|
|
75
|
+
parser.add_argument(
|
|
76
|
+
"--select",
|
|
77
|
+
action="append",
|
|
78
|
+
choices=("source", "seed", "model"),
|
|
79
|
+
help="what to generate (repeatable); default: sources and seeds, else models",
|
|
80
|
+
)
|
|
81
|
+
parser.add_argument("-s", "--scale", metavar="SPEC", help="small:table1=N,table2=N")
|
|
82
|
+
parser.add_argument(
|
|
83
|
+
"--profile",
|
|
84
|
+
metavar="PROFILE.shape",
|
|
85
|
+
help="a profile whose value frequencies weight the accepted_values columns",
|
|
86
|
+
)
|
|
87
|
+
parser.add_argument("--no-smart", action="store_true", help="keep the first generators")
|
|
88
|
+
parser.add_argument("--explain", action="store_true", help="print what was inferred")
|
|
89
|
+
|
|
90
|
+
def execute(self, args: Any) -> int:
|
|
91
|
+
import shape
|
|
92
|
+
|
|
93
|
+
from .fromdbt import from_dbt, metadata
|
|
94
|
+
from .project import read_project
|
|
95
|
+
|
|
96
|
+
relations = read_project(args.inputs)
|
|
97
|
+
profile = shape.load(args.profile) if args.profile else None
|
|
98
|
+
schema, notes = from_dbt(
|
|
99
|
+
relations,
|
|
100
|
+
kinds=args.select,
|
|
101
|
+
domain=args.domain,
|
|
102
|
+
smart=not args.no_smart,
|
|
103
|
+
scale=args.scale,
|
|
104
|
+
profile=profile,
|
|
105
|
+
)
|
|
106
|
+
out = Path(args.output) if args.output else Path("dbt_import.gen.json")
|
|
107
|
+
_json(out, schema.to_dict())
|
|
108
|
+
meta_path = out.with_name(out.name.removesuffix(".json") + ".dbt-meta.json")
|
|
109
|
+
_json(meta_path, metadata(relations, schema))
|
|
110
|
+
print("Shape dbt import")
|
|
111
|
+
print()
|
|
112
|
+
print(f" Output: {out}")
|
|
113
|
+
print(f" Metadata: {meta_path}")
|
|
114
|
+
print(f" Tables: {len(schema.tables)}")
|
|
115
|
+
print(f" Relationships: {len(schema.relationships)}")
|
|
116
|
+
for name, table in sorted(schema.tables.items()):
|
|
117
|
+
pk = f" (PK: {', '.join(table.primary_key)})" if table.primary_key else ""
|
|
118
|
+
print(f" {name}: {len(table.columns)} columns{pk}")
|
|
119
|
+
text_notes = [n for n in notes if isinstance(n, str)]
|
|
120
|
+
for n in text_notes:
|
|
121
|
+
print(f" note: {n}")
|
|
122
|
+
if args.explain:
|
|
123
|
+
for n in notes:
|
|
124
|
+
if not isinstance(n, str):
|
|
125
|
+
col = f".{n.column}" if n.column else ""
|
|
126
|
+
print(f" [{n.rule_id}] {n.table}{col}: {n.description}")
|
|
127
|
+
return 0
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class ToDbtTests(_Guarded):
|
|
131
|
+
name = "to-dbt-tests"
|
|
132
|
+
help = "compile a contract or a profile into dbt schema.yml tests"
|
|
133
|
+
|
|
134
|
+
def configure(self, parser: Any) -> None:
|
|
135
|
+
parser.description = (
|
|
136
|
+
"Writes schema.yml data tests that run in a dbt job with no Python: not_null, "
|
|
137
|
+
"unique, accepted_values, dbt_utils.accepted_range and dbt_expectations tests. "
|
|
138
|
+
"Rules dbt cannot state (dtype, pattern, distribution) are kept as column meta."
|
|
139
|
+
)
|
|
140
|
+
parser.add_argument(
|
|
141
|
+
"source",
|
|
142
|
+
metavar="CONTRACT.json|PROFILE.shape",
|
|
143
|
+
help="a v1 contract, or a profile (a contract is captured from it)",
|
|
144
|
+
)
|
|
145
|
+
parser.add_argument("-o", "--output", metavar="schema.yml", required=True)
|
|
146
|
+
parser.add_argument("--model", help="the dbt model, for a contract of one table")
|
|
147
|
+
parser.add_argument(
|
|
148
|
+
"--kind",
|
|
149
|
+
choices=("models", "seeds", "sources"),
|
|
150
|
+
default="models",
|
|
151
|
+
help="default: models",
|
|
152
|
+
)
|
|
153
|
+
parser.add_argument(
|
|
154
|
+
"--source-name", default="raw", help="the dbt source, for --kind sources"
|
|
155
|
+
)
|
|
156
|
+
parser.add_argument(
|
|
157
|
+
"--tests-key",
|
|
158
|
+
choices=("data_tests", "tests"),
|
|
159
|
+
default="data_tests",
|
|
160
|
+
help="`tests` for dbt before 1.8",
|
|
161
|
+
)
|
|
162
|
+
parser.add_argument(
|
|
163
|
+
"--args-style",
|
|
164
|
+
choices=("arguments", "inline"),
|
|
165
|
+
default="arguments",
|
|
166
|
+
help="test arguments under `arguments:` (dbt 1.10+) or inline (every version)",
|
|
167
|
+
)
|
|
168
|
+
parser.add_argument(
|
|
169
|
+
"--distribution",
|
|
170
|
+
action="store_true",
|
|
171
|
+
help="from a profile: add mean, standard-deviation and quartile bound tests",
|
|
172
|
+
)
|
|
173
|
+
parser.add_argument(
|
|
174
|
+
"--margin", type=float, default=0.05, help="from a profile: widen min/max by this share"
|
|
175
|
+
)
|
|
176
|
+
parser.add_argument(
|
|
177
|
+
"--packages-out", metavar="packages.yml", help="also write the packages the tests need"
|
|
178
|
+
)
|
|
179
|
+
parser.add_argument(
|
|
180
|
+
"--merge",
|
|
181
|
+
metavar="schema.yml",
|
|
182
|
+
help="add the tests to the entries of this existing schema.yml (dbt allows one entry "
|
|
183
|
+
"per model; use -o with the same path to update it in place; comments are lost)",
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
def execute(self, args: Any) -> int:
|
|
187
|
+
from .totests import bounds_from_profile, compile_tests, contract_from_profile
|
|
188
|
+
|
|
189
|
+
src = Path(args.source)
|
|
190
|
+
bounds = None
|
|
191
|
+
if src.suffix == ".shape":
|
|
192
|
+
import shape
|
|
193
|
+
|
|
194
|
+
profile = shape.load(src)
|
|
195
|
+
contract = contract_from_profile(profile, margin=args.margin)
|
|
196
|
+
if args.distribution:
|
|
197
|
+
bounds = bounds_from_profile(profile)
|
|
198
|
+
model = args.model or getattr(profile, "name", None)
|
|
199
|
+
else:
|
|
200
|
+
try:
|
|
201
|
+
contract = json.loads(src.read_text(encoding="utf-8"))
|
|
202
|
+
except json.JSONDecodeError as exc:
|
|
203
|
+
return _fail(f"{src} is not valid JSON: {exc}")
|
|
204
|
+
if args.distribution:
|
|
205
|
+
return _fail("--distribution needs a profile (.shape), not a contract")
|
|
206
|
+
model = args.model
|
|
207
|
+
compiled = compile_tests(
|
|
208
|
+
contract,
|
|
209
|
+
model=model,
|
|
210
|
+
kind=args.kind,
|
|
211
|
+
source_name=args.source_name,
|
|
212
|
+
bounds=bounds,
|
|
213
|
+
tests_key=args.tests_key,
|
|
214
|
+
args_style=args.args_style,
|
|
215
|
+
)
|
|
216
|
+
out = Path(args.output)
|
|
217
|
+
if args.merge:
|
|
218
|
+
import yaml # type: ignore[import-untyped]
|
|
219
|
+
|
|
220
|
+
from .totests import merge_schema_docs, render_yaml
|
|
221
|
+
|
|
222
|
+
base = yaml.safe_load(Path(args.merge).read_text(encoding="utf-8")) or {}
|
|
223
|
+
merged = merge_schema_docs(base, compiled.doc, tests_key=args.tests_key)
|
|
224
|
+
_write(out, render_yaml(merged, compiled.packages))
|
|
225
|
+
else:
|
|
226
|
+
_write(out, compiled.yaml())
|
|
227
|
+
print(f"Wrote {out}")
|
|
228
|
+
if args.packages_out and compiled.packages:
|
|
229
|
+
_write(Path(args.packages_out), compiled.packages_yml())
|
|
230
|
+
print(f"Wrote {args.packages_out}")
|
|
231
|
+
elif compiled.packages:
|
|
232
|
+
print("These tests need dbt packages; add to packages.yml and run `dbt deps`:")
|
|
233
|
+
print(compiled.packages_yml())
|
|
234
|
+
for note in compiled.notes:
|
|
235
|
+
print(f" note: {note}")
|
|
236
|
+
return 0
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
class DbtSeeds(_Guarded):
|
|
240
|
+
name = "dbt-seeds"
|
|
241
|
+
help = "generate a schema's tables as CSV seeds in a dbt project"
|
|
242
|
+
|
|
243
|
+
def configure(self, parser: Any) -> None:
|
|
244
|
+
from .seeds import DIALECTS
|
|
245
|
+
|
|
246
|
+
parser.description = (
|
|
247
|
+
"Generates the tables and writes seeds/<table>.csv with a seeds: block that states "
|
|
248
|
+
"every column type (identifiers with leading zeros stay text). Seeds are for small, "
|
|
249
|
+
"static data: a file over 1 MiB is refused unless --allow-large."
|
|
250
|
+
)
|
|
251
|
+
parser.add_argument("schema", metavar="SCHEMA.gen.json", help="a generation schema")
|
|
252
|
+
parser.add_argument("--project", required=True, metavar="DIR", help="the dbt project")
|
|
253
|
+
parser.add_argument("--seeds-dir", default="seeds", help="default: seeds")
|
|
254
|
+
parser.add_argument("--scale", help="a scale preset of the schema")
|
|
255
|
+
parser.add_argument("--seed", type=int, help="the generation seed")
|
|
256
|
+
parser.add_argument("--rows", metavar="T=N,...", help="row counts per table")
|
|
257
|
+
parser.add_argument("--dialect", choices=sorted(DIALECTS), default="ansi")
|
|
258
|
+
parser.add_argument(
|
|
259
|
+
"--metadata", metavar="FILE", help="the .dbt-meta.json `from-dbt` wrote (descriptions)"
|
|
260
|
+
)
|
|
261
|
+
parser.add_argument("--allow-large", action="store_true", help="allow a file over 1 MiB")
|
|
262
|
+
|
|
263
|
+
def execute(self, args: Any) -> int:
|
|
264
|
+
from shape.generation.engine import Engine
|
|
265
|
+
from shape.generation.schema import GenSchema
|
|
266
|
+
|
|
267
|
+
from .seeds import DbtSeedsSink
|
|
268
|
+
|
|
269
|
+
try:
|
|
270
|
+
doc = json.loads(Path(args.schema).read_text(encoding="utf-8"))
|
|
271
|
+
except json.JSONDecodeError as exc:
|
|
272
|
+
return _fail(f"{args.schema} is not valid JSON: {exc}")
|
|
273
|
+
schema = GenSchema.from_dict(doc)
|
|
274
|
+
rows: dict[str, int] = {}
|
|
275
|
+
for pair in (args.rows or "").split(","):
|
|
276
|
+
if pair.strip():
|
|
277
|
+
name, _, count = pair.partition("=")
|
|
278
|
+
try:
|
|
279
|
+
rows[name.strip()] = int(count)
|
|
280
|
+
except ValueError:
|
|
281
|
+
return _fail(f"bad row count {pair!r}; use table=N")
|
|
282
|
+
meta: dict[str, Any] = {}
|
|
283
|
+
if args.metadata:
|
|
284
|
+
meta = json.loads(Path(args.metadata).read_text(encoding="utf-8")).get("tables", {})
|
|
285
|
+
result = Engine(schema, scale=args.scale, seed=args.seed, row_counts=rows).generate()
|
|
286
|
+
sink = DbtSeedsSink()
|
|
287
|
+
for name, table in result.tables.items():
|
|
288
|
+
columns = {
|
|
289
|
+
c.name: {
|
|
290
|
+
"type": c.type,
|
|
291
|
+
"precision": c.precision,
|
|
292
|
+
"scale": c.scale,
|
|
293
|
+
"max_length": c.max_length,
|
|
294
|
+
}
|
|
295
|
+
for c in schema.tables[name].columns.values()
|
|
296
|
+
}
|
|
297
|
+
described = meta.get(name, {})
|
|
298
|
+
count = sink.write(
|
|
299
|
+
args.project,
|
|
300
|
+
name,
|
|
301
|
+
table.to_batches() or [],
|
|
302
|
+
seeds_dir=args.seeds_dir,
|
|
303
|
+
columns=columns,
|
|
304
|
+
dialect=args.dialect,
|
|
305
|
+
allow_large=args.allow_large,
|
|
306
|
+
description=described.get("description") or schema.tables[name].description,
|
|
307
|
+
column_descriptions={
|
|
308
|
+
c: i.get("description", "") for c, i in described.get("columns", {}).items()
|
|
309
|
+
},
|
|
310
|
+
schema=table.schema,
|
|
311
|
+
)
|
|
312
|
+
print(f" {name}: {count:,} rows -> {args.seeds_dir}/{name}.csv")
|
|
313
|
+
print(f"Seeds written to {args.project}/{args.seeds_dir}; run `dbt seed` or `dbt build`")
|
|
314
|
+
return 0
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
class DbtReport(_Guarded):
|
|
318
|
+
name = "dbt-report"
|
|
319
|
+
help = "one report for a dbt run (run_results.json, manifest.json) and a Shape check and drift"
|
|
320
|
+
|
|
321
|
+
def configure(self, parser: Any) -> None:
|
|
322
|
+
parser.description = (
|
|
323
|
+
"Reads the output of a dbt run and, optionally, a Shape contract check and a drift "
|
|
324
|
+
"comparison, and reports them together. Exit 1 when a dbt test or model failed, a "
|
|
325
|
+
"contract rule was violated, or (with --fail-on-drift) the data drifted."
|
|
326
|
+
)
|
|
327
|
+
parser.add_argument("--run-results", required=True, metavar="run_results.json")
|
|
328
|
+
parser.add_argument("--manifest", metavar="manifest.json", help="names each test's model")
|
|
329
|
+
parser.add_argument("--check-result", metavar="JSON", help="a `shape check --json` result")
|
|
330
|
+
parser.add_argument("--diff-result", metavar="JSON", help="a `shape diff --json` result")
|
|
331
|
+
parser.add_argument("--profile", metavar="PROFILE.shape", help="check this profile ...")
|
|
332
|
+
parser.add_argument("--contract", metavar="CONTRACT.json", help="... against this contract")
|
|
333
|
+
parser.add_argument("--baseline", metavar="BASE.shape", help="diff --profile against this")
|
|
334
|
+
parser.add_argument("--table", help="the dbt model a single-table check or diff is about")
|
|
335
|
+
parser.add_argument("--fail-on-drift", action="store_true")
|
|
336
|
+
parser.add_argument("-o", "--output", metavar="REPORT.json")
|
|
337
|
+
parser.add_argument("--md", metavar="REPORT.md", help="also write a Markdown report")
|
|
338
|
+
|
|
339
|
+
def execute(self, args: Any) -> int:
|
|
340
|
+
from .report import ReportError, build_report, load_json, render_markdown
|
|
341
|
+
|
|
342
|
+
run_results = load_json(args.run_results, "run_results")
|
|
343
|
+
manifest = load_json(args.manifest, "manifest") if args.manifest else None
|
|
344
|
+
check: dict[str, Any] | None = None
|
|
345
|
+
drift: dict[str, Any] | None = None
|
|
346
|
+
if args.check_result:
|
|
347
|
+
check = load_json(args.check_result, "check result")
|
|
348
|
+
if args.diff_result:
|
|
349
|
+
drift = load_json(args.diff_result, "diff result")
|
|
350
|
+
if args.profile and (args.contract or args.baseline):
|
|
351
|
+
import shape
|
|
352
|
+
|
|
353
|
+
current = shape.load(args.profile)
|
|
354
|
+
if args.contract and check is None:
|
|
355
|
+
check = shape.check(current, args.contract).to_dict()
|
|
356
|
+
if args.baseline and drift is None:
|
|
357
|
+
drift = shape.diff(shape.load(args.baseline), current).to_dict()
|
|
358
|
+
elif args.contract or args.baseline:
|
|
359
|
+
raise ReportError("--contract and --baseline need --profile")
|
|
360
|
+
report = build_report(
|
|
361
|
+
run_results,
|
|
362
|
+
manifest,
|
|
363
|
+
check=check,
|
|
364
|
+
drift=drift,
|
|
365
|
+
table=args.table,
|
|
366
|
+
fail_on_drift=args.fail_on_drift,
|
|
367
|
+
)
|
|
368
|
+
text = render_markdown(report)
|
|
369
|
+
if args.output:
|
|
370
|
+
_json(Path(args.output), report)
|
|
371
|
+
if args.md:
|
|
372
|
+
_write(Path(args.md), text)
|
|
373
|
+
print(text, end="")
|
|
374
|
+
return 0 if report["ok"] else 1
|