darwin-cleaner 0.4.0.dev0__tar.gz → 0.4.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.
- darwin_cleaner-0.4.1/PKG-INFO +134 -0
- darwin_cleaner-0.4.1/README.md +120 -0
- {darwin_cleaner-0.4.0.dev0 → darwin_cleaner-0.4.1}/pyproject.toml +1 -1
- {darwin_cleaner-0.4.0.dev0 → darwin_cleaner-0.4.1}/src/darwin_cleaner/__init__.py +6 -5
- {darwin_cleaner-0.4.0.dev0 → darwin_cleaner-0.4.1}/src/darwin_cleaner/context.py +7 -6
- {darwin_cleaner-0.4.0.dev0 → darwin_cleaner-0.4.1}/src/darwin_cleaner/contract.py +34 -25
- {darwin_cleaner-0.4.0.dev0 → darwin_cleaner-0.4.1}/src/darwin_cleaner/engine.py +44 -40
- darwin_cleaner-0.4.1/src/darwin_cleaner/exceptions.py +49 -0
- {darwin_cleaner-0.4.0.dev0 → darwin_cleaner-0.4.1}/src/darwin_cleaner/middleware.py +59 -50
- {darwin_cleaner-0.4.0.dev0 → darwin_cleaner-0.4.1}/src/darwin_cleaner/request.py +17 -12
- {darwin_cleaner-0.4.0.dev0 → darwin_cleaner-0.4.1}/src/darwin_cleaner/results.py +30 -26
- {darwin_cleaner-0.4.0.dev0 → darwin_cleaner-0.4.1}/src/darwin_cleaner/rules.py +21 -17
- {darwin_cleaner-0.4.0.dev0 → darwin_cleaner-0.4.1}/src/darwin_cleaner/steps.py +40 -39
- darwin_cleaner-0.4.1/src/darwin_cleaner.egg-info/PKG-INFO +134 -0
- {darwin_cleaner-0.4.0.dev0 → darwin_cleaner-0.4.1}/tests/test_contracts.py +60 -60
- {darwin_cleaner-0.4.0.dev0 → darwin_cleaner-0.4.1}/tests/test_engine.py +188 -188
- {darwin_cleaner-0.4.0.dev0 → darwin_cleaner-0.4.1}/tests/test_error_modes.py +92 -92
- {darwin_cleaner-0.4.0.dev0 → darwin_cleaner-0.4.1}/tests/test_registry.py +98 -98
- {darwin_cleaner-0.4.0.dev0 → darwin_cleaner-0.4.1}/tests/test_rules.py +26 -26
- {darwin_cleaner-0.4.0.dev0 → darwin_cleaner-0.4.1}/tests/test_steps.py +185 -185
- darwin_cleaner-0.4.0.dev0/PKG-INFO +0 -120
- darwin_cleaner-0.4.0.dev0/README.md +0 -106
- darwin_cleaner-0.4.0.dev0/src/darwin_cleaner/exceptions.py +0 -47
- darwin_cleaner-0.4.0.dev0/src/darwin_cleaner.egg-info/PKG-INFO +0 -120
- {darwin_cleaner-0.4.0.dev0 → darwin_cleaner-0.4.1}/LICENSE +0 -0
- {darwin_cleaner-0.4.0.dev0 → darwin_cleaner-0.4.1}/setup.cfg +0 -0
- {darwin_cleaner-0.4.0.dev0 → darwin_cleaner-0.4.1}/src/darwin_cleaner.egg-info/SOURCES.txt +0 -0
- {darwin_cleaner-0.4.0.dev0 → darwin_cleaner-0.4.1}/src/darwin_cleaner.egg-info/dependency_links.txt +0 -0
- {darwin_cleaner-0.4.0.dev0 → darwin_cleaner-0.4.1}/src/darwin_cleaner.egg-info/requires.txt +0 -0
- {darwin_cleaner-0.4.0.dev0 → darwin_cleaner-0.4.1}/src/darwin_cleaner.egg-info/top_level.txt +0 -0
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: darwin-cleaner
|
|
3
|
+
Version: 0.4.1
|
|
4
|
+
Summary: 契约与规则驱动的单文件清洗引擎:读取 parquet → 分叉 → 按 order 跑 middleware → 返回数据与 meta
|
|
5
|
+
License: MIT
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: pandas>=2.0
|
|
10
|
+
Requires-Dist: pyarrow>=12
|
|
11
|
+
Provides-Extra: test
|
|
12
|
+
Requires-Dist: pytest>=8; extra == "test"
|
|
13
|
+
Dynamic: license-file
|
|
14
|
+
|
|
15
|
+
# darwin-cleaner
|
|
16
|
+
|
|
17
|
+
[English](README.md) · [简体中文](README.cn.md)
|
|
18
|
+
|
|
19
|
+
A contract- and rules-driven **single-file cleaning engine**: read one parquet file (or an in-memory DataFrame) → split rows / columns → run middlewares by `order` → return data and meta in memory.
|
|
20
|
+
|
|
21
|
+
Python >= 3.10.
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
pip install darwin-cleaner
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Scope
|
|
28
|
+
|
|
29
|
+
This library only transforms data. Upstream and downstream concerns stay outside:
|
|
30
|
+
|
|
31
|
+
| In the library | Outside (caller's responsibility) |
|
|
32
|
+
|---|---|
|
|
33
|
+
| Read a single parquet / accept a DataFrame | Merge multiple files, discover files, check freshness |
|
|
34
|
+
| Row forks / column forks | Load `cleaner.json` / `clean.d/*.json` / adapter configs |
|
|
35
|
+
| 12 built-in middlewares (`dedupe` disabled by default) | Write parquet / csv / meta / checkpoints |
|
|
36
|
+
| Contract and rules validation, stats and report generation | CLI, scheduling, exit codes, business identifiers |
|
|
37
|
+
|
|
38
|
+
See [docs/design.md](docs/design.md) for the design and [docs/clean-stage-code-walkthrough.md](docs/clean-stage-code-walkthrough.md) for a walkthrough of the original clean-stage code. Run the [examples](examples/README.md) to see the engine in action.
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## 1. Quick start
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from pathlib import Path
|
|
46
|
+
from darwin_cleaner import (
|
|
47
|
+
CleaningEngine, CleanRequest, CleanOptions, Contract, FieldSpec,
|
|
48
|
+
MiddlewareOverride, MiddlewareRegistryImpl, Rules, TypeSpec,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
registry = MiddlewareRegistryImpl()
|
|
52
|
+
registry.builtins() # 12 built-in steps; dedupe is off by default
|
|
53
|
+
|
|
54
|
+
contract = Contract(
|
|
55
|
+
name="stk_ohlcv",
|
|
56
|
+
fields={
|
|
57
|
+
"symbol": FieldSpec(name="symbol", type="str"),
|
|
58
|
+
"trade_date": FieldSpec(name="trade_date", type="str"),
|
|
59
|
+
"close": FieldSpec(name="close", type="float"),
|
|
60
|
+
},
|
|
61
|
+
types={"float": TypeSpec(name="float", converter="numeric", min=0)},
|
|
62
|
+
output=("symbol", "trade_date", "close"),
|
|
63
|
+
keys=("symbol", "trade_date"), # columns in keys are implicitly required
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
engine = CleaningEngine(registry)
|
|
67
|
+
result = engine.clean(CleanRequest(
|
|
68
|
+
input=Path("raw.parquet"),
|
|
69
|
+
contracts={"stk_ohlcv": contract},
|
|
70
|
+
rules=Rules(),
|
|
71
|
+
options=CleanOptions(
|
|
72
|
+
middleware_overrides={
|
|
73
|
+
"dedupe": MiddlewareOverride(
|
|
74
|
+
enabled=True,
|
|
75
|
+
params={"scope": "keys", "strategy": "last"},
|
|
76
|
+
),
|
|
77
|
+
},
|
|
78
|
+
),
|
|
79
|
+
))
|
|
80
|
+
|
|
81
|
+
for out in result.outputs:
|
|
82
|
+
if out.status == "success":
|
|
83
|
+
df = out.data # pandas.DataFrame
|
|
84
|
+
meta = out.meta # content hash + rule fingerprint + stats
|
|
85
|
+
report = out.report # audit trail
|
|
86
|
+
# Persistence is the caller's responsibility.
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
---
|
|
90
|
+
|
|
91
|
+
## 2. Core concepts
|
|
92
|
+
|
|
93
|
+
- **Contract** — fields, types, output columns, unique-row keys and sort order. The caller parses config files and injects contracts; the engine never reads configuration.
|
|
94
|
+
- **FieldSpec.required** — tri-state. `True`: a missing column is an error. `False`: explicitly optional (filled with nulls). `None`: not declared; the engine infers it — columns used in `sort` or `keys` become `True`, all others `False`.
|
|
95
|
+
- **Rules** — `mapping` / `value_map` / `transform` / `filters` / `outputs`, etc. They replace global config lookups inside middlewares.
|
|
96
|
+
- **Middleware** — unified signature `(df, ctx, params) -> df | None`. `order` decides execution position, `params` are declarative (and part of the rule fingerprint), `enabled` is the on/off switch, and `MiddlewareOverride` can change both per request.
|
|
97
|
+
- **Order bands** — `10-19` preprocessing, `20-29` dtype, `30-39` fill, `40-49` formulas, `50-69` validation / dedupe, `90-99` output.
|
|
98
|
+
|
|
99
|
+
---
|
|
100
|
+
|
|
101
|
+
## 3. Built-in middlewares
|
|
102
|
+
|
|
103
|
+
| Order | Name | Purpose | Default |
|
|
104
|
+
|---|---|---|---|
|
|
105
|
+
| 10 | `field_mapping` | Rename fields | on |
|
|
106
|
+
| 12 | `value_mapping` | Replace values | on |
|
|
107
|
+
| 15 | `field_transform` | Constants / scale / actions | on |
|
|
108
|
+
| 20 | `type_conversion` | Normalize dtypes | on |
|
|
109
|
+
| 30 | `fill` | Group-wise forward fill | on |
|
|
110
|
+
| 40 | `formula_compute` | Compute all-null columns from formulas | on |
|
|
111
|
+
| 45 | `formula_validate` | Validate formulas with dual tolerance | on |
|
|
112
|
+
| 50 | `consistency` | Cross-field consistency | on |
|
|
113
|
+
| 60 | `type_validate` | Null out inf / out-of-range values | on |
|
|
114
|
+
| 70 | `dedupe` | Deduplicate by keys | **off** |
|
|
115
|
+
| 90 | `output` | Select columns per contract | on |
|
|
116
|
+
| 95 | `sort` | Sort per contract | on |
|
|
117
|
+
|
|
118
|
+
`builtins()` registers all 12. Disabled middlewares are skipped at the registry level: they do not enter the plan and are never called. User middlewares can be loaded from a directory with `load_middlewares_from_dir(path)` and registered explicitly. Duplicate names raise `CleanerRuleError` at registration time.
|
|
119
|
+
|
|
120
|
+
---
|
|
121
|
+
|
|
122
|
+
## 4. Testing
|
|
123
|
+
|
|
124
|
+
```bash
|
|
125
|
+
PYTHONPATH=src pytest
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
The suite covers contracts, fork plans, the registry (built-ins, switches, overrides, conflicts, fingerprints, directory loading), all 12 built-in steps, end-to-end engine paths (row + column forks, parquet input, zero-row failure, missing required columns) and strict / lenient error modes.
|
|
129
|
+
|
|
130
|
+
---
|
|
131
|
+
|
|
132
|
+
## 5. License
|
|
133
|
+
|
|
134
|
+
MIT
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
# darwin-cleaner
|
|
2
|
+
|
|
3
|
+
[English](README.md) · [简体中文](README.cn.md)
|
|
4
|
+
|
|
5
|
+
A contract- and rules-driven **single-file cleaning engine**: read one parquet file (or an in-memory DataFrame) → split rows / columns → run middlewares by `order` → return data and meta in memory.
|
|
6
|
+
|
|
7
|
+
Python >= 3.10.
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install darwin-cleaner
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Scope
|
|
14
|
+
|
|
15
|
+
This library only transforms data. Upstream and downstream concerns stay outside:
|
|
16
|
+
|
|
17
|
+
| In the library | Outside (caller's responsibility) |
|
|
18
|
+
|---|---|
|
|
19
|
+
| Read a single parquet / accept a DataFrame | Merge multiple files, discover files, check freshness |
|
|
20
|
+
| Row forks / column forks | Load `cleaner.json` / `clean.d/*.json` / adapter configs |
|
|
21
|
+
| 12 built-in middlewares (`dedupe` disabled by default) | Write parquet / csv / meta / checkpoints |
|
|
22
|
+
| Contract and rules validation, stats and report generation | CLI, scheduling, exit codes, business identifiers |
|
|
23
|
+
|
|
24
|
+
See [docs/design.md](docs/design.md) for the design and [docs/clean-stage-code-walkthrough.md](docs/clean-stage-code-walkthrough.md) for a walkthrough of the original clean-stage code. Run the [examples](examples/README.md) to see the engine in action.
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
## 1. Quick start
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
from darwin_cleaner import (
|
|
33
|
+
CleaningEngine, CleanRequest, CleanOptions, Contract, FieldSpec,
|
|
34
|
+
MiddlewareOverride, MiddlewareRegistryImpl, Rules, TypeSpec,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
registry = MiddlewareRegistryImpl()
|
|
38
|
+
registry.builtins() # 12 built-in steps; dedupe is off by default
|
|
39
|
+
|
|
40
|
+
contract = Contract(
|
|
41
|
+
name="stk_ohlcv",
|
|
42
|
+
fields={
|
|
43
|
+
"symbol": FieldSpec(name="symbol", type="str"),
|
|
44
|
+
"trade_date": FieldSpec(name="trade_date", type="str"),
|
|
45
|
+
"close": FieldSpec(name="close", type="float"),
|
|
46
|
+
},
|
|
47
|
+
types={"float": TypeSpec(name="float", converter="numeric", min=0)},
|
|
48
|
+
output=("symbol", "trade_date", "close"),
|
|
49
|
+
keys=("symbol", "trade_date"), # columns in keys are implicitly required
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
engine = CleaningEngine(registry)
|
|
53
|
+
result = engine.clean(CleanRequest(
|
|
54
|
+
input=Path("raw.parquet"),
|
|
55
|
+
contracts={"stk_ohlcv": contract},
|
|
56
|
+
rules=Rules(),
|
|
57
|
+
options=CleanOptions(
|
|
58
|
+
middleware_overrides={
|
|
59
|
+
"dedupe": MiddlewareOverride(
|
|
60
|
+
enabled=True,
|
|
61
|
+
params={"scope": "keys", "strategy": "last"},
|
|
62
|
+
),
|
|
63
|
+
},
|
|
64
|
+
),
|
|
65
|
+
))
|
|
66
|
+
|
|
67
|
+
for out in result.outputs:
|
|
68
|
+
if out.status == "success":
|
|
69
|
+
df = out.data # pandas.DataFrame
|
|
70
|
+
meta = out.meta # content hash + rule fingerprint + stats
|
|
71
|
+
report = out.report # audit trail
|
|
72
|
+
# Persistence is the caller's responsibility.
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
## 2. Core concepts
|
|
78
|
+
|
|
79
|
+
- **Contract** — fields, types, output columns, unique-row keys and sort order. The caller parses config files and injects contracts; the engine never reads configuration.
|
|
80
|
+
- **FieldSpec.required** — tri-state. `True`: a missing column is an error. `False`: explicitly optional (filled with nulls). `None`: not declared; the engine infers it — columns used in `sort` or `keys` become `True`, all others `False`.
|
|
81
|
+
- **Rules** — `mapping` / `value_map` / `transform` / `filters` / `outputs`, etc. They replace global config lookups inside middlewares.
|
|
82
|
+
- **Middleware** — unified signature `(df, ctx, params) -> df | None`. `order` decides execution position, `params` are declarative (and part of the rule fingerprint), `enabled` is the on/off switch, and `MiddlewareOverride` can change both per request.
|
|
83
|
+
- **Order bands** — `10-19` preprocessing, `20-29` dtype, `30-39` fill, `40-49` formulas, `50-69` validation / dedupe, `90-99` output.
|
|
84
|
+
|
|
85
|
+
---
|
|
86
|
+
|
|
87
|
+
## 3. Built-in middlewares
|
|
88
|
+
|
|
89
|
+
| Order | Name | Purpose | Default |
|
|
90
|
+
|---|---|---|---|
|
|
91
|
+
| 10 | `field_mapping` | Rename fields | on |
|
|
92
|
+
| 12 | `value_mapping` | Replace values | on |
|
|
93
|
+
| 15 | `field_transform` | Constants / scale / actions | on |
|
|
94
|
+
| 20 | `type_conversion` | Normalize dtypes | on |
|
|
95
|
+
| 30 | `fill` | Group-wise forward fill | on |
|
|
96
|
+
| 40 | `formula_compute` | Compute all-null columns from formulas | on |
|
|
97
|
+
| 45 | `formula_validate` | Validate formulas with dual tolerance | on |
|
|
98
|
+
| 50 | `consistency` | Cross-field consistency | on |
|
|
99
|
+
| 60 | `type_validate` | Null out inf / out-of-range values | on |
|
|
100
|
+
| 70 | `dedupe` | Deduplicate by keys | **off** |
|
|
101
|
+
| 90 | `output` | Select columns per contract | on |
|
|
102
|
+
| 95 | `sort` | Sort per contract | on |
|
|
103
|
+
|
|
104
|
+
`builtins()` registers all 12. Disabled middlewares are skipped at the registry level: they do not enter the plan and are never called. User middlewares can be loaded from a directory with `load_middlewares_from_dir(path)` and registered explicitly. Duplicate names raise `CleanerRuleError` at registration time.
|
|
105
|
+
|
|
106
|
+
---
|
|
107
|
+
|
|
108
|
+
## 4. Testing
|
|
109
|
+
|
|
110
|
+
```bash
|
|
111
|
+
PYTHONPATH=src pytest
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
The suite covers contracts, fork plans, the registry (built-ins, switches, overrides, conflicts, fingerprints, directory loading), all 12 built-in steps, end-to-end engine paths (row + column forks, parquet input, zero-row failure, missing required columns) and strict / lenient error modes.
|
|
115
|
+
|
|
116
|
+
---
|
|
117
|
+
|
|
118
|
+
## 5. License
|
|
119
|
+
|
|
120
|
+
MIT
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
# src/darwin_cleaner/__init__.py
|
|
2
2
|
|
|
3
3
|
"""
|
|
4
|
-
darwin-cleaner
|
|
4
|
+
darwin-cleaner: a contract- and rule-driven single-file cleaning engine.
|
|
5
5
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
6
|
+
Scope: read a single parquet -> row forks / column forks -> run middleware by
|
|
7
|
+
order -> return data and meta. No business concepts such as source / clean_type;
|
|
8
|
+
no configuration loading, file discovery, scheduling, checkpoints, CLI, or
|
|
9
|
+
persistence to disk.
|
|
9
10
|
"""
|
|
10
11
|
|
|
11
12
|
from __future__ import annotations
|
|
@@ -59,7 +60,7 @@ from darwin_cleaner.rules import (
|
|
|
59
60
|
TransformSpec,
|
|
60
61
|
)
|
|
61
62
|
|
|
62
|
-
__version__ = "0.4.
|
|
63
|
+
__version__ = "0.4.1"
|
|
63
64
|
|
|
64
65
|
__all__ = [
|
|
65
66
|
"__version__",
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
# src/darwin_cleaner/context.py
|
|
2
2
|
|
|
3
3
|
"""
|
|
4
|
-
|
|
4
|
+
Execution context: middleware reads the contract, rules, and report from ctx.
|
|
5
5
|
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
Contains no business identifiers (source / clean_type / date / filename),
|
|
7
|
+
and no IO options (output_path / overwrite / check_only / csv_mode).
|
|
8
8
|
"""
|
|
9
9
|
|
|
10
10
|
from __future__ import annotations
|
|
@@ -21,7 +21,7 @@ if TYPE_CHECKING:
|
|
|
21
21
|
|
|
22
22
|
|
|
23
23
|
class Logger(Protocol):
|
|
24
|
-
"""
|
|
24
|
+
"""Minimal logging protocol to avoid binding to a specific logging library."""
|
|
25
25
|
|
|
26
26
|
def debug(self, msg: str, *args: Any) -> None: ...
|
|
27
27
|
|
|
@@ -35,9 +35,10 @@ class Logger(Protocol):
|
|
|
35
35
|
@dataclass
|
|
36
36
|
class CleanContext:
|
|
37
37
|
"""
|
|
38
|
-
|
|
38
|
+
Runtime context for a single fork.
|
|
39
39
|
|
|
40
|
-
output_key
|
|
40
|
+
output_key is only an identifier for this output, used by the report;
|
|
41
|
+
it carries no business semantics.
|
|
41
42
|
"""
|
|
42
43
|
|
|
43
44
|
output_key: str
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
# src/darwin_cleaner/contract.py
|
|
2
2
|
|
|
3
3
|
"""
|
|
4
|
-
|
|
4
|
+
Contract value objects: describe "what a piece of data should look like".
|
|
5
5
|
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
These types are parsed by the upper layer and injected into the engine;
|
|
7
|
+
the engine is not responsible for reading files.
|
|
8
|
+
All objects are frozen and immutable during execution.
|
|
8
9
|
|
|
9
|
-
|
|
10
|
+
Note: Contract.name is only a label for diagnostics, not a business concept
|
|
11
|
+
such as clean_type / source.
|
|
10
12
|
"""
|
|
11
13
|
|
|
12
14
|
from __future__ import annotations
|
|
@@ -20,7 +22,7 @@ SortDirection = Literal["ascending", "descending"]
|
|
|
20
22
|
|
|
21
23
|
@dataclass(frozen=True)
|
|
22
24
|
class FillSpec:
|
|
23
|
-
"""
|
|
25
|
+
"""Field fill rule."""
|
|
24
26
|
|
|
25
27
|
strategy: Literal["ffill", "value", "none"] = "ffill"
|
|
26
28
|
max_days: int = 5
|
|
@@ -29,7 +31,7 @@ class FillSpec:
|
|
|
29
31
|
|
|
30
32
|
@dataclass(frozen=True)
|
|
31
33
|
class TypeSpec:
|
|
32
|
-
"""
|
|
34
|
+
"""Type definition."""
|
|
33
35
|
|
|
34
36
|
name: str
|
|
35
37
|
converter: str | None = None
|
|
@@ -43,10 +45,11 @@ class TypeSpec:
|
|
|
43
45
|
@dataclass(frozen=True)
|
|
44
46
|
class FieldSpec:
|
|
45
47
|
"""
|
|
46
|
-
|
|
48
|
+
Contract for a single field.
|
|
47
49
|
|
|
48
|
-
type_def
|
|
49
|
-
|
|
50
|
+
type_def keeps the original definition dict for upper-layer compatibility
|
|
51
|
+
and diagnostics; commonly used constraints are also promoted to explicit
|
|
52
|
+
fields so that rules can read them directly.
|
|
50
53
|
"""
|
|
51
54
|
|
|
52
55
|
name: str
|
|
@@ -59,19 +62,20 @@ class FieldSpec:
|
|
|
59
62
|
on_violation: ViolationAction = "null"
|
|
60
63
|
required: bool | None = None
|
|
61
64
|
"""
|
|
62
|
-
|
|
65
|
+
Whether this column must be present in the output data (tri-state).
|
|
63
66
|
|
|
64
|
-
True
|
|
65
|
-
False
|
|
66
|
-
None
|
|
67
|
+
True -- missing is an error;
|
|
68
|
+
False -- missing is explicitly allowed, and an empty column is added;
|
|
69
|
+
None -- not declared; derived by Contract: True for sort / keys fields,
|
|
70
|
+
False for all others.
|
|
67
71
|
|
|
68
|
-
|
|
72
|
+
Use Contract.is_required(field) for the final value.
|
|
69
73
|
"""
|
|
70
74
|
|
|
71
75
|
|
|
72
76
|
@dataclass(frozen=True)
|
|
73
77
|
class SortSpec:
|
|
74
|
-
"""
|
|
78
|
+
"""Single-field sort declaration; the order of multiple SortSpecs is the sort priority."""
|
|
75
79
|
|
|
76
80
|
field: str
|
|
77
81
|
direction: SortDirection = "ascending"
|
|
@@ -80,9 +84,10 @@ class SortSpec:
|
|
|
80
84
|
@dataclass(frozen=True)
|
|
81
85
|
class Contract:
|
|
82
86
|
"""
|
|
83
|
-
|
|
87
|
+
Generic contract view: fields, types, output columns, sorting.
|
|
84
88
|
|
|
85
|
-
fields / types
|
|
89
|
+
fields / types are merged by the upper layer and then injected; this
|
|
90
|
+
library only accepts the merged immutable view.
|
|
86
91
|
"""
|
|
87
92
|
|
|
88
93
|
name: str = ""
|
|
@@ -91,24 +96,27 @@ class Contract:
|
|
|
91
96
|
output: tuple[str, ...] = ()
|
|
92
97
|
keys: tuple[str, ...] = ()
|
|
93
98
|
"""
|
|
94
|
-
|
|
99
|
+
Columns that distinguish unique rows (composite key). An empty tuple means
|
|
100
|
+
unique rows are not distinguished and duplicate rows are allowed.
|
|
95
101
|
|
|
96
|
-
|
|
97
|
-
|
|
102
|
+
When non-empty, these columns must appear in output; their required status
|
|
103
|
+
is derived as True by is_required(). Whether/how to deduplicate is controlled
|
|
104
|
+
by the params of the dedupe middleware (disabled by default).
|
|
98
105
|
"""
|
|
99
106
|
sort: tuple[SortSpec, ...] = ()
|
|
100
107
|
enabled: bool = True
|
|
101
108
|
help: str = ""
|
|
102
109
|
|
|
103
110
|
def output_specs(self) -> tuple[FieldSpec, ...]:
|
|
104
|
-
"""
|
|
111
|
+
"""Return field definitions in output order."""
|
|
105
112
|
return tuple(self.fields[name] for name in self.output if name in self.fields)
|
|
106
113
|
|
|
107
114
|
def is_required(self, field: str) -> bool:
|
|
108
115
|
"""
|
|
109
|
-
|
|
116
|
+
Final required status of a field.
|
|
110
117
|
|
|
111
|
-
|
|
118
|
+
An explicit declaration takes precedence; otherwise fields participating
|
|
119
|
+
in sort or keys are derived as True, and all others as False.
|
|
112
120
|
"""
|
|
113
121
|
spec = self.fields.get(field)
|
|
114
122
|
if spec is not None and spec.required is not None:
|
|
@@ -121,9 +129,10 @@ class Contract:
|
|
|
121
129
|
|
|
122
130
|
def dedupe_keys(self) -> tuple[str, ...]:
|
|
123
131
|
"""
|
|
124
|
-
|
|
132
|
+
Return the deduplication keys declared by the contract.
|
|
125
133
|
|
|
126
|
-
|
|
134
|
+
For reference by the upper layer and the dedupe middleware only;
|
|
135
|
+
dedupe's params.keys takes precedence.
|
|
127
136
|
"""
|
|
128
137
|
return self.keys
|
|
129
138
|
|