dataforge-07-dbt 0.1.0__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.
- dataforge_07_dbt-0.1.0/PKG-INFO +168 -0
- dataforge_07_dbt-0.1.0/README.md +143 -0
- dataforge_07_dbt-0.1.0/dataforge_07_dbt.egg-info/PKG-INFO +168 -0
- dataforge_07_dbt-0.1.0/dataforge_07_dbt.egg-info/SOURCES.txt +12 -0
- dataforge_07_dbt-0.1.0/dataforge_07_dbt.egg-info/dependency_links.txt +1 -0
- dataforge_07_dbt-0.1.0/dataforge_07_dbt.egg-info/entry_points.txt +3 -0
- dataforge_07_dbt-0.1.0/dataforge_07_dbt.egg-info/requires.txt +11 -0
- dataforge_07_dbt-0.1.0/dataforge_07_dbt.egg-info/top_level.txt +1 -0
- dataforge_07_dbt-0.1.0/dataforge_dbt/__init__.py +7 -0
- dataforge_07_dbt-0.1.0/dataforge_dbt/config.py +170 -0
- dataforge_07_dbt-0.1.0/dataforge_dbt/dispatch.py +515 -0
- dataforge_07_dbt-0.1.0/dataforge_dbt/macros/dataforge_repair.sql +9 -0
- dataforge_07_dbt-0.1.0/pyproject.toml +86 -0
- dataforge_07_dbt-0.1.0/setup.cfg +4 -0
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dataforge_07_dbt
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: dbt relation-export wrapper for DataForge data-quality repair audits.
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Project-URL: Homepage, https://github.com/Aegis15/dataforge
|
|
7
|
+
Project-URL: Repository, https://github.com/Aegis15/dataforge
|
|
8
|
+
Project-URL: Documentation, https://dataforge.praneshrajan15.workers.dev/playground
|
|
9
|
+
Keywords: dataforge,dbt,data-quality,duckdb
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Requires-Python: <3.13,>=3.11
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
Requires-Dist: dataforge_07<0.2,>=0.1.0
|
|
16
|
+
Requires-Dist: dbt-duckdb<1.11,>=1.8
|
|
17
|
+
Requires-Dist: duckdb>=1.1
|
|
18
|
+
Requires-Dist: pydantic>=2.7
|
|
19
|
+
Requires-Dist: PyYAML>=6.0
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Requires-Dist: pytest>=8.2; extra == "dev"
|
|
22
|
+
Requires-Dist: ruff>=0.11; extra == "dev"
|
|
23
|
+
Requires-Dist: mypy<1.20,>=1.10; extra == "dev"
|
|
24
|
+
Requires-Dist: types-PyYAML; extra == "dev"
|
|
25
|
+
|
|
26
|
+
# dataforge-dbt
|
|
27
|
+
|
|
28
|
+
Run DataForge checks from a dbt model post-hook and keep the audit artifacts in your dbt `target/` directory.
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
python -m pip install -e ".[dev]"
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Quick start
|
|
35
|
+
|
|
36
|
+
### 1. Install the Python dependency
|
|
37
|
+
|
|
38
|
+
The PyPI package is not published yet. Install from this source checkout:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
python -m pip install -e ".[dev]"
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
After PyPI publication, `pip install dataforge_07_dbt` will install the
|
|
45
|
+
integration plus the supported `dbt-duckdb` adapter path for the free local
|
|
46
|
+
integration-test warehouse.
|
|
47
|
+
|
|
48
|
+
### 2. Add the dbt package
|
|
49
|
+
|
|
50
|
+
In `packages.yml`:
|
|
51
|
+
|
|
52
|
+
```yaml
|
|
53
|
+
packages:
|
|
54
|
+
- package: dataforge/dataforge
|
|
55
|
+
version: 0.1.0
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
During local development from a checkout, use:
|
|
59
|
+
|
|
60
|
+
```yaml
|
|
61
|
+
packages:
|
|
62
|
+
- local: ../dataforge-dbt
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Then run:
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
dbt deps
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### 3. Add a model post-hook
|
|
72
|
+
|
|
73
|
+
```sql
|
|
74
|
+
{{ config(post_hook="{{ dataforge.dataforge_repair('column_x', mode='dry_run') }}") }}
|
|
75
|
+
|
|
76
|
+
select *
|
|
77
|
+
from {{ ref('my_source_model') }}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Supported modes:
|
|
81
|
+
|
|
82
|
+
- **`dry_run`**: logs proposed DataForge findings as warnings and writes no transaction artifact.
|
|
83
|
+
- **`apply`**: writes a JSONL audit artifact under `target/dataforge_txns/`.
|
|
84
|
+
- **`refuse`**: fails the hook if DataForge detects any `UNSAFE` issue.
|
|
85
|
+
|
|
86
|
+
### 4. Run dbt through the dispatcher
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
dataforge-dbt \
|
|
90
|
+
--relation main.my_model \
|
|
91
|
+
--column column_x \
|
|
92
|
+
--mode dry_run \
|
|
93
|
+
--target-path target \
|
|
94
|
+
--project-dir . \
|
|
95
|
+
--run-dbt
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
The macro emits a stable log line showing the dispatcher command for the
|
|
99
|
+
relation and column. The Python dispatcher is the execution boundary: it can
|
|
100
|
+
run dbt, export the relation through the adapter, run DataForge detectors, and
|
|
101
|
+
write audit artifacts under `target/`. The macro itself remains SQL-only
|
|
102
|
+
because dbt post-hooks do not provide a portable, safe shell execution surface.
|
|
103
|
+
|
|
104
|
+
### 5. Verify transaction artifacts
|
|
105
|
+
|
|
106
|
+
For `mode='apply'`, verify that the target directory contains a DataForge transaction artifact:
|
|
107
|
+
|
|
108
|
+
```bash
|
|
109
|
+
ls target/dataforge_txns/
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Each file is JSONL and includes the dbt relation, inspected column, UTC timestamp, and serialized DataForge issues.
|
|
113
|
+
|
|
114
|
+
## Python dispatch entrypoint
|
|
115
|
+
|
|
116
|
+
The package also ships a Python command used by tests and automation:
|
|
117
|
+
|
|
118
|
+
```bash
|
|
119
|
+
dataforge-dbt \
|
|
120
|
+
--relation main.example_with_dirty_data \
|
|
121
|
+
--column column_x \
|
|
122
|
+
--mode dry_run \
|
|
123
|
+
--input-csv integration_tests/dbt_project/seeds/dirty_decimal_shift.csv \
|
|
124
|
+
--target-path target
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
This command reads the CSV with `dtype=str`, runs DataForge detectors, logs any findings with the prefix `DATAFORGE_DBT`, and enforces the selected mode.
|
|
128
|
+
|
|
129
|
+
## Configuration block
|
|
130
|
+
|
|
131
|
+
You may add a conservative integration block to `profiles.yml`:
|
|
132
|
+
|
|
133
|
+
```yaml
|
|
134
|
+
my_profile:
|
|
135
|
+
target: dev
|
|
136
|
+
outputs:
|
|
137
|
+
dev:
|
|
138
|
+
type: duckdb
|
|
139
|
+
path: ./dev.duckdb
|
|
140
|
+
dataforge:
|
|
141
|
+
mode: dry_run
|
|
142
|
+
target_path: target
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
Macro arguments remain the source of truth for the common case. The profile
|
|
146
|
+
block is useful for central defaults in CI; an explicit hook or dispatcher
|
|
147
|
+
`--mode` always overrides `dataforge.mode` from `profiles.yml`.
|
|
148
|
+
|
|
149
|
+
## Free-tier test setup
|
|
150
|
+
|
|
151
|
+
The integration tests use DuckDB only. No Snowflake, BigQuery, or paid warehouse account is required.
|
|
152
|
+
|
|
153
|
+
```bash
|
|
154
|
+
python -m pip install -e ".[dev]"
|
|
155
|
+
python -m pytest
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
The test project includes a seed CSV with a known decimal-shift anomaly and asserts that DataForge logs the issue.
|
|
159
|
+
|
|
160
|
+
## Publishing
|
|
161
|
+
|
|
162
|
+
The package is not published yet. The intended release path is PyPI Trusted
|
|
163
|
+
Publishing after repository ownership is configured; do not add PyPI API tokens
|
|
164
|
+
to GitHub Secrets.
|
|
165
|
+
|
|
166
|
+
## When this is the wrong tool
|
|
167
|
+
|
|
168
|
+
Use dbt tests or warehouse constraints first for deterministic rules such as `not_null`, `unique`, accepted values, and referential integrity. Use `dataforge-dbt` when you want DataForge's anomaly detectors and repair audit trail around messy values that are hard to express as static SQL tests.
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
# dataforge-dbt
|
|
2
|
+
|
|
3
|
+
Run DataForge checks from a dbt model post-hook and keep the audit artifacts in your dbt `target/` directory.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
python -m pip install -e ".[dev]"
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Quick start
|
|
10
|
+
|
|
11
|
+
### 1. Install the Python dependency
|
|
12
|
+
|
|
13
|
+
The PyPI package is not published yet. Install from this source checkout:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
python -m pip install -e ".[dev]"
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
After PyPI publication, `pip install dataforge_07_dbt` will install the
|
|
20
|
+
integration plus the supported `dbt-duckdb` adapter path for the free local
|
|
21
|
+
integration-test warehouse.
|
|
22
|
+
|
|
23
|
+
### 2. Add the dbt package
|
|
24
|
+
|
|
25
|
+
In `packages.yml`:
|
|
26
|
+
|
|
27
|
+
```yaml
|
|
28
|
+
packages:
|
|
29
|
+
- package: dataforge/dataforge
|
|
30
|
+
version: 0.1.0
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
During local development from a checkout, use:
|
|
34
|
+
|
|
35
|
+
```yaml
|
|
36
|
+
packages:
|
|
37
|
+
- local: ../dataforge-dbt
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Then run:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
dbt deps
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### 3. Add a model post-hook
|
|
47
|
+
|
|
48
|
+
```sql
|
|
49
|
+
{{ config(post_hook="{{ dataforge.dataforge_repair('column_x', mode='dry_run') }}") }}
|
|
50
|
+
|
|
51
|
+
select *
|
|
52
|
+
from {{ ref('my_source_model') }}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Supported modes:
|
|
56
|
+
|
|
57
|
+
- **`dry_run`**: logs proposed DataForge findings as warnings and writes no transaction artifact.
|
|
58
|
+
- **`apply`**: writes a JSONL audit artifact under `target/dataforge_txns/`.
|
|
59
|
+
- **`refuse`**: fails the hook if DataForge detects any `UNSAFE` issue.
|
|
60
|
+
|
|
61
|
+
### 4. Run dbt through the dispatcher
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
dataforge-dbt \
|
|
65
|
+
--relation main.my_model \
|
|
66
|
+
--column column_x \
|
|
67
|
+
--mode dry_run \
|
|
68
|
+
--target-path target \
|
|
69
|
+
--project-dir . \
|
|
70
|
+
--run-dbt
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
The macro emits a stable log line showing the dispatcher command for the
|
|
74
|
+
relation and column. The Python dispatcher is the execution boundary: it can
|
|
75
|
+
run dbt, export the relation through the adapter, run DataForge detectors, and
|
|
76
|
+
write audit artifacts under `target/`. The macro itself remains SQL-only
|
|
77
|
+
because dbt post-hooks do not provide a portable, safe shell execution surface.
|
|
78
|
+
|
|
79
|
+
### 5. Verify transaction artifacts
|
|
80
|
+
|
|
81
|
+
For `mode='apply'`, verify that the target directory contains a DataForge transaction artifact:
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
ls target/dataforge_txns/
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Each file is JSONL and includes the dbt relation, inspected column, UTC timestamp, and serialized DataForge issues.
|
|
88
|
+
|
|
89
|
+
## Python dispatch entrypoint
|
|
90
|
+
|
|
91
|
+
The package also ships a Python command used by tests and automation:
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
dataforge-dbt \
|
|
95
|
+
--relation main.example_with_dirty_data \
|
|
96
|
+
--column column_x \
|
|
97
|
+
--mode dry_run \
|
|
98
|
+
--input-csv integration_tests/dbt_project/seeds/dirty_decimal_shift.csv \
|
|
99
|
+
--target-path target
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
This command reads the CSV with `dtype=str`, runs DataForge detectors, logs any findings with the prefix `DATAFORGE_DBT`, and enforces the selected mode.
|
|
103
|
+
|
|
104
|
+
## Configuration block
|
|
105
|
+
|
|
106
|
+
You may add a conservative integration block to `profiles.yml`:
|
|
107
|
+
|
|
108
|
+
```yaml
|
|
109
|
+
my_profile:
|
|
110
|
+
target: dev
|
|
111
|
+
outputs:
|
|
112
|
+
dev:
|
|
113
|
+
type: duckdb
|
|
114
|
+
path: ./dev.duckdb
|
|
115
|
+
dataforge:
|
|
116
|
+
mode: dry_run
|
|
117
|
+
target_path: target
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Macro arguments remain the source of truth for the common case. The profile
|
|
121
|
+
block is useful for central defaults in CI; an explicit hook or dispatcher
|
|
122
|
+
`--mode` always overrides `dataforge.mode` from `profiles.yml`.
|
|
123
|
+
|
|
124
|
+
## Free-tier test setup
|
|
125
|
+
|
|
126
|
+
The integration tests use DuckDB only. No Snowflake, BigQuery, or paid warehouse account is required.
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
python -m pip install -e ".[dev]"
|
|
130
|
+
python -m pytest
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
The test project includes a seed CSV with a known decimal-shift anomaly and asserts that DataForge logs the issue.
|
|
134
|
+
|
|
135
|
+
## Publishing
|
|
136
|
+
|
|
137
|
+
The package is not published yet. The intended release path is PyPI Trusted
|
|
138
|
+
Publishing after repository ownership is configured; do not add PyPI API tokens
|
|
139
|
+
to GitHub Secrets.
|
|
140
|
+
|
|
141
|
+
## When this is the wrong tool
|
|
142
|
+
|
|
143
|
+
Use dbt tests or warehouse constraints first for deterministic rules such as `not_null`, `unique`, accepted values, and referential integrity. Use `dataforge-dbt` when you want DataForge's anomaly detectors and repair audit trail around messy values that are hard to express as static SQL tests.
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dataforge_07_dbt
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: dbt relation-export wrapper for DataForge data-quality repair audits.
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Project-URL: Homepage, https://github.com/Aegis15/dataforge
|
|
7
|
+
Project-URL: Repository, https://github.com/Aegis15/dataforge
|
|
8
|
+
Project-URL: Documentation, https://dataforge.praneshrajan15.workers.dev/playground
|
|
9
|
+
Keywords: dataforge,dbt,data-quality,duckdb
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Requires-Python: <3.13,>=3.11
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
Requires-Dist: dataforge_07<0.2,>=0.1.0
|
|
16
|
+
Requires-Dist: dbt-duckdb<1.11,>=1.8
|
|
17
|
+
Requires-Dist: duckdb>=1.1
|
|
18
|
+
Requires-Dist: pydantic>=2.7
|
|
19
|
+
Requires-Dist: PyYAML>=6.0
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Requires-Dist: pytest>=8.2; extra == "dev"
|
|
22
|
+
Requires-Dist: ruff>=0.11; extra == "dev"
|
|
23
|
+
Requires-Dist: mypy<1.20,>=1.10; extra == "dev"
|
|
24
|
+
Requires-Dist: types-PyYAML; extra == "dev"
|
|
25
|
+
|
|
26
|
+
# dataforge-dbt
|
|
27
|
+
|
|
28
|
+
Run DataForge checks from a dbt model post-hook and keep the audit artifacts in your dbt `target/` directory.
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
python -m pip install -e ".[dev]"
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Quick start
|
|
35
|
+
|
|
36
|
+
### 1. Install the Python dependency
|
|
37
|
+
|
|
38
|
+
The PyPI package is not published yet. Install from this source checkout:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
python -m pip install -e ".[dev]"
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
After PyPI publication, `pip install dataforge_07_dbt` will install the
|
|
45
|
+
integration plus the supported `dbt-duckdb` adapter path for the free local
|
|
46
|
+
integration-test warehouse.
|
|
47
|
+
|
|
48
|
+
### 2. Add the dbt package
|
|
49
|
+
|
|
50
|
+
In `packages.yml`:
|
|
51
|
+
|
|
52
|
+
```yaml
|
|
53
|
+
packages:
|
|
54
|
+
- package: dataforge/dataforge
|
|
55
|
+
version: 0.1.0
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
During local development from a checkout, use:
|
|
59
|
+
|
|
60
|
+
```yaml
|
|
61
|
+
packages:
|
|
62
|
+
- local: ../dataforge-dbt
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Then run:
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
dbt deps
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### 3. Add a model post-hook
|
|
72
|
+
|
|
73
|
+
```sql
|
|
74
|
+
{{ config(post_hook="{{ dataforge.dataforge_repair('column_x', mode='dry_run') }}") }}
|
|
75
|
+
|
|
76
|
+
select *
|
|
77
|
+
from {{ ref('my_source_model') }}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Supported modes:
|
|
81
|
+
|
|
82
|
+
- **`dry_run`**: logs proposed DataForge findings as warnings and writes no transaction artifact.
|
|
83
|
+
- **`apply`**: writes a JSONL audit artifact under `target/dataforge_txns/`.
|
|
84
|
+
- **`refuse`**: fails the hook if DataForge detects any `UNSAFE` issue.
|
|
85
|
+
|
|
86
|
+
### 4. Run dbt through the dispatcher
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
dataforge-dbt \
|
|
90
|
+
--relation main.my_model \
|
|
91
|
+
--column column_x \
|
|
92
|
+
--mode dry_run \
|
|
93
|
+
--target-path target \
|
|
94
|
+
--project-dir . \
|
|
95
|
+
--run-dbt
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
The macro emits a stable log line showing the dispatcher command for the
|
|
99
|
+
relation and column. The Python dispatcher is the execution boundary: it can
|
|
100
|
+
run dbt, export the relation through the adapter, run DataForge detectors, and
|
|
101
|
+
write audit artifacts under `target/`. The macro itself remains SQL-only
|
|
102
|
+
because dbt post-hooks do not provide a portable, safe shell execution surface.
|
|
103
|
+
|
|
104
|
+
### 5. Verify transaction artifacts
|
|
105
|
+
|
|
106
|
+
For `mode='apply'`, verify that the target directory contains a DataForge transaction artifact:
|
|
107
|
+
|
|
108
|
+
```bash
|
|
109
|
+
ls target/dataforge_txns/
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Each file is JSONL and includes the dbt relation, inspected column, UTC timestamp, and serialized DataForge issues.
|
|
113
|
+
|
|
114
|
+
## Python dispatch entrypoint
|
|
115
|
+
|
|
116
|
+
The package also ships a Python command used by tests and automation:
|
|
117
|
+
|
|
118
|
+
```bash
|
|
119
|
+
dataforge-dbt \
|
|
120
|
+
--relation main.example_with_dirty_data \
|
|
121
|
+
--column column_x \
|
|
122
|
+
--mode dry_run \
|
|
123
|
+
--input-csv integration_tests/dbt_project/seeds/dirty_decimal_shift.csv \
|
|
124
|
+
--target-path target
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
This command reads the CSV with `dtype=str`, runs DataForge detectors, logs any findings with the prefix `DATAFORGE_DBT`, and enforces the selected mode.
|
|
128
|
+
|
|
129
|
+
## Configuration block
|
|
130
|
+
|
|
131
|
+
You may add a conservative integration block to `profiles.yml`:
|
|
132
|
+
|
|
133
|
+
```yaml
|
|
134
|
+
my_profile:
|
|
135
|
+
target: dev
|
|
136
|
+
outputs:
|
|
137
|
+
dev:
|
|
138
|
+
type: duckdb
|
|
139
|
+
path: ./dev.duckdb
|
|
140
|
+
dataforge:
|
|
141
|
+
mode: dry_run
|
|
142
|
+
target_path: target
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
Macro arguments remain the source of truth for the common case. The profile
|
|
146
|
+
block is useful for central defaults in CI; an explicit hook or dispatcher
|
|
147
|
+
`--mode` always overrides `dataforge.mode` from `profiles.yml`.
|
|
148
|
+
|
|
149
|
+
## Free-tier test setup
|
|
150
|
+
|
|
151
|
+
The integration tests use DuckDB only. No Snowflake, BigQuery, or paid warehouse account is required.
|
|
152
|
+
|
|
153
|
+
```bash
|
|
154
|
+
python -m pip install -e ".[dev]"
|
|
155
|
+
python -m pytest
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
The test project includes a seed CSV with a known decimal-shift anomaly and asserts that DataForge logs the issue.
|
|
159
|
+
|
|
160
|
+
## Publishing
|
|
161
|
+
|
|
162
|
+
The package is not published yet. The intended release path is PyPI Trusted
|
|
163
|
+
Publishing after repository ownership is configured; do not add PyPI API tokens
|
|
164
|
+
to GitHub Secrets.
|
|
165
|
+
|
|
166
|
+
## When this is the wrong tool
|
|
167
|
+
|
|
168
|
+
Use dbt tests or warehouse constraints first for deterministic rules such as `not_null`, `unique`, accepted values, and referential integrity. Use `dataforge-dbt` when you want DataForge's anomaly detectors and repair audit trail around messy values that are hard to express as static SQL tests.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
dataforge_07_dbt.egg-info/PKG-INFO
|
|
4
|
+
dataforge_07_dbt.egg-info/SOURCES.txt
|
|
5
|
+
dataforge_07_dbt.egg-info/dependency_links.txt
|
|
6
|
+
dataforge_07_dbt.egg-info/entry_points.txt
|
|
7
|
+
dataforge_07_dbt.egg-info/requires.txt
|
|
8
|
+
dataforge_07_dbt.egg-info/top_level.txt
|
|
9
|
+
dataforge_dbt/__init__.py
|
|
10
|
+
dataforge_dbt/config.py
|
|
11
|
+
dataforge_dbt/dispatch.py
|
|
12
|
+
dataforge_dbt/macros/dataforge_repair.sql
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
dataforge_dbt
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Configuration loading for the DataForge dbt integration."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, Literal
|
|
9
|
+
|
|
10
|
+
import yaml
|
|
11
|
+
|
|
12
|
+
Mode = Literal["dry_run", "apply", "refuse"]
|
|
13
|
+
|
|
14
|
+
_VALID_MODES: set[str] = {"dry_run", "apply", "refuse"}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class DataForgeDbtConfigError(ValueError):
|
|
18
|
+
"""Raised when the DataForge dbt integration configuration is invalid.
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
message: User-facing description of the invalid configuration.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class DataForgeDbtConfig:
|
|
27
|
+
"""Runtime configuration for a DataForge dbt hook invocation.
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
mode: Hook behavior: log only, write a transaction artifact, or fail on unsafe issues.
|
|
31
|
+
target_path: dbt target directory used for DataForge transaction artifacts.
|
|
32
|
+
profile_name: Optional dbt profile name used to find a scoped integration block.
|
|
33
|
+
|
|
34
|
+
Example:
|
|
35
|
+
>>> config = DataForgeDbtConfig(mode="dry_run", target_path=Path("target"))
|
|
36
|
+
>>> config.transaction_dir
|
|
37
|
+
PosixPath('target/dataforge_txns')
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
mode: Mode
|
|
41
|
+
target_path: Path
|
|
42
|
+
profile_name: str | None = None
|
|
43
|
+
row_identity_columns: tuple[str, ...] = ()
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def transaction_dir(self) -> Path:
|
|
47
|
+
"""Return the target directory for DataForge dbt transaction artifacts.
|
|
48
|
+
|
|
49
|
+
Returns:
|
|
50
|
+
Path under the dbt target directory where transaction JSONL files are written.
|
|
51
|
+
"""
|
|
52
|
+
return self.target_path / "dataforge_txns"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def parse_mode(value: str) -> Mode:
|
|
56
|
+
"""Validate and normalize a DataForge dbt mode value.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
value: Raw mode string supplied by a dbt macro or integration block.
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
A validated mode literal.
|
|
63
|
+
|
|
64
|
+
Raises:
|
|
65
|
+
DataForgeDbtConfigError: If the mode is not one of dry_run, apply, or refuse.
|
|
66
|
+
"""
|
|
67
|
+
normalized = value.strip().lower()
|
|
68
|
+
if normalized not in _VALID_MODES:
|
|
69
|
+
raise DataForgeDbtConfigError(
|
|
70
|
+
"DataForge dbt mode must be one of 'dry_run', 'apply', or 'refuse'."
|
|
71
|
+
)
|
|
72
|
+
return normalized # type: ignore[return-value]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def load_config(
|
|
76
|
+
*,
|
|
77
|
+
mode: str,
|
|
78
|
+
target_path: Path,
|
|
79
|
+
profiles_path: Path | None = None,
|
|
80
|
+
profile_name: str | None = None,
|
|
81
|
+
) -> DataForgeDbtConfig:
|
|
82
|
+
"""Load DataForge dbt configuration from arguments and optional profiles.yml.
|
|
83
|
+
|
|
84
|
+
Args:
|
|
85
|
+
mode: Mode supplied by the dbt macro invocation.
|
|
86
|
+
target_path: dbt target directory.
|
|
87
|
+
profiles_path: Optional path to dbt profiles.yml.
|
|
88
|
+
profile_name: Optional profile name whose ``dataforge`` block should be read.
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
Parsed immutable runtime configuration.
|
|
92
|
+
|
|
93
|
+
Raises:
|
|
94
|
+
DataForgeDbtConfigError: If the profile block or mode is invalid.
|
|
95
|
+
"""
|
|
96
|
+
profile_block = _read_profile_block(profiles_path=profiles_path, profile_name=profile_name)
|
|
97
|
+
configured_mode = mode
|
|
98
|
+
configured_target = (
|
|
99
|
+
Path(str(profile_block.get("target_path", target_path))) if profile_block else target_path
|
|
100
|
+
)
|
|
101
|
+
env_target = os.environ.get("DATAFORGE_DBT_TARGET_PATH")
|
|
102
|
+
resolved_target = Path(env_target) if env_target else configured_target
|
|
103
|
+
return DataForgeDbtConfig(
|
|
104
|
+
mode=parse_mode(configured_mode),
|
|
105
|
+
target_path=resolved_target,
|
|
106
|
+
profile_name=profile_name,
|
|
107
|
+
row_identity_columns=_parse_row_identity_columns(profile_block),
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _parse_row_identity_columns(profile_block: dict[str, Any]) -> tuple[str, ...]:
|
|
112
|
+
"""Return optional row identity columns from the profile integration block."""
|
|
113
|
+
raw = profile_block.get("row_identity_columns", profile_block.get("row_id"))
|
|
114
|
+
if raw is None:
|
|
115
|
+
return ()
|
|
116
|
+
if isinstance(raw, str):
|
|
117
|
+
return tuple(part.strip() for part in raw.split(",") if part.strip())
|
|
118
|
+
if isinstance(raw, list) and all(isinstance(item, str) for item in raw):
|
|
119
|
+
return tuple(item.strip() for item in raw if item.strip())
|
|
120
|
+
raise DataForgeDbtConfigError(
|
|
121
|
+
"dataforge.row_identity_columns must be a string or list of strings."
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _read_profile_block(
|
|
126
|
+
*,
|
|
127
|
+
profiles_path: Path | None,
|
|
128
|
+
profile_name: str | None,
|
|
129
|
+
) -> dict[str, Any]:
|
|
130
|
+
"""Read the optional ``dataforge`` integration block from profiles.yml.
|
|
131
|
+
|
|
132
|
+
Args:
|
|
133
|
+
profiles_path: Optional dbt profiles.yml path.
|
|
134
|
+
profile_name: Optional dbt profile name.
|
|
135
|
+
|
|
136
|
+
Returns:
|
|
137
|
+
The parsed dataforge block, or an empty dict when no block exists.
|
|
138
|
+
|
|
139
|
+
Raises:
|
|
140
|
+
DataForgeDbtConfigError: If profiles.yml is malformed.
|
|
141
|
+
"""
|
|
142
|
+
if profiles_path is None or profile_name is None or not profiles_path.exists():
|
|
143
|
+
return {}
|
|
144
|
+
|
|
145
|
+
try:
|
|
146
|
+
loaded = yaml.safe_load(profiles_path.read_text(encoding="utf-8"))
|
|
147
|
+
except yaml.YAMLError as exc:
|
|
148
|
+
raise DataForgeDbtConfigError(f"Could not parse dbt profiles.yml: {exc}") from exc
|
|
149
|
+
except OSError as exc:
|
|
150
|
+
raise DataForgeDbtConfigError(f"Could not read dbt profiles.yml: {exc}") from exc
|
|
151
|
+
|
|
152
|
+
if loaded is None:
|
|
153
|
+
return {}
|
|
154
|
+
if not isinstance(loaded, dict):
|
|
155
|
+
raise DataForgeDbtConfigError("dbt profiles.yml must contain a mapping at the top level.")
|
|
156
|
+
|
|
157
|
+
profile = loaded.get(profile_name)
|
|
158
|
+
if profile is None:
|
|
159
|
+
return {}
|
|
160
|
+
if not isinstance(profile, dict):
|
|
161
|
+
raise DataForgeDbtConfigError(f"dbt profile '{profile_name}' must be a mapping.")
|
|
162
|
+
|
|
163
|
+
block = profile.get("dataforge", {})
|
|
164
|
+
if block is None:
|
|
165
|
+
return {}
|
|
166
|
+
if not isinstance(block, dict):
|
|
167
|
+
raise DataForgeDbtConfigError(
|
|
168
|
+
f"dbt profile '{profile_name}' has a dataforge block that is not a mapping."
|
|
169
|
+
)
|
|
170
|
+
return block
|
|
@@ -0,0 +1,515 @@
|
|
|
1
|
+
"""Python entrypoint used by DataForge dbt macros and integration tests."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import subprocess
|
|
11
|
+
import sys
|
|
12
|
+
import tempfile
|
|
13
|
+
from contextlib import suppress
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from datetime import UTC, datetime
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
import yaml
|
|
20
|
+
from dataforge import (
|
|
21
|
+
DuckDBStore,
|
|
22
|
+
Issue,
|
|
23
|
+
Severity,
|
|
24
|
+
TableStoreError,
|
|
25
|
+
read_csv,
|
|
26
|
+
run_all_detectors,
|
|
27
|
+
run_table_store_repair,
|
|
28
|
+
)
|
|
29
|
+
from dataforge.table import TableLike
|
|
30
|
+
from pydantic import BaseModel, Field
|
|
31
|
+
|
|
32
|
+
from dataforge_dbt.config import DataForgeDbtConfigError, load_config
|
|
33
|
+
|
|
34
|
+
_LOGGER = logging.getLogger("dataforge_dbt")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class DataForgeDbtDispatchError(RuntimeError):
|
|
38
|
+
"""Raised when a DataForge dbt dispatch invocation cannot complete.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
message: User-facing failure reason.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True)
|
|
46
|
+
class DispatchRequest:
|
|
47
|
+
"""Inputs for one DataForge dbt post-hook invocation.
|
|
48
|
+
|
|
49
|
+
Args:
|
|
50
|
+
relation: dbt relation identifier for logs and transaction metadata.
|
|
51
|
+
column: Column to inspect for DataForge findings.
|
|
52
|
+
mode: Hook behavior requested by the dbt macro.
|
|
53
|
+
input_csv: Optional CSV export of the model relation. When omitted,
|
|
54
|
+
DataForge exports the relation from dbt's adapter artifacts.
|
|
55
|
+
target_path: dbt target directory.
|
|
56
|
+
project_dir: dbt project directory.
|
|
57
|
+
select: Optional dbt selector to run before exporting.
|
|
58
|
+
run_dbt: Whether to run ``dbt run`` before exporting.
|
|
59
|
+
profiles_path: Optional dbt profiles.yml path.
|
|
60
|
+
profile_name: Optional dbt profile name.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
relation: str
|
|
64
|
+
column: str
|
|
65
|
+
mode: str
|
|
66
|
+
input_csv: Path | None
|
|
67
|
+
target_path: Path
|
|
68
|
+
project_dir: Path | None = None
|
|
69
|
+
select: str | None = None
|
|
70
|
+
run_dbt: bool = False
|
|
71
|
+
profiles_path: Path | None = None
|
|
72
|
+
profile_name: str | None = None
|
|
73
|
+
row_identity_columns: tuple[str, ...] = ()
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class DbtTransaction(BaseModel):
|
|
77
|
+
"""Audit artifact written by ``mode='apply'`` for dbt hook runs.
|
|
78
|
+
|
|
79
|
+
Args:
|
|
80
|
+
relation: dbt relation that was inspected.
|
|
81
|
+
column: Column passed to ``dataforge_repair``.
|
|
82
|
+
mode: DataForge dbt mode that produced the artifact.
|
|
83
|
+
created_at: UTC timestamp for the audit artifact.
|
|
84
|
+
issues: Serialized DataForge issues detected in the relation.
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
relation: str = Field(min_length=1)
|
|
88
|
+
column: str = Field(min_length=1)
|
|
89
|
+
mode: str = Field(pattern="^apply$")
|
|
90
|
+
created_at: datetime
|
|
91
|
+
issues: list[dict[str, object]] = Field(default_factory=list)
|
|
92
|
+
patch_plan: dict[str, object] | None = None
|
|
93
|
+
apply_receipt: dict[str, object] | None = None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def dispatch(request: DispatchRequest) -> list[Issue]:
|
|
97
|
+
"""Run DataForge detection for a dbt relation export.
|
|
98
|
+
|
|
99
|
+
Args:
|
|
100
|
+
request: Validated dispatch inputs from the macro or test harness.
|
|
101
|
+
|
|
102
|
+
Returns:
|
|
103
|
+
DataForge issues detected for the requested column.
|
|
104
|
+
|
|
105
|
+
Raises:
|
|
106
|
+
DataForgeDbtDispatchError: If inputs are missing or refuse mode blocks the run.
|
|
107
|
+
DataForgeDbtConfigError: If configuration is invalid.
|
|
108
|
+
"""
|
|
109
|
+
config = load_config(
|
|
110
|
+
mode=request.mode,
|
|
111
|
+
target_path=request.target_path,
|
|
112
|
+
profiles_path=request.profiles_path,
|
|
113
|
+
profile_name=request.profile_name,
|
|
114
|
+
)
|
|
115
|
+
if request.input_csv is None and request.project_dir is not None:
|
|
116
|
+
return _dispatch_table_store_relation(request, config)
|
|
117
|
+
|
|
118
|
+
input_csv = request.input_csv or _export_relation_csv(request)
|
|
119
|
+
table = _read_input_csv(input_csv)
|
|
120
|
+
if request.column not in table.columns:
|
|
121
|
+
raise DataForgeDbtDispatchError(
|
|
122
|
+
f"Column '{request.column}' does not exist in dbt relation '{request.relation}'."
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
issues = [
|
|
126
|
+
issue for issue in run_all_detectors(table, schema=None) if issue.column == request.column
|
|
127
|
+
]
|
|
128
|
+
_log_issues(relation=request.relation, column=request.column, issues=issues)
|
|
129
|
+
|
|
130
|
+
if config.mode == "refuse" and any(issue.severity == Severity.UNSAFE for issue in issues):
|
|
131
|
+
raise DataForgeDbtDispatchError(
|
|
132
|
+
f"DataForge refuse mode blocked dbt relation '{request.relation}' because UNSAFE issues were detected."
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
if config.mode == "apply" and issues:
|
|
136
|
+
_write_transaction(config.transaction_dir, request=request, issues=issues)
|
|
137
|
+
|
|
138
|
+
return issues
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def main(argv: list[str] | None = None) -> int:
|
|
142
|
+
"""Run the DataForge dbt dispatch command-line entrypoint.
|
|
143
|
+
|
|
144
|
+
Args:
|
|
145
|
+
argv: Optional argument vector for tests. When omitted, ``sys.argv`` is used.
|
|
146
|
+
|
|
147
|
+
Returns:
|
|
148
|
+
Process exit code.
|
|
149
|
+
"""
|
|
150
|
+
_configure_logging()
|
|
151
|
+
parser = _build_parser()
|
|
152
|
+
args = parser.parse_args(argv)
|
|
153
|
+
request = DispatchRequest(
|
|
154
|
+
relation=args.relation,
|
|
155
|
+
column=args.column,
|
|
156
|
+
mode=args.mode,
|
|
157
|
+
input_csv=Path(args.input_csv) if args.input_csv else None,
|
|
158
|
+
target_path=Path(args.target_path),
|
|
159
|
+
project_dir=Path(args.project_dir) if args.project_dir else None,
|
|
160
|
+
select=args.select,
|
|
161
|
+
run_dbt=args.run_dbt,
|
|
162
|
+
profiles_path=Path(args.profiles_path) if args.profiles_path else None,
|
|
163
|
+
profile_name=args.profile_name,
|
|
164
|
+
row_identity_columns=tuple(args.row_id or ()),
|
|
165
|
+
)
|
|
166
|
+
try:
|
|
167
|
+
dispatch(request)
|
|
168
|
+
except (DataForgeDbtConfigError, DataForgeDbtDispatchError) as exc:
|
|
169
|
+
_LOGGER.error("DATAFORGE_DBT error relation=%s message=%s", request.relation, exc)
|
|
170
|
+
return 1
|
|
171
|
+
return 0
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
175
|
+
"""Build the command-line parser for ``dataforge-dbt``.
|
|
176
|
+
|
|
177
|
+
Returns:
|
|
178
|
+
Configured argument parser.
|
|
179
|
+
"""
|
|
180
|
+
parser = argparse.ArgumentParser(prog="dataforge-dbt")
|
|
181
|
+
parser.add_argument("--relation", required=True)
|
|
182
|
+
parser.add_argument("--column", required=True)
|
|
183
|
+
parser.add_argument("--mode", required=True, choices=["dry_run", "apply", "refuse"])
|
|
184
|
+
parser.add_argument("--input-csv")
|
|
185
|
+
parser.add_argument("--target-path", required=True)
|
|
186
|
+
parser.add_argument("--project-dir")
|
|
187
|
+
parser.add_argument("--select")
|
|
188
|
+
parser.add_argument("--run-dbt", action="store_true")
|
|
189
|
+
parser.add_argument("--profiles-path")
|
|
190
|
+
parser.add_argument("--profile-name")
|
|
191
|
+
parser.add_argument("--row-id", action="append", help="Stable row identity column.")
|
|
192
|
+
return parser
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _configure_logging() -> None:
|
|
196
|
+
"""Configure stable process logging for dbt and pytest capture.
|
|
197
|
+
|
|
198
|
+
Returns:
|
|
199
|
+
None.
|
|
200
|
+
"""
|
|
201
|
+
logging.basicConfig(level=logging.INFO, format="%(levelname)s:%(name)s:%(message)s")
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _read_input_csv(path: Path) -> TableLike:
|
|
205
|
+
"""Read a dbt relation CSV export using DataForge-safe dtype handling.
|
|
206
|
+
|
|
207
|
+
Args:
|
|
208
|
+
path: CSV file produced from a dbt model relation.
|
|
209
|
+
|
|
210
|
+
Returns:
|
|
211
|
+
String-preserving DataForge table.
|
|
212
|
+
|
|
213
|
+
Raises:
|
|
214
|
+
DataForgeDbtDispatchError: If the CSV does not exist or cannot be read.
|
|
215
|
+
"""
|
|
216
|
+
if not path.exists():
|
|
217
|
+
raise DataForgeDbtDispatchError(f"DataForge dbt input CSV does not exist: {path}")
|
|
218
|
+
try:
|
|
219
|
+
return read_csv(path)
|
|
220
|
+
except OSError as exc:
|
|
221
|
+
raise DataForgeDbtDispatchError(
|
|
222
|
+
f"Could not read DataForge dbt input CSV '{path}': {exc}"
|
|
223
|
+
) from exc
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
_SAFE_RELATION_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*|\.\"[^\"]+\")*$")
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _export_relation_csv(request: DispatchRequest) -> Path:
|
|
230
|
+
"""Export a dbt relation to a temporary CSV through the configured adapter."""
|
|
231
|
+
project_dir = request.project_dir
|
|
232
|
+
if project_dir is None:
|
|
233
|
+
raise DataForgeDbtDispatchError(
|
|
234
|
+
"Either --input-csv or --project-dir must be supplied for DataForge dbt dispatch."
|
|
235
|
+
)
|
|
236
|
+
profiles_path = _resolve_profiles_path(request.profiles_path)
|
|
237
|
+
profile_name = request.profile_name or _read_project_profile(project_dir)
|
|
238
|
+
if request.run_dbt:
|
|
239
|
+
_run_dbt(project_dir, profiles_path.parent, request.select)
|
|
240
|
+
output_dir = request.target_path / "dataforge_exports"
|
|
241
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
242
|
+
safe_relation = "".join(
|
|
243
|
+
ch if ch.isalnum() or ch in {"-", "_"} else "_" for ch in request.relation
|
|
244
|
+
)
|
|
245
|
+
export_path = output_dir / f"{safe_relation}.csv"
|
|
246
|
+
_export_duckdb_relation(
|
|
247
|
+
relation=request.relation,
|
|
248
|
+
output_path=export_path,
|
|
249
|
+
profiles_path=profiles_path,
|
|
250
|
+
profile_name=profile_name,
|
|
251
|
+
)
|
|
252
|
+
return export_path
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _dispatch_table_store_relation(
|
|
256
|
+
request: DispatchRequest,
|
|
257
|
+
config: Any,
|
|
258
|
+
) -> list[Issue]:
|
|
259
|
+
"""Run a dbt relation through the table-store patch-plan path."""
|
|
260
|
+
project_dir = request.project_dir
|
|
261
|
+
if project_dir is None:
|
|
262
|
+
raise DataForgeDbtDispatchError(
|
|
263
|
+
"Either --input-csv or --project-dir must be supplied for DataForge dbt dispatch."
|
|
264
|
+
)
|
|
265
|
+
profiles_path = _resolve_profiles_path(request.profiles_path)
|
|
266
|
+
profile_name = request.profile_name or _read_project_profile(project_dir)
|
|
267
|
+
if request.run_dbt:
|
|
268
|
+
_run_dbt(project_dir, profiles_path.parent, request.select)
|
|
269
|
+
|
|
270
|
+
output = _read_duckdb_output(profiles_path, profile_name)
|
|
271
|
+
if output.get("type") != "duckdb":
|
|
272
|
+
raise DataForgeDbtDispatchError(
|
|
273
|
+
"Native DataForge dbt apply currently supports dbt-duckdb only."
|
|
274
|
+
)
|
|
275
|
+
database_path = output.get("path")
|
|
276
|
+
if not isinstance(database_path, str) or not database_path:
|
|
277
|
+
raise DataForgeDbtDispatchError("dbt-duckdb profile output is missing path.")
|
|
278
|
+
|
|
279
|
+
row_ids = request.row_identity_columns or config.row_identity_columns or ("id",)
|
|
280
|
+
try:
|
|
281
|
+
store = DuckDBStore(
|
|
282
|
+
database_path=Path(database_path),
|
|
283
|
+
relation=request.relation,
|
|
284
|
+
row_identity_columns=row_ids,
|
|
285
|
+
)
|
|
286
|
+
store_result = run_table_store_repair(
|
|
287
|
+
store,
|
|
288
|
+
mode="dry_run" if config.mode == "refuse" else config.mode,
|
|
289
|
+
schema=None,
|
|
290
|
+
state_root=request.target_path,
|
|
291
|
+
only_column=request.column,
|
|
292
|
+
)
|
|
293
|
+
except TableStoreError as exc:
|
|
294
|
+
raise DataForgeDbtDispatchError(str(exc)) from exc
|
|
295
|
+
|
|
296
|
+
issues = store_result.issues
|
|
297
|
+
_log_issues(relation=request.relation, column=request.column, issues=issues)
|
|
298
|
+
|
|
299
|
+
if config.mode == "refuse" and any(issue.severity == Severity.UNSAFE for issue in issues):
|
|
300
|
+
raise DataForgeDbtDispatchError(
|
|
301
|
+
f"DataForge refuse mode blocked dbt relation '{request.relation}' because UNSAFE issues were detected."
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
if config.mode == "apply" and issues:
|
|
305
|
+
_write_transaction(
|
|
306
|
+
config.transaction_dir,
|
|
307
|
+
request=request,
|
|
308
|
+
issues=issues,
|
|
309
|
+
patch_plan=store_result.patch_plan.model_dump(mode="json"),
|
|
310
|
+
apply_receipt=store_result.apply_receipt.model_dump(mode="json")
|
|
311
|
+
if store_result.apply_receipt is not None
|
|
312
|
+
else None,
|
|
313
|
+
)
|
|
314
|
+
return issues
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _resolve_profiles_path(profiles_path: Path | None) -> Path:
|
|
318
|
+
"""Resolve dbt profiles.yml from a file path, directory, or default location."""
|
|
319
|
+
if profiles_path is None:
|
|
320
|
+
candidate = Path.home() / ".dbt" / "profiles.yml"
|
|
321
|
+
elif profiles_path.is_dir():
|
|
322
|
+
candidate = profiles_path / "profiles.yml"
|
|
323
|
+
else:
|
|
324
|
+
candidate = profiles_path
|
|
325
|
+
if not candidate.exists():
|
|
326
|
+
raise DataForgeDbtDispatchError(f"dbt profiles.yml not found: {candidate}")
|
|
327
|
+
return candidate
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _read_project_profile(project_dir: Path) -> str:
|
|
331
|
+
"""Read the dbt profile name from dbt_project.yml."""
|
|
332
|
+
project_file = project_dir / "dbt_project.yml"
|
|
333
|
+
if not project_file.exists():
|
|
334
|
+
raise DataForgeDbtDispatchError(f"dbt_project.yml not found: {project_file}")
|
|
335
|
+
payload = yaml.safe_load(project_file.read_text(encoding="utf-8"))
|
|
336
|
+
if not isinstance(payload, dict) or not payload.get("profile"):
|
|
337
|
+
raise DataForgeDbtDispatchError("dbt_project.yml must define a profile name.")
|
|
338
|
+
return str(payload["profile"])
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _run_dbt(project_dir: Path, profiles_dir: Path, selector: str | None) -> None:
|
|
342
|
+
"""Run dbt before exporting the selected relation."""
|
|
343
|
+
command = [
|
|
344
|
+
sys.executable,
|
|
345
|
+
"-m",
|
|
346
|
+
"dbt.cli.main",
|
|
347
|
+
"run",
|
|
348
|
+
"--project-dir",
|
|
349
|
+
str(project_dir),
|
|
350
|
+
"--profiles-dir",
|
|
351
|
+
str(profiles_dir),
|
|
352
|
+
]
|
|
353
|
+
if selector:
|
|
354
|
+
command.extend(["--select", selector])
|
|
355
|
+
env = os.environ.copy()
|
|
356
|
+
result = subprocess.run(
|
|
357
|
+
command,
|
|
358
|
+
cwd=project_dir,
|
|
359
|
+
env=env,
|
|
360
|
+
text=True,
|
|
361
|
+
capture_output=True,
|
|
362
|
+
timeout=180,
|
|
363
|
+
check=False,
|
|
364
|
+
)
|
|
365
|
+
if result.returncode != 0:
|
|
366
|
+
raise DataForgeDbtDispatchError(
|
|
367
|
+
"dbt run failed before DataForge export.\n"
|
|
368
|
+
f"STDOUT:\n{result.stdout}\n\nSTDERR:\n{result.stderr}"
|
|
369
|
+
)
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def _export_duckdb_relation(
|
|
373
|
+
*,
|
|
374
|
+
relation: str,
|
|
375
|
+
output_path: Path,
|
|
376
|
+
profiles_path: Path,
|
|
377
|
+
profile_name: str,
|
|
378
|
+
) -> None:
|
|
379
|
+
"""Export a relation from a dbt-duckdb profile."""
|
|
380
|
+
if not _safe_relation(relation):
|
|
381
|
+
raise DataForgeDbtDispatchError(f"Unsafe relation identifier: {relation}")
|
|
382
|
+
output = _read_duckdb_output(profiles_path, profile_name)
|
|
383
|
+
if output.get("type") != "duckdb":
|
|
384
|
+
raise DataForgeDbtDispatchError(
|
|
385
|
+
"DataForge dbt relation export currently supports dbt-duckdb profiles only."
|
|
386
|
+
)
|
|
387
|
+
database_path = output.get("path")
|
|
388
|
+
if not isinstance(database_path, str) or not database_path:
|
|
389
|
+
raise DataForgeDbtDispatchError("dbt-duckdb profile output is missing path.")
|
|
390
|
+
try:
|
|
391
|
+
import duckdb
|
|
392
|
+
except ImportError as exc:
|
|
393
|
+
raise DataForgeDbtDispatchError(
|
|
394
|
+
"DuckDB export requires dbt-duckdb or duckdb to be installed."
|
|
395
|
+
) from exc
|
|
396
|
+
try:
|
|
397
|
+
fd, temp_name = tempfile.mkstemp(suffix=".csv")
|
|
398
|
+
os.close(fd)
|
|
399
|
+
temp_output = Path(temp_name)
|
|
400
|
+
temp_output.unlink(missing_ok=True)
|
|
401
|
+
with duckdb.connect(database_path, read_only=True) as connection:
|
|
402
|
+
escaped_output = str(temp_output).replace("'", "''")
|
|
403
|
+
connection.execute(
|
|
404
|
+
f"COPY (SELECT * FROM {relation}) TO '{escaped_output}' (HEADER, DELIMITER ',')"
|
|
405
|
+
)
|
|
406
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
407
|
+
temp_output.replace(output_path)
|
|
408
|
+
except Exception as exc:
|
|
409
|
+
with suppress(NameError, FileNotFoundError):
|
|
410
|
+
temp_output.unlink()
|
|
411
|
+
raise DataForgeDbtDispatchError(
|
|
412
|
+
f"Could not export dbt relation '{relation}' from DuckDB: {exc}"
|
|
413
|
+
) from exc
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def _read_duckdb_output(profiles_path: Path, profile_name: str) -> dict[str, Any]:
|
|
417
|
+
"""Read the active output block from dbt profiles.yml."""
|
|
418
|
+
payload = yaml.safe_load(profiles_path.read_text(encoding="utf-8"))
|
|
419
|
+
if not isinstance(payload, dict):
|
|
420
|
+
raise DataForgeDbtDispatchError("dbt profiles.yml must be a mapping.")
|
|
421
|
+
profile = payload.get(profile_name)
|
|
422
|
+
if not isinstance(profile, dict):
|
|
423
|
+
raise DataForgeDbtDispatchError(f"dbt profile '{profile_name}' not found.")
|
|
424
|
+
target = str(profile.get("target", "dev"))
|
|
425
|
+
outputs = profile.get("outputs")
|
|
426
|
+
if not isinstance(outputs, dict) or not isinstance(outputs.get(target), dict):
|
|
427
|
+
raise DataForgeDbtDispatchError(
|
|
428
|
+
f"dbt profile '{profile_name}' output '{target}' not found."
|
|
429
|
+
)
|
|
430
|
+
return dict(outputs[target])
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def _safe_relation(relation: str) -> bool:
|
|
434
|
+
"""Return whether a dbt relation identifier is safe to embed in SQL."""
|
|
435
|
+
return bool(_SAFE_RELATION_RE.match(relation))
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _log_issues(*, relation: str, column: str, issues: list[Issue]) -> None:
|
|
439
|
+
"""Log detected issues in a stable dbt-testable format.
|
|
440
|
+
|
|
441
|
+
Args:
|
|
442
|
+
relation: dbt relation that was inspected.
|
|
443
|
+
column: Column passed to the macro.
|
|
444
|
+
issues: DataForge issues to log.
|
|
445
|
+
|
|
446
|
+
Returns:
|
|
447
|
+
None.
|
|
448
|
+
"""
|
|
449
|
+
if not issues:
|
|
450
|
+
_LOGGER.info("DATAFORGE_DBT no_issues relation=%s column=%s", relation, column)
|
|
451
|
+
return
|
|
452
|
+
|
|
453
|
+
for issue in issues:
|
|
454
|
+
_LOGGER.warning(
|
|
455
|
+
"DATAFORGE_DBT issue relation=%s column=%s row=%s type=%s severity=%s confidence=%.2f reason=%s",
|
|
456
|
+
relation,
|
|
457
|
+
column,
|
|
458
|
+
issue.row,
|
|
459
|
+
issue.issue_type,
|
|
460
|
+
issue.severity.value,
|
|
461
|
+
issue.confidence,
|
|
462
|
+
issue.reason,
|
|
463
|
+
)
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def _write_transaction(
|
|
467
|
+
transaction_dir: Path,
|
|
468
|
+
*,
|
|
469
|
+
request: DispatchRequest,
|
|
470
|
+
issues: list[Issue],
|
|
471
|
+
patch_plan: dict[str, object] | None = None,
|
|
472
|
+
apply_receipt: dict[str, object] | None = None,
|
|
473
|
+
) -> Path:
|
|
474
|
+
"""Write a dbt-scoped DataForge transaction artifact.
|
|
475
|
+
|
|
476
|
+
Args:
|
|
477
|
+
transaction_dir: Directory under dbt target for transaction files.
|
|
478
|
+
request: Original dispatch request.
|
|
479
|
+
issues: Issues detected during the hook.
|
|
480
|
+
|
|
481
|
+
Returns:
|
|
482
|
+
Path to the written JSONL transaction artifact.
|
|
483
|
+
|
|
484
|
+
Raises:
|
|
485
|
+
DataForgeDbtDispatchError: If the transaction file cannot be written.
|
|
486
|
+
"""
|
|
487
|
+
transaction_dir.mkdir(parents=True, exist_ok=True)
|
|
488
|
+
timestamp = datetime.now(UTC)
|
|
489
|
+
safe_relation = "".join(
|
|
490
|
+
ch if ch.isalnum() or ch in {"-", "_"} else "_" for ch in request.relation
|
|
491
|
+
)
|
|
492
|
+
output_path = transaction_dir / f"dataforge-dbt-{safe_relation}-{timestamp:%Y%m%d%H%M%S}.jsonl"
|
|
493
|
+
transaction = DbtTransaction(
|
|
494
|
+
relation=request.relation,
|
|
495
|
+
column=request.column,
|
|
496
|
+
mode="apply",
|
|
497
|
+
created_at=timestamp,
|
|
498
|
+
issues=[issue.model_dump(mode="json") for issue in issues],
|
|
499
|
+
patch_plan=patch_plan,
|
|
500
|
+
apply_receipt=apply_receipt,
|
|
501
|
+
)
|
|
502
|
+
try:
|
|
503
|
+
output_path.write_text(
|
|
504
|
+
json.dumps(transaction.model_dump(mode="json"), sort_keys=True) + "\n", encoding="utf-8"
|
|
505
|
+
)
|
|
506
|
+
except OSError as exc:
|
|
507
|
+
raise DataForgeDbtDispatchError(
|
|
508
|
+
f"Could not write DataForge dbt transaction file: {exc}"
|
|
509
|
+
) from exc
|
|
510
|
+
_LOGGER.info("DATAFORGE_DBT transaction_written path=%s", output_path)
|
|
511
|
+
return output_path
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
if __name__ == "__main__":
|
|
515
|
+
sys.exit(main())
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
{% macro dataforge_repair(column_name, mode='dry_run') %}
|
|
2
|
+
{% set valid_modes = ['dry_run', 'apply', 'refuse'] %}
|
|
3
|
+
{% if mode not in valid_modes %}
|
|
4
|
+
{{ exceptions.raise_compiler_error("dataforge_repair mode must be one of: dry_run, apply, refuse") }}
|
|
5
|
+
{% endif %}
|
|
6
|
+
{% set dispatch_command = "dataforge-dbt --relation " ~ this ~ " --column " ~ column_name ~ " --mode " ~ mode ~ " --target-path target --project-dir ." %}
|
|
7
|
+
{% do log("DATAFORGE_DBT dispatch_configured relation=" ~ this ~ " column=" ~ column_name ~ " mode=" ~ mode ~ " command=" ~ dispatch_command, info=True) %}
|
|
8
|
+
select 1 as dataforge_repair_hook
|
|
9
|
+
{% endmacro %}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "dataforge_07_dbt"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "dbt relation-export wrapper for DataForge data-quality repair audits."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
requires-python = ">=3.11,<3.13"
|
|
8
|
+
keywords = ["dataforge", "dbt", "data-quality", "duckdb"]
|
|
9
|
+
classifiers = [
|
|
10
|
+
"Development Status :: 3 - Alpha",
|
|
11
|
+
"Programming Language :: Python :: 3.11",
|
|
12
|
+
"Programming Language :: Python :: 3.12",
|
|
13
|
+
]
|
|
14
|
+
dependencies = [
|
|
15
|
+
"dataforge_07>=0.1.0,<0.2",
|
|
16
|
+
"dbt-duckdb>=1.8,<1.11",
|
|
17
|
+
"duckdb>=1.1",
|
|
18
|
+
"pydantic>=2.7",
|
|
19
|
+
"PyYAML>=6.0",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
Homepage = "https://github.com/Aegis15/dataforge"
|
|
24
|
+
Repository = "https://github.com/Aegis15/dataforge"
|
|
25
|
+
Documentation = "https://dataforge.praneshrajan15.workers.dev/playground"
|
|
26
|
+
|
|
27
|
+
[project.optional-dependencies]
|
|
28
|
+
dev = [
|
|
29
|
+
"pytest>=8.2",
|
|
30
|
+
"ruff>=0.11",
|
|
31
|
+
"mypy>=1.10,<1.20",
|
|
32
|
+
"types-PyYAML",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
[project.scripts]
|
|
36
|
+
dataforge-dbt = "dataforge_dbt.dispatch:main"
|
|
37
|
+
dataforge15-dbt = "dataforge_dbt.dispatch:main"
|
|
38
|
+
|
|
39
|
+
[build-system]
|
|
40
|
+
requires = ["setuptools>=68", "wheel"]
|
|
41
|
+
build-backend = "setuptools.build_meta"
|
|
42
|
+
|
|
43
|
+
[tool.setuptools.packages.find]
|
|
44
|
+
where = ["."]
|
|
45
|
+
include = ["dataforge_dbt*"]
|
|
46
|
+
|
|
47
|
+
[tool.setuptools.package-data]
|
|
48
|
+
dataforge_dbt = ["macros/*.sql"]
|
|
49
|
+
|
|
50
|
+
[tool.ruff]
|
|
51
|
+
line-length = 100
|
|
52
|
+
target-version = "py311"
|
|
53
|
+
|
|
54
|
+
[tool.ruff.lint]
|
|
55
|
+
select = ["E", "F", "W", "I", "N", "UP", "B", "A", "C4", "PIE", "RET", "SIM"]
|
|
56
|
+
ignore = ["E501"]
|
|
57
|
+
|
|
58
|
+
[tool.ruff.format]
|
|
59
|
+
quote-style = "double"
|
|
60
|
+
indent-style = "space"
|
|
61
|
+
line-ending = "auto"
|
|
62
|
+
|
|
63
|
+
[tool.mypy]
|
|
64
|
+
strict = true
|
|
65
|
+
python_version = "3.11"
|
|
66
|
+
warn_unused_configs = true
|
|
67
|
+
warn_redundant_casts = true
|
|
68
|
+
warn_unused_ignores = true
|
|
69
|
+
disallow_untyped_defs = true
|
|
70
|
+
explicit_package_bases = true
|
|
71
|
+
|
|
72
|
+
[[tool.mypy.overrides]]
|
|
73
|
+
module = ["dataforge.*"]
|
|
74
|
+
ignore_missing_imports = true
|
|
75
|
+
|
|
76
|
+
[[tool.mypy.overrides]]
|
|
77
|
+
module = ["duckdb", "yaml", "yaml.*"]
|
|
78
|
+
ignore_missing_imports = true
|
|
79
|
+
|
|
80
|
+
[tool.pytest.ini_options]
|
|
81
|
+
minversion = "8.0"
|
|
82
|
+
addopts = "-ra --strict-markers --strict-config"
|
|
83
|
+
testpaths = ["integration_tests"]
|
|
84
|
+
markers = [
|
|
85
|
+
"integration: marks tests as integration tests",
|
|
86
|
+
]
|