map-conform 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- map_conform/__init__.py +5 -0
- map_conform/__main__.py +7 -0
- map_conform/batch/__init__.py +1 -0
- map_conform/batch/arrow.py +80 -0
- map_conform/batch/columnar.py +125 -0
- map_conform/batch/engine.py +191 -0
- map_conform/batch/files.py +207 -0
- map_conform/cli.py +460 -0
- map_conform/doctor.py +178 -0
- map_conform/errors.py +107 -0
- map_conform/expr/__init__.py +6 -0
- map_conform/expr/compiler.py +562 -0
- map_conform/expr/functions.py +542 -0
- map_conform/expr/sandbox.py +333 -0
- map_conform/expr/sdk.py +116 -0
- map_conform/map-conform-spec.schema.json +1204 -0
- map_conform/mapper.py +355 -0
- map_conform/metadata.py +73 -0
- map_conform/metrics.py +62 -0
- map_conform/naming/__init__.py +1 -0
- map_conform/naming/ascii-table.json +980 -0
- map_conform/naming/conform.py +262 -0
- map_conform/naming/flatten.py +148 -0
- map_conform/naming/nested.py +117 -0
- map_conform/naming/reserved/ansi.txt +369 -0
- map_conform/naming/reserved/duckdb.txt +114 -0
- map_conform/naming/reserved/postgres.txt +105 -0
- map_conform/naming/reserved/snowflake.txt +90 -0
- map_conform/naming/reserved.py +34 -0
- map_conform/naming/shape.py +96 -0
- map_conform/naming/streams.py +76 -0
- map_conform/naming/translit.py +170 -0
- map_conform/plan/__init__.py +1 -0
- map_conform/plan/chain.py +667 -0
- map_conform/plan/compile.py +551 -0
- map_conform/plan/lower.py +281 -0
- map_conform/plan/ops.py +336 -0
- map_conform/plan/row.py +212 -0
- map_conform/plan/vector.py +71 -0
- map_conform/rejects.py +92 -0
- map_conform/settings.py +157 -0
- map_conform/spec/__init__.py +1 -0
- map_conform/spec/_struct.py +483 -0
- map_conform/spec/bridge.py +109 -0
- map_conform/spec/check.py +380 -0
- map_conform/spec/errors.py +22 -0
- map_conform/spec/importer.py +87 -0
- map_conform/spec/jsonschema.py +54 -0
- map_conform/spec/load.py +357 -0
- map_conform/spec/model.py +473 -0
- map_conform/spec/reference.py +179 -0
- map_conform/spec/steps.py +297 -0
- map_conform/spec/stream_maps.py +233 -0
- map_conform/spec/zamboni.py +99 -0
- map_conform/transforms/__init__.py +1 -0
- map_conform/transforms/builtins.py +63 -0
- map_conform/transforms/casts.py +310 -0
- map_conform/transforms/fake.py +150 -0
- map_conform/transforms/nested.py +111 -0
- map_conform/transforms/numeric.py +318 -0
- map_conform/transforms/polars_vector.py +151 -0
- map_conform/transforms/privacy.py +220 -0
- map_conform/transforms/registry.py +116 -0
- map_conform/transforms/temporal.py +410 -0
- map_conform/transforms/text.py +249 -0
- map_conform/transforms/vector.py +386 -0
- map_conform/types/__init__.py +1 -0
- map_conform/types/canonical.py +255 -0
- map_conform/types/from_jsonschema.py +177 -0
- map_conform/types/jsontext.py +63 -0
- map_conform/types/to_arrow.py +52 -0
- map_conform/types/to_jsonschema.py +65 -0
- map_conform/types/wire.py +53 -0
- map_conform/udfs.py +327 -0
- map_conform-0.1.0.dist-info/METADATA +157 -0
- map_conform-0.1.0.dist-info/RECORD +79 -0
- map_conform-0.1.0.dist-info/WHEEL +4 -0
- map_conform-0.1.0.dist-info/entry_points.txt +2 -0
- map_conform-0.1.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""Lower ``case`` steps to ``pyarrow.compute.case_when`` (detailed design §7, WBS 8.6).
|
|
2
|
+
|
|
3
|
+
A ``case`` is vectorised when every branch chain is, and every ``when`` lowers to an Arrow
|
|
4
|
+
mask. The whens are evaluated as masks over the whole column, each branch runs on the
|
|
5
|
+
whole column, and the first branch whose mask holds supplies the value, as ``case_when``
|
|
6
|
+
does. Like every vector op, a lowered ``when`` claims only rows where it agrees with Python:
|
|
7
|
+
|
|
8
|
+
- ``is_null(value)``; ``is_blank(value)`` (ASCII text);
|
|
9
|
+
- ``value == x``, ``value != x``, ``value in [...]``, ``value not in [...]`` with string or
|
|
10
|
+
number literals of the column's kind; ordered comparisons (``<``, ``>=``, ...) leave null
|
|
11
|
+
rows to the scalar path, where Python raises;
|
|
12
|
+
- ``matches(pattern, value)`` on text without line breaks, when the pattern compiles as RE2;
|
|
13
|
+
- ``not``, ``and``, ``or`` of those.
|
|
14
|
+
|
|
15
|
+
A when that reads another column, or uses anything else, keeps the whole case row-wise.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import ast
|
|
21
|
+
from collections.abc import Callable
|
|
22
|
+
from typing import TYPE_CHECKING, Any
|
|
23
|
+
|
|
24
|
+
import pyarrow as pa
|
|
25
|
+
import pyarrow.compute as _compute
|
|
26
|
+
|
|
27
|
+
from map_conform.expr.compiler import parse_expression
|
|
28
|
+
from map_conform.plan.ops import CaseOp, CastArgs, CompiledStep
|
|
29
|
+
from map_conform.transforms import polars_vector
|
|
30
|
+
from map_conform.transforms.vector import CASTS, TRANSFORMS, Vector, everything, unsafe_text
|
|
31
|
+
|
|
32
|
+
if TYPE_CHECKING:
|
|
33
|
+
from map_conform.plan.ops import Op
|
|
34
|
+
from map_conform.types.canonical import CType
|
|
35
|
+
|
|
36
|
+
# The pyarrow stubs cannot follow array-in, array-out kernels; tests/parity checks this module.
|
|
37
|
+
_pa: Any = pa
|
|
38
|
+
pc: Any = _compute
|
|
39
|
+
|
|
40
|
+
Mask = Callable[[pa.Array], tuple[pa.Array, pa.Array]]
|
|
41
|
+
"""``column -> (mask, todo)``; the mask is non-null."""
|
|
42
|
+
|
|
43
|
+
_NO = pa.scalar(False) # noqa: FBT003 -- a fill value
|
|
44
|
+
_YES = pa.scalar(True) # noqa: FBT003 -- a fill value
|
|
45
|
+
|
|
46
|
+
_COMPARE = {
|
|
47
|
+
ast.Eq: "equal",
|
|
48
|
+
ast.NotEq: "not_equal",
|
|
49
|
+
ast.Lt: "less",
|
|
50
|
+
ast.LtE: "less_equal",
|
|
51
|
+
ast.Gt: "greater",
|
|
52
|
+
ast.GtE: "greater_equal",
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _false(column: pa.Array) -> pa.Array:
|
|
57
|
+
return _pa.repeat(_pa.scalar(value=False), len(column))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _is_text(column: pa.Array) -> bool:
|
|
61
|
+
return pa.types.is_string(column.type) or pa.types.is_large_string(column.type)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _is_number(column: pa.Array) -> bool:
|
|
65
|
+
kind = column.type
|
|
66
|
+
return pa.types.is_integer(kind) or pa.types.is_floating(kind) or pa.types.is_decimal(kind)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _literal(node: ast.expr) -> object:
|
|
70
|
+
value = ast.literal_eval(node)
|
|
71
|
+
if isinstance(value, bool) or not isinstance(value, (str, int, float)):
|
|
72
|
+
raise TypeError(value)
|
|
73
|
+
return value
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _fits(column: pa.Array, value: object) -> bool:
|
|
77
|
+
if isinstance(value, str):
|
|
78
|
+
return _is_text(column)
|
|
79
|
+
return _is_number(column)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _is_value(node: ast.expr) -> bool:
|
|
83
|
+
return isinstance(node, ast.Name) and node.id in {"value", "self"}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _compare(node: ast.Compare) -> Mask | None: # noqa: C901, PLR0911 -- one branch per form
|
|
87
|
+
if len(node.ops) != 1 or not _is_value(node.left):
|
|
88
|
+
return None
|
|
89
|
+
op, right = node.ops[0], node.comparators[0]
|
|
90
|
+
if isinstance(op, (ast.In, ast.NotIn)):
|
|
91
|
+
if not isinstance(right, (ast.List, ast.Tuple, ast.Set)):
|
|
92
|
+
return None
|
|
93
|
+
try:
|
|
94
|
+
values = [_literal(e) for e in right.elts]
|
|
95
|
+
except (TypeError, ValueError):
|
|
96
|
+
return None
|
|
97
|
+
|
|
98
|
+
def member(column: pa.Array) -> tuple[pa.Array, pa.Array]:
|
|
99
|
+
if not values or not all(_fits(column, v) for v in values):
|
|
100
|
+
return _false(column), everything(column)
|
|
101
|
+
hit = pc.fill_null(pc.is_in(column, value_set=_pa.array(values)), _NO)
|
|
102
|
+
return (pc.invert(hit) if isinstance(op, ast.NotIn) else hit), _false(column)
|
|
103
|
+
|
|
104
|
+
return member
|
|
105
|
+
name = _COMPARE.get(type(op))
|
|
106
|
+
if name is None:
|
|
107
|
+
return None
|
|
108
|
+
try:
|
|
109
|
+
literal = _literal(right)
|
|
110
|
+
except (TypeError, ValueError):
|
|
111
|
+
return None
|
|
112
|
+
|
|
113
|
+
def compare(column: pa.Array) -> tuple[pa.Array, pa.Array]:
|
|
114
|
+
if not _fits(column, literal):
|
|
115
|
+
return _false(column), everything(column)
|
|
116
|
+
result = getattr(pc, name)(column, literal)
|
|
117
|
+
if name == "not_equal": # None != x is True in Python
|
|
118
|
+
return pc.fill_null(result, _YES), _false(column)
|
|
119
|
+
if name == "equal":
|
|
120
|
+
return pc.fill_null(result, _NO), _false(column)
|
|
121
|
+
return pc.fill_null(result, _NO), pc.is_null(column) # Python raises on None
|
|
122
|
+
|
|
123
|
+
return compare
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _call(node: ast.Call) -> Mask | None: # noqa: C901, PLR0911 -- one branch per function
|
|
127
|
+
if not isinstance(node.func, ast.Name) or node.keywords:
|
|
128
|
+
return None
|
|
129
|
+
name, args = node.func.id, node.args
|
|
130
|
+
if name in {"is_null", "is_blank"} and len(args) == 1 and _is_value(args[0]):
|
|
131
|
+
if name == "is_null":
|
|
132
|
+
return lambda column: (pc.is_null(column), _false(column))
|
|
133
|
+
|
|
134
|
+
def blank(column: pa.Array) -> tuple[pa.Array, pa.Array]:
|
|
135
|
+
if not _is_text(column):
|
|
136
|
+
return pc.is_null(column), _false(column)
|
|
137
|
+
empty = pc.fill_null(pc.equal(pc.utf8_trim_whitespace(column), ""), _YES)
|
|
138
|
+
return empty, unsafe_text(column)
|
|
139
|
+
|
|
140
|
+
return blank
|
|
141
|
+
if name == "matches" and len(args) == 2 and _is_value(args[1]): # noqa: PLR2004
|
|
142
|
+
try:
|
|
143
|
+
pattern = _literal(args[0])
|
|
144
|
+
except (TypeError, ValueError):
|
|
145
|
+
return None
|
|
146
|
+
if not isinstance(pattern, str):
|
|
147
|
+
return None
|
|
148
|
+
try:
|
|
149
|
+
pc.match_substring_regex(_pa.array([""]), pattern)
|
|
150
|
+
except pa.ArrowInvalid:
|
|
151
|
+
return None # not RE2: keep Python's semantics
|
|
152
|
+
|
|
153
|
+
def match(column: pa.Array) -> tuple[pa.Array, pa.Array]:
|
|
154
|
+
if not _is_text(column):
|
|
155
|
+
return _false(column), everything(column)
|
|
156
|
+
found = pc.fill_null(pc.match_substring_regex(column, pattern), _NO)
|
|
157
|
+
breaks = pc.fill_null(pc.match_substring_regex(column, r"[\r\n]"), _NO)
|
|
158
|
+
return found, pc.or_(unsafe_text(column), breaks)
|
|
159
|
+
|
|
160
|
+
return match
|
|
161
|
+
return None
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def lower_expression(node: ast.expr) -> Mask | None: # noqa: PLR0911 -- one per node type
|
|
165
|
+
"""A mask for a when expression's AST, or None when it does not lower."""
|
|
166
|
+
if isinstance(node, ast.Compare):
|
|
167
|
+
return _compare(node)
|
|
168
|
+
if isinstance(node, ast.Call):
|
|
169
|
+
return _call(node)
|
|
170
|
+
if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
|
|
171
|
+
inner = lower_expression(node.operand)
|
|
172
|
+
if inner is None:
|
|
173
|
+
return None
|
|
174
|
+
return lambda column: _not(inner, column)
|
|
175
|
+
if isinstance(node, ast.BoolOp):
|
|
176
|
+
lowered = [lower_expression(v) for v in node.values]
|
|
177
|
+
parts = [p for p in lowered if p is not None]
|
|
178
|
+
if len(parts) != len(lowered):
|
|
179
|
+
return None
|
|
180
|
+
combine = pc.and_ if isinstance(node.op, ast.And) else pc.or_
|
|
181
|
+
return lambda column: _combine(combine, parts, column)
|
|
182
|
+
return None
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _not(inner: Mask, column: pa.Array) -> tuple[pa.Array, pa.Array]:
|
|
186
|
+
mask, todo = inner(column)
|
|
187
|
+
return pc.invert(mask), todo
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _combine(
|
|
191
|
+
combine: Callable[[pa.Array, pa.Array], pa.Array], parts: list[Mask], column: pa.Array
|
|
192
|
+
) -> tuple[pa.Array, pa.Array]:
|
|
193
|
+
mask, todo = parts[0](column)
|
|
194
|
+
for part in parts[1:]:
|
|
195
|
+
more, more_todo = part(column)
|
|
196
|
+
mask, todo = combine(mask, more), pc.or_(todo, more_todo)
|
|
197
|
+
return mask, todo
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def lower_when(text: str) -> Mask | None:
|
|
201
|
+
"""A mask for a ``when`` expression, or None when it does not lower."""
|
|
202
|
+
try:
|
|
203
|
+
tree = parse_expression(text)
|
|
204
|
+
except (SyntaxError, ValueError):
|
|
205
|
+
return None
|
|
206
|
+
return lower_expression(tree.body)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _op_vector(op: CompiledStep, column_type: CType, engine: str) -> tuple[Vector | None, CType]:
|
|
210
|
+
"""The vector op for a step: polars' where it has one and the engine is polars."""
|
|
211
|
+
if isinstance(op.kwargs, CastArgs):
|
|
212
|
+
kind = op.kwargs.target.kind
|
|
213
|
+
fn = polars_vector.CASTS.get(kind) if engine == "polars" else None
|
|
214
|
+
return fn or CASTS.get(kind), op.kwargs.target
|
|
215
|
+
name = op.transform.name
|
|
216
|
+
fn = polars_vector.TRANSFORMS.get(name) if engine == "polars" else None
|
|
217
|
+
return fn or TRANSFORMS.get(name), column_type
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def chain_vector(steps: tuple[Op, ...], column_type: CType, engine: str = "arrow") -> Vector | None:
|
|
221
|
+
"""The ops of a chain as one vector op, or None when any op is not vectorisable."""
|
|
222
|
+
parts: list[tuple[Vector, Any, CType]] = []
|
|
223
|
+
for op in steps:
|
|
224
|
+
if isinstance(op, CaseOp):
|
|
225
|
+
lowered = case_vector(op, column_type, engine)
|
|
226
|
+
if lowered is None:
|
|
227
|
+
return None
|
|
228
|
+
parts.append((lowered, None, column_type))
|
|
229
|
+
continue
|
|
230
|
+
if not isinstance(op, CompiledStep):
|
|
231
|
+
return None
|
|
232
|
+
fn, ctype = _op_vector(op, column_type, engine)
|
|
233
|
+
if fn is None:
|
|
234
|
+
return None
|
|
235
|
+
parts.append((fn, op.kwargs, ctype))
|
|
236
|
+
|
|
237
|
+
def run(column: pa.Array, _k: Any, _t: CType) -> tuple[pa.Array, pa.Array]: # noqa: ANN401
|
|
238
|
+
todo = _false(column)
|
|
239
|
+
values = column
|
|
240
|
+
for fn, kwargs, ctype in parts:
|
|
241
|
+
values, more = fn(values, kwargs, ctype)
|
|
242
|
+
todo = pc.or_(todo, pc.fill_null(more, _NO))
|
|
243
|
+
return values, todo
|
|
244
|
+
|
|
245
|
+
return run
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def case_vector(op: CaseOp, column_type: CType, engine: str = "arrow") -> Vector | None:
|
|
249
|
+
"""A ``case`` (or a column's ``when``) as one vector op, or None when it does not lower."""
|
|
250
|
+
if op.reads:
|
|
251
|
+
return None
|
|
252
|
+
whens: list[tuple[Mask, Vector]] = []
|
|
253
|
+
for when, chain in op.branches:
|
|
254
|
+
mask = lower_when(when.text)
|
|
255
|
+
branch = chain_vector(chain.steps, column_type, engine)
|
|
256
|
+
if mask is None or branch is None:
|
|
257
|
+
return None
|
|
258
|
+
whens.append((mask, branch))
|
|
259
|
+
otherwise: Vector | None = None
|
|
260
|
+
if op.otherwise is not None:
|
|
261
|
+
otherwise = chain_vector(op.otherwise.steps, column_type, engine)
|
|
262
|
+
if otherwise is None:
|
|
263
|
+
return None
|
|
264
|
+
|
|
265
|
+
def run(column: pa.Array, _k: Any, _t: CType) -> tuple[pa.Array, pa.Array]: # noqa: ANN401
|
|
266
|
+
if otherwise is None:
|
|
267
|
+
result, result_todo = column, _false(column)
|
|
268
|
+
else:
|
|
269
|
+
result, result_todo = otherwise(column, None, column_type)
|
|
270
|
+
when_todo = _false(column)
|
|
271
|
+
for mask_fn, branch in reversed(whens):
|
|
272
|
+
mask, more = mask_fn(column)
|
|
273
|
+
values, values_todo = branch(column, None, column_type)
|
|
274
|
+
if values.type != result.type:
|
|
275
|
+
values = pc.cast(values, result.type)
|
|
276
|
+
result = pc.if_else(mask, values, result)
|
|
277
|
+
result_todo = pc.if_else(mask, values_todo, result_todo)
|
|
278
|
+
when_todo = pc.or_(when_todo, more)
|
|
279
|
+
return result, pc.or_(result_todo, when_todo)
|
|
280
|
+
|
|
281
|
+
return run
|
map_conform/plan/ops.py
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
"""The run-time form of a compiled chain (detailed design §3.4, §10.1).
|
|
2
|
+
|
|
3
|
+
A :class:`CompiledChain` is a tuple of ops. Each op has a ``rule`` (how errors name it), says
|
|
4
|
+
whether it must see nulls, whether it can produce a null whatever its input, and which
|
|
5
|
+
columns it reads; ``apply`` runs it on one value.
|
|
6
|
+
|
|
7
|
+
- :class:`CompiledStep`: a builtin or a cast, with its kwargs already validated;
|
|
8
|
+
- :class:`ExprOp`: an ``expr`` step;
|
|
9
|
+
- :class:`GuardedOp`: steps that run only where a ``when`` is truthy;
|
|
10
|
+
- :class:`CaseOp`: the first branch whose ``when`` is truthy, else the ``else`` chain;
|
|
11
|
+
- :class:`FieldsOp`: chains applied to nested members of a struct or json value.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import re
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from typing import TYPE_CHECKING, Any
|
|
19
|
+
|
|
20
|
+
from map_conform.errors import CellError, StepFailed
|
|
21
|
+
from map_conform.expr.compiler import Expression, Row
|
|
22
|
+
from map_conform.naming.shape import Shape
|
|
23
|
+
from map_conform.transforms.registry import Transform
|
|
24
|
+
from map_conform.types.canonical import CType
|
|
25
|
+
|
|
26
|
+
if TYPE_CHECKING:
|
|
27
|
+
from map_conform.transforms.registry import Context
|
|
28
|
+
|
|
29
|
+
_EMPTY_ROW = Row.of({})
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class CastArgs:
|
|
34
|
+
"""A cast step's arguments: its target type and its validated options."""
|
|
35
|
+
|
|
36
|
+
target: CType
|
|
37
|
+
options: Any
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class StepError(Exception):
|
|
41
|
+
"""A step failed on a value; ``cell`` says which and why."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, cell: CellError) -> None:
|
|
44
|
+
"""Keep the failure."""
|
|
45
|
+
self.cell = cell
|
|
46
|
+
super().__init__(f"{cell.rule}: {cell.reason}")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class CompiledStep:
|
|
51
|
+
"""One resolved builtin or cast, with validated kwargs."""
|
|
52
|
+
|
|
53
|
+
transform: Transform
|
|
54
|
+
kwargs: Any
|
|
55
|
+
rule: str
|
|
56
|
+
"""How errors name the step, e.g. ``strip_chars`` or ``cast: decimal(10,2)``."""
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def null_safe(self) -> bool:
|
|
60
|
+
"""Whether the step must see nulls."""
|
|
61
|
+
return self.transform.null_safe
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def forces_nullable(self) -> bool:
|
|
65
|
+
"""Whether the step can produce null whatever its input (set_null)."""
|
|
66
|
+
return self.transform.forces_nullable
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def reads(self) -> frozenset[str]:
|
|
70
|
+
"""Builtins read no other column."""
|
|
71
|
+
return frozenset()
|
|
72
|
+
|
|
73
|
+
def apply(self, value: object, ctx: Context, _row: Row) -> object:
|
|
74
|
+
"""Run the builtin."""
|
|
75
|
+
return self.transform.scalar(value, self.kwargs, ctx)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass(frozen=True)
|
|
79
|
+
class ExprOp:
|
|
80
|
+
"""An ``expr`` step: its result replaces the value."""
|
|
81
|
+
|
|
82
|
+
expression: Expression
|
|
83
|
+
null_safe = True
|
|
84
|
+
forces_nullable = False
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def rule(self) -> str:
|
|
88
|
+
"""``expr: <text>``."""
|
|
89
|
+
return f"expr: {self.expression.text}"
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def reads(self) -> frozenset[str]:
|
|
93
|
+
"""The columns the expression reads."""
|
|
94
|
+
return self.expression.reads
|
|
95
|
+
|
|
96
|
+
def apply(self, value: object, _ctx: Context, row: Row) -> object:
|
|
97
|
+
"""Evaluate the expression with the value as ``value``."""
|
|
98
|
+
return self.expression.evaluate(row, value)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _truthy(when: Expression, row: Row, value: object) -> bool:
|
|
102
|
+
try:
|
|
103
|
+
return bool(when.evaluate(row, value))
|
|
104
|
+
except StepFailed as exc:
|
|
105
|
+
raise StepFailed(f"when {when.text!r}: {exc.reason}") from None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
Op = Any
|
|
109
|
+
"""CompiledStep | ExprOp | GuardedOp | CaseOp | FieldsOp."""
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _run(ops: tuple[Op, ...], value: object, ctx: Context, row: Row) -> object:
|
|
113
|
+
for op in ops:
|
|
114
|
+
if value is None and not op.null_safe:
|
|
115
|
+
continue
|
|
116
|
+
try:
|
|
117
|
+
value = op.apply(value, ctx, row)
|
|
118
|
+
except StepFailed as exc:
|
|
119
|
+
raise StepError(CellError(op.rule, exc.reason)) from exc
|
|
120
|
+
return value
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@dataclass(frozen=True)
|
|
124
|
+
class GuardedOp:
|
|
125
|
+
"""Steps that run only where ``when`` is truthy; elsewhere the value passes unchanged."""
|
|
126
|
+
|
|
127
|
+
when: Expression
|
|
128
|
+
ops: tuple[Op, ...]
|
|
129
|
+
null_safe = True
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def rule(self) -> str:
|
|
133
|
+
"""The guarded steps and their condition."""
|
|
134
|
+
return f"{', '.join(op.rule for op in self.ops)} (when {self.when.text})"
|
|
135
|
+
|
|
136
|
+
@property
|
|
137
|
+
def forces_nullable(self) -> bool:
|
|
138
|
+
"""When a guarded step can produce null."""
|
|
139
|
+
return any(op.forces_nullable for op in self.ops)
|
|
140
|
+
|
|
141
|
+
@property
|
|
142
|
+
def reads(self) -> frozenset[str]:
|
|
143
|
+
"""The condition's columns and the steps'."""
|
|
144
|
+
return self.when.reads.union(*(op.reads for op in self.ops))
|
|
145
|
+
|
|
146
|
+
def apply(self, value: object, ctx: Context, row: Row) -> object:
|
|
147
|
+
"""Run the steps where the condition holds."""
|
|
148
|
+
if not _truthy(self.when, row, value):
|
|
149
|
+
return value
|
|
150
|
+
return _run(self.ops, value, ctx, row)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
@dataclass(frozen=True)
|
|
154
|
+
class CompiledChain:
|
|
155
|
+
"""A column's ops, ending as its declared type."""
|
|
156
|
+
|
|
157
|
+
steps: tuple[Op, ...]
|
|
158
|
+
target: CType
|
|
159
|
+
|
|
160
|
+
@property
|
|
161
|
+
def reads(self) -> frozenset[str]:
|
|
162
|
+
"""Every column the chain's expressions read: its dependencies."""
|
|
163
|
+
return frozenset().union(*(op.reads for op in self.steps))
|
|
164
|
+
|
|
165
|
+
@property
|
|
166
|
+
def forces_nullable(self) -> bool:
|
|
167
|
+
"""Whether a step can produce null whatever the input."""
|
|
168
|
+
return any(op.forces_nullable for op in self.steps)
|
|
169
|
+
|
|
170
|
+
def run(self, value: object, ctx: Context, row: Row | None = None) -> object:
|
|
171
|
+
"""Apply the ops to one value. Nulls skip ops that are not null-safe.
|
|
172
|
+
|
|
173
|
+
Raises:
|
|
174
|
+
StepError: naming the failed step and the reason.
|
|
175
|
+
"""
|
|
176
|
+
return _run(self.steps, value, ctx, row or _EMPTY_ROW)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
@dataclass(frozen=True)
|
|
180
|
+
class CaseOp:
|
|
181
|
+
"""The first branch whose condition holds runs; otherwise the else chain, if any."""
|
|
182
|
+
|
|
183
|
+
branches: tuple[tuple[Expression, CompiledChain], ...]
|
|
184
|
+
otherwise: CompiledChain | None
|
|
185
|
+
label: str = "case"
|
|
186
|
+
null_safe = True
|
|
187
|
+
|
|
188
|
+
@property
|
|
189
|
+
def rule(self) -> str:
|
|
190
|
+
"""``case: when <a> -> [steps]; else -> [steps]``."""
|
|
191
|
+
parts = [
|
|
192
|
+
f"when {when.text} -> [{', '.join(op.rule for op in chain.steps)}]"
|
|
193
|
+
for when, chain in self.branches
|
|
194
|
+
]
|
|
195
|
+
if self.otherwise is not None:
|
|
196
|
+
parts.append(f"else -> [{', '.join(op.rule for op in self.otherwise.steps)}]")
|
|
197
|
+
return f"{self.label}: {'; '.join(parts)}"
|
|
198
|
+
|
|
199
|
+
@property
|
|
200
|
+
def forces_nullable(self) -> bool:
|
|
201
|
+
"""When any branch can produce null."""
|
|
202
|
+
chains = [chain for _, chain in self.branches]
|
|
203
|
+
if self.otherwise is not None:
|
|
204
|
+
chains.append(self.otherwise)
|
|
205
|
+
return any(chain.forces_nullable for chain in chains)
|
|
206
|
+
|
|
207
|
+
@property
|
|
208
|
+
def reads(self) -> frozenset[str]:
|
|
209
|
+
"""The conditions' columns and the branches'."""
|
|
210
|
+
out: set[str] = set()
|
|
211
|
+
for when, chain in self.branches:
|
|
212
|
+
out |= when.reads | chain.reads
|
|
213
|
+
if self.otherwise is not None:
|
|
214
|
+
out |= self.otherwise.reads
|
|
215
|
+
return frozenset(out)
|
|
216
|
+
|
|
217
|
+
def apply(self, value: object, ctx: Context, row: Row) -> object:
|
|
218
|
+
"""Run the first matching branch."""
|
|
219
|
+
for when, chain in self.branches:
|
|
220
|
+
if _truthy(when, row, value):
|
|
221
|
+
return chain.run(value, ctx, row)
|
|
222
|
+
if self.otherwise is None:
|
|
223
|
+
return value
|
|
224
|
+
return self.otherwise.run(value, ctx, row)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
@dataclass(frozen=True)
|
|
228
|
+
class ShapeOp:
|
|
229
|
+
"""A declared shape applied to the source value: undeclared members dropped, defaults set."""
|
|
230
|
+
|
|
231
|
+
shape: Shape
|
|
232
|
+
column: str
|
|
233
|
+
null_safe = True
|
|
234
|
+
forces_nullable = False
|
|
235
|
+
reads: frozenset[str] = frozenset()
|
|
236
|
+
|
|
237
|
+
@property
|
|
238
|
+
def rule(self) -> str:
|
|
239
|
+
"""``shape``."""
|
|
240
|
+
return "shape"
|
|
241
|
+
|
|
242
|
+
def apply(self, value: object, _ctx: Context, row: Row) -> object:
|
|
243
|
+
"""Conform the value to the shape, reporting dropped members on the row."""
|
|
244
|
+
return self.shape.conform(value, "", lambda p: row.dropped.append((self.column, p)))
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
# --- nested fields --------------------------------------------------------------------------
|
|
248
|
+
|
|
249
|
+
_SEGMENT = re.compile(r"\[\*\]|[^.\[\]]+")
|
|
250
|
+
DROP = object()
|
|
251
|
+
"""Returned by a field op to remove the member."""
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def path_segments(path: str) -> tuple[str, ...] | None:
|
|
255
|
+
"""``address.zip`` -> (address, zip); ``items[*].sku`` -> (items, [*], sku); None if bad."""
|
|
256
|
+
segments = tuple(_SEGMENT.findall(path))
|
|
257
|
+
rebuilt = "".join(s if s == "[*]" else f".{s}" for s in segments).lstrip(".")
|
|
258
|
+
return segments if segments and rebuilt == path else None
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
@dataclass(frozen=True)
|
|
262
|
+
class FieldOp:
|
|
263
|
+
"""A chain, a condition, or a drop, for the members at one path."""
|
|
264
|
+
|
|
265
|
+
path: str
|
|
266
|
+
segments: tuple[str, ...]
|
|
267
|
+
chain: CompiledChain | None
|
|
268
|
+
when: Expression | None
|
|
269
|
+
drop: bool
|
|
270
|
+
|
|
271
|
+
@property
|
|
272
|
+
def reads(self) -> frozenset[str]:
|
|
273
|
+
"""The condition's and the chain's columns."""
|
|
274
|
+
out = self.when.reads if self.when is not None else frozenset()
|
|
275
|
+
return out | (self.chain.reads if self.chain is not None else frozenset())
|
|
276
|
+
|
|
277
|
+
def member(self, value: object, ctx: Context, row: Row) -> object:
|
|
278
|
+
"""The new member value, or DROP."""
|
|
279
|
+
if self.when is not None and not _truthy(self.when, row, value):
|
|
280
|
+
return value
|
|
281
|
+
if self.drop:
|
|
282
|
+
return DROP
|
|
283
|
+
if self.chain is None:
|
|
284
|
+
return value
|
|
285
|
+
try:
|
|
286
|
+
return self.chain.run(value, ctx, row)
|
|
287
|
+
except StepError as exc:
|
|
288
|
+
raise StepFailed(f"{self.path}: {exc.cell.rule}: {exc.cell.reason}") from None
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _update(container: object, segments: tuple[str, ...], fn: FieldOp, *args: Any) -> object:
|
|
292
|
+
"""A copy of the container with fn applied at the path; missing members are left alone."""
|
|
293
|
+
head, rest = segments[0], segments[1:]
|
|
294
|
+
if head == "[*]":
|
|
295
|
+
if not isinstance(container, list):
|
|
296
|
+
return container
|
|
297
|
+
items = [_update_item(item, rest, fn, *args) for item in container]
|
|
298
|
+
return [item for item in items if item is not DROP]
|
|
299
|
+
if not isinstance(container, dict) or head not in container:
|
|
300
|
+
return container
|
|
301
|
+
copy = dict(container)
|
|
302
|
+
new = _update_item(copy[head], rest, fn, *args)
|
|
303
|
+
if new is DROP:
|
|
304
|
+
del copy[head]
|
|
305
|
+
else:
|
|
306
|
+
copy[head] = new
|
|
307
|
+
return copy
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _update_item(item: object, rest: tuple[str, ...], fn: FieldOp, *args: Any) -> object:
|
|
311
|
+
return fn.member(item, *args) if not rest else _update(item, rest, fn, *args)
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
@dataclass(frozen=True)
|
|
315
|
+
class FieldsOp:
|
|
316
|
+
"""Transforms on nested members, after the cast (pipelinewise ``field_paths``)."""
|
|
317
|
+
|
|
318
|
+
fields: tuple[FieldOp, ...]
|
|
319
|
+
null_safe = False
|
|
320
|
+
forces_nullable = False
|
|
321
|
+
|
|
322
|
+
@property
|
|
323
|
+
def rule(self) -> str:
|
|
324
|
+
"""``fields: a.b, c[*].d``."""
|
|
325
|
+
return f"fields: {', '.join(f.path for f in self.fields)}"
|
|
326
|
+
|
|
327
|
+
@property
|
|
328
|
+
def reads(self) -> frozenset[str]:
|
|
329
|
+
"""Every field's columns."""
|
|
330
|
+
return frozenset().union(*(f.reads for f in self.fields))
|
|
331
|
+
|
|
332
|
+
def apply(self, value: object, ctx: Context, row: Row) -> object:
|
|
333
|
+
"""Apply each field op in turn; containers on the path are copied, never changed."""
|
|
334
|
+
for op in self.fields:
|
|
335
|
+
value = _update(value, op.segments, op, ctx, row)
|
|
336
|
+
return value
|