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,318 @@
|
|
|
1
|
+
"""Numeric casts and builtins (detailed design §6.2).
|
|
2
|
+
|
|
3
|
+
One grammar serves int16/32/64, float32/64 and decimal(p,s) targets. After the value cleanup
|
|
4
|
+
(trim, null tokens) a string may have, in this order of removal:
|
|
5
|
+
|
|
6
|
+
- parentheses meaning negative (``parens_negative``);
|
|
7
|
+
- a trailing ``%`` (``percent: divide`` or ``strip``; otherwise an error);
|
|
8
|
+
- a trailing minus (``trailing_minus``);
|
|
9
|
+
- one currency symbol or ISO-4217 code, before or after, with an optional sign before it;
|
|
10
|
+
- a sign, then digits with thousands separators in valid groups of three, a decimal point,
|
|
11
|
+
and an exponent.
|
|
12
|
+
|
|
13
|
+
Separators come from ``locale`` (us ``1,234.5``, eu ``1.234,5``, ch ``1'234.5``) unless
|
|
14
|
+
``thousands`` / ``decimal_point`` are given. Arithmetic is exact (``Decimal``), so ``1.005``
|
|
15
|
+
rounds to ``1.01``. ``rounding`` defaults to ``half_up`` (away from zero) for decimals and to
|
|
16
|
+
``error`` for integers, so a fraction never silently becomes an integer; ``12.0`` is fine.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import math
|
|
22
|
+
import re
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from decimal import ROUND_DOWN, ROUND_HALF_EVEN, ROUND_HALF_UP, Decimal, Inexact, InvalidOperation
|
|
25
|
+
from decimal import Context as DecimalContext
|
|
26
|
+
from typing import TYPE_CHECKING, Any, Literal
|
|
27
|
+
|
|
28
|
+
from map_conform.errors import StepFailed
|
|
29
|
+
from map_conform.transforms.casts import Cleanup, clean, cleanup_defaults
|
|
30
|
+
from map_conform.transforms.registry import NUMERIC, RAW, Registry, Transform
|
|
31
|
+
|
|
32
|
+
if TYPE_CHECKING:
|
|
33
|
+
from map_conform.plan.ops import CastArgs
|
|
34
|
+
from map_conform.spec.model import ColumnSpec, Defaults
|
|
35
|
+
from map_conform.transforms.registry import Context
|
|
36
|
+
|
|
37
|
+
Rounding = Literal["half_up", "half_even", "down", "error"]
|
|
38
|
+
|
|
39
|
+
INT_BOUNDS = {
|
|
40
|
+
"int16": (-(2**15), 2**15 - 1),
|
|
41
|
+
"int32": (-(2**31), 2**31 - 1),
|
|
42
|
+
"int64": (-(2**63), 2**63 - 1),
|
|
43
|
+
}
|
|
44
|
+
LOCALES = {"us": (",", "."), "eu": (".", ","), "ch": ("'", ".")}
|
|
45
|
+
CURRENCY_SYMBOLS = "$€£¥₹₩₽₺₪₫฿¢₱₦₴₸₡"
|
|
46
|
+
_CURRENCY = rf"(?:[{re.escape(CURRENCY_SYMBOLS)}]|[A-Z]{{3}})"
|
|
47
|
+
_LEADING_CURRENCY = re.compile(rf"^([+-]?)\s*{_CURRENCY}\s*")
|
|
48
|
+
_TRAILING_CURRENCY = re.compile(rf"\s*{_CURRENCY}$")
|
|
49
|
+
_ANY_CURRENCY = re.compile(_CURRENCY)
|
|
50
|
+
_EXPONENT = r"(?:[eE][+-]?\d+)?"
|
|
51
|
+
_MODES = {"half_up": ROUND_HALF_UP, "half_even": ROUND_HALF_EVEN, "down": ROUND_DOWN}
|
|
52
|
+
_EXACT = DecimalContext(prec=200, traps=[InvalidOperation])
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class NumberCast(Cleanup):
|
|
57
|
+
"""Options for casts to integers, floats and decimals."""
|
|
58
|
+
|
|
59
|
+
locale: Literal["us", "eu", "ch"] = "us"
|
|
60
|
+
thousands: str | None = None
|
|
61
|
+
decimal_point: str | None = None
|
|
62
|
+
parens_negative: bool = False
|
|
63
|
+
trailing_minus: bool = False
|
|
64
|
+
percent: Literal["error", "divide", "strip"] = "error"
|
|
65
|
+
rounding: Rounding | None = None
|
|
66
|
+
nan: Literal["null", "error"] = "null"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def parse_number(text: str, options: NumberCast) -> Decimal: # noqa: C901, PLR0912
|
|
70
|
+
"""Parse a numeric string exactly.
|
|
71
|
+
|
|
72
|
+
Raises:
|
|
73
|
+
StepFailed: when the text does not follow the grammar.
|
|
74
|
+
"""
|
|
75
|
+
thousands, point = LOCALES[options.locale]
|
|
76
|
+
thousands = options.thousands if options.thousands is not None else thousands
|
|
77
|
+
point = options.decimal_point if options.decimal_point is not None else point
|
|
78
|
+
s = text.strip()
|
|
79
|
+
negative = False
|
|
80
|
+
if s.startswith("(") and s.endswith(")"):
|
|
81
|
+
if not options.parens_negative:
|
|
82
|
+
raise StepFailed("parentheses need parens_negative: true")
|
|
83
|
+
negative, s = True, s[1:-1].strip()
|
|
84
|
+
percent = s.endswith("%")
|
|
85
|
+
if percent:
|
|
86
|
+
if options.percent == "error":
|
|
87
|
+
raise StepFailed("'%' needs percent: divide (or strip)")
|
|
88
|
+
s = s[:-1].strip()
|
|
89
|
+
if s.endswith("-") and not s.startswith("-"):
|
|
90
|
+
if not options.trailing_minus:
|
|
91
|
+
raise StepFailed("a trailing minus needs trailing_minus: true")
|
|
92
|
+
negative, s = not negative, s[:-1].strip()
|
|
93
|
+
sign = ""
|
|
94
|
+
if match := _LEADING_CURRENCY.match(s):
|
|
95
|
+
sign, s = match.group(1), s[match.end() :]
|
|
96
|
+
elif match := _TRAILING_CURRENCY.search(s):
|
|
97
|
+
s = s[: match.start()]
|
|
98
|
+
if _ANY_CURRENCY.search(s):
|
|
99
|
+
raise StepFailed("at most one currency marker")
|
|
100
|
+
s = sign + s.strip()
|
|
101
|
+
if s and s[0] in "+-": # note: "" in "+-" is True, so test s first
|
|
102
|
+
negative, s = negative ^ (s[0] == "-"), s[1:]
|
|
103
|
+
body = _normalise_body(s, thousands, point)
|
|
104
|
+
try:
|
|
105
|
+
number = _EXACT.create_decimal(body)
|
|
106
|
+
except InvalidOperation as exc:
|
|
107
|
+
raise StepFailed("not a number") from exc
|
|
108
|
+
if negative:
|
|
109
|
+
number = -number
|
|
110
|
+
if percent and options.percent == "divide":
|
|
111
|
+
number = _EXACT.divide(number, Decimal(100))
|
|
112
|
+
return number
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _normalise_body(s: str, thousands: str, point: str) -> str:
|
|
116
|
+
"""Remove valid thousands separators and make the decimal point a '.'."""
|
|
117
|
+
t, p = re.escape(thousands), re.escape(point)
|
|
118
|
+
grouped = rf"\d{{1,3}}(?:{t}\d{{3}})+"
|
|
119
|
+
plain = r"\d+"
|
|
120
|
+
pattern = rf"^(?:{grouped}|{plain})?(?:{p}\d*)?{_EXPONENT}$"
|
|
121
|
+
if not re.search(r"\d", s) or not re.match(pattern, s):
|
|
122
|
+
if thousands and thousands in s:
|
|
123
|
+
raise StepFailed(f"thousands separators {thousands!r} must form groups of three")
|
|
124
|
+
raise StepFailed("not a number")
|
|
125
|
+
return s.replace(thousands, "").replace(point, ".")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _from_value(value: object, options: NumberCast) -> Decimal | None:
|
|
129
|
+
"""Any raw value as an exact Decimal; None for null or a NaN treated as null."""
|
|
130
|
+
cleaned = clean(value, options)
|
|
131
|
+
if isinstance(cleaned, bool):
|
|
132
|
+
raise StepFailed("a boolean is not a number")
|
|
133
|
+
if isinstance(cleaned, (float, Decimal)) and not _is_finite(cleaned):
|
|
134
|
+
if options.nan == "null":
|
|
135
|
+
return None
|
|
136
|
+
raise StepFailed(f"{cleaned} is not a finite number")
|
|
137
|
+
if cleaned is None or isinstance(cleaned, Decimal):
|
|
138
|
+
return cleaned
|
|
139
|
+
if isinstance(cleaned, float):
|
|
140
|
+
return Decimal(repr(cleaned)) # the shortest repr: 0.1 stays 0.1
|
|
141
|
+
if isinstance(cleaned, int):
|
|
142
|
+
return Decimal(cleaned)
|
|
143
|
+
if isinstance(cleaned, str):
|
|
144
|
+
return parse_number(cleaned, options)
|
|
145
|
+
raise StepFailed(f"{type(cleaned).__name__} is not a number")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _is_finite(number: float | Decimal) -> bool:
|
|
149
|
+
return number.is_finite() if isinstance(number, Decimal) else math.isfinite(number)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
_MAX_DIGITS = 150
|
|
153
|
+
"""Larger numbers fit no column; quantizing them would overflow the decimal context."""
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _round(number: Decimal, exponent: Decimal, mode: Rounding) -> Decimal:
|
|
157
|
+
if number.adjusted() >= _MAX_DIGITS:
|
|
158
|
+
raise StepFailed(f"{number} is too large for any numeric column")
|
|
159
|
+
if mode == "error":
|
|
160
|
+
try:
|
|
161
|
+
return number.quantize(exponent, context=DecimalContext(prec=200, traps=[Inexact]))
|
|
162
|
+
except Inexact as exc:
|
|
163
|
+
raise StepFailed(f"{number} has more fraction digits than the column allows") from exc
|
|
164
|
+
return number.quantize(exponent, rounding=_MODES[mode], context=_EXACT)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def cast_int(value: object, args: CastArgs, _ctx: Context) -> object:
|
|
168
|
+
"""Cast to int16/32/64; a fraction is an error unless a rounding mode is set."""
|
|
169
|
+
options: NumberCast = args.options
|
|
170
|
+
number = _from_value(value, options)
|
|
171
|
+
if number is None:
|
|
172
|
+
return None
|
|
173
|
+
integral = _round(number, Decimal(1), options.rounding or "error")
|
|
174
|
+
result = int(integral)
|
|
175
|
+
low, high = INT_BOUNDS[args.target.kind]
|
|
176
|
+
if not low <= result <= high:
|
|
177
|
+
raise StepFailed(f"{result} is outside {args.target.kind}")
|
|
178
|
+
return result
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def cast_float(value: object, args: CastArgs, _ctx: Context) -> object:
|
|
182
|
+
"""Cast to float32/64; the result is finite or null."""
|
|
183
|
+
options: NumberCast = args.options
|
|
184
|
+
number = _from_value(value, options)
|
|
185
|
+
if number is None:
|
|
186
|
+
return None
|
|
187
|
+
result = float(number)
|
|
188
|
+
if not math.isfinite(result):
|
|
189
|
+
raise StepFailed(f"{number} does not fit a {args.target.kind}")
|
|
190
|
+
return result
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def cast_decimal(value: object, args: CastArgs, _ctx: Context) -> object:
|
|
194
|
+
"""Cast to decimal(p,s): exactly s fraction digits, at most p digits."""
|
|
195
|
+
options: NumberCast = args.options
|
|
196
|
+
number = _from_value(value, options)
|
|
197
|
+
if number is None:
|
|
198
|
+
return None
|
|
199
|
+
precision, scale = args.target.decimal_params
|
|
200
|
+
result = _round(number, Decimal(1).scaleb(-scale), options.rounding or "half_up")
|
|
201
|
+
digits = len(result.as_tuple().digits)
|
|
202
|
+
if digits > precision and result != 0:
|
|
203
|
+
raise StepFailed(f"{digits} digits > precision {precision}")
|
|
204
|
+
return result
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _number_defaults(settings: Defaults, column: ColumnSpec | None) -> dict[str, Any]:
|
|
208
|
+
return cleanup_defaults(settings, column)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
# --- builtins after the cast -------------------------------------------------------------------
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
@dataclass(frozen=True)
|
|
215
|
+
class RoundKwargs:
|
|
216
|
+
"""Round to ``ndigits`` fraction digits (half_up)."""
|
|
217
|
+
|
|
218
|
+
ndigits: int = 0
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
@dataclass(frozen=True)
|
|
222
|
+
class ClampKwargs:
|
|
223
|
+
"""Keep a number within bounds."""
|
|
224
|
+
|
|
225
|
+
min: float | None = None
|
|
226
|
+
max: float | None = None
|
|
227
|
+
on_out_of_range: Literal["clamp", "null", "error"] = "clamp"
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
@dataclass(frozen=True)
|
|
231
|
+
class ScaleKwargs:
|
|
232
|
+
"""Multiply, e.g. 0.01 for cents to units."""
|
|
233
|
+
|
|
234
|
+
factor: float = 1.0
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _round_step(value: object, k: RoundKwargs, _ctx: Context) -> object:
|
|
238
|
+
if isinstance(value, Decimal):
|
|
239
|
+
return value.quantize(Decimal(1).scaleb(-k.ndigits), rounding=ROUND_HALF_UP)
|
|
240
|
+
if isinstance(value, float):
|
|
241
|
+
exact = Decimal(repr(value)).quantize(Decimal(1).scaleb(-k.ndigits), rounding=ROUND_HALF_UP)
|
|
242
|
+
return float(exact)
|
|
243
|
+
return value
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _exact(value: object) -> Decimal:
|
|
247
|
+
if isinstance(value, float):
|
|
248
|
+
return Decimal(repr(value))
|
|
249
|
+
if isinstance(value, (int, Decimal)):
|
|
250
|
+
return Decimal(value)
|
|
251
|
+
raise StepFailed(f"{type(value).__name__} is not a number")
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _clamp(value: object, k: ClampKwargs, _ctx: Context) -> object:
|
|
255
|
+
number = _exact(value)
|
|
256
|
+
bound: Decimal | None = None
|
|
257
|
+
if k.min is not None and number < _exact(k.min):
|
|
258
|
+
bound = _exact(k.min)
|
|
259
|
+
elif k.max is not None and number > _exact(k.max):
|
|
260
|
+
bound = _exact(k.max)
|
|
261
|
+
if bound is None:
|
|
262
|
+
return value
|
|
263
|
+
if k.on_out_of_range == "null":
|
|
264
|
+
return None
|
|
265
|
+
if k.on_out_of_range == "error":
|
|
266
|
+
raise StepFailed(f"{value} is outside [{k.min}, {k.max}]")
|
|
267
|
+
if isinstance(value, Decimal):
|
|
268
|
+
return bound
|
|
269
|
+
return float(bound) if isinstance(value, float) else int(bound)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _scale(value: object, k: ScaleKwargs, ctx: Context) -> object:
|
|
273
|
+
factor = Decimal(repr(k.factor))
|
|
274
|
+
if isinstance(value, Decimal):
|
|
275
|
+
_, scale = ctx.target.decimal_params if ctx.target.kind == "decimal" else (0, 0)
|
|
276
|
+
return (value * factor).quantize(Decimal(1).scaleb(-scale), rounding=ROUND_HALF_UP)
|
|
277
|
+
if isinstance(value, int) and not isinstance(value, bool):
|
|
278
|
+
result = Decimal(value) * factor
|
|
279
|
+
if result != result.to_integral_value():
|
|
280
|
+
raise StepFailed(f"{value} x {k.factor} is not a whole number")
|
|
281
|
+
return int(result)
|
|
282
|
+
if isinstance(value, float):
|
|
283
|
+
return float(Decimal(repr(value)) * factor)
|
|
284
|
+
return value
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def register(registry: Registry) -> None:
|
|
288
|
+
"""Add the numeric casts and builtins."""
|
|
289
|
+
accepts = frozenset({RAW, "string", *NUMERIC})
|
|
290
|
+
registry.register_cast(
|
|
291
|
+
{"int16", "int32", "int64"},
|
|
292
|
+
Transform("cast", cast_int, kwargs=NumberCast, defaults=_number_defaults, accepts=accepts),
|
|
293
|
+
)
|
|
294
|
+
registry.register_cast(
|
|
295
|
+
{"float32", "float64"},
|
|
296
|
+
Transform(
|
|
297
|
+
"cast", cast_float, kwargs=NumberCast, defaults=_number_defaults, accepts=accepts
|
|
298
|
+
),
|
|
299
|
+
)
|
|
300
|
+
registry.register_cast(
|
|
301
|
+
{"decimal"},
|
|
302
|
+
Transform(
|
|
303
|
+
"cast", cast_decimal, kwargs=NumberCast, defaults=_number_defaults, accepts=accepts
|
|
304
|
+
),
|
|
305
|
+
)
|
|
306
|
+
registry.register(
|
|
307
|
+
Transform(
|
|
308
|
+
"round",
|
|
309
|
+
_round_step,
|
|
310
|
+
kwargs=RoundKwargs,
|
|
311
|
+
positional="ndigits",
|
|
312
|
+
accepts=frozenset({"float32", "float64", "decimal"}),
|
|
313
|
+
)
|
|
314
|
+
)
|
|
315
|
+
registry.register(Transform("clamp", _clamp, kwargs=ClampKwargs, accepts=NUMERIC))
|
|
316
|
+
registry.register(
|
|
317
|
+
Transform("scale", _scale, kwargs=ScaleKwargs, positional="factor", accepts=NUMERIC)
|
|
318
|
+
)
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
r"""polars implementations for ``engine: polars`` (detailed design §10.2, WBS 8.7).
|
|
2
|
+
|
|
3
|
+
With the ``polars`` extra, a column (``engine: polars``) or a stream (``defaults.engine``)
|
|
4
|
+
uses these vector ops where they exist, and the Arrow ones elsewhere. They cover what Arrow
|
|
5
|
+
does not vectorise: regular expressions and strptime-style date formats. They follow the
|
|
6
|
+
same rule as every vector op: claim only rows where the result is the scalar one.
|
|
7
|
+
|
|
8
|
+
- ``regex_replace`` and ``regex_extract`` claim printable-ASCII rows without line breaks,
|
|
9
|
+
for patterns that compile in polars and cannot match the empty string (Python and Rust
|
|
10
|
+
differ on empty matches), with the ``i`` flag at most. Python replacement references
|
|
11
|
+
(``\\1``, ``\\g<1>``, ``\\g<name>``) are translated.
|
|
12
|
+
- Temporal casts whose first format is a strptime pattern of ``%Y %m %d %H %M %S`` and
|
|
13
|
+
literals claim rows that parse and print back to the same text, so padding and other
|
|
14
|
+
leniencies stay with Python's ``strptime``. The zone must be UTC.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import importlib.util
|
|
20
|
+
import re
|
|
21
|
+
from typing import TYPE_CHECKING, Any
|
|
22
|
+
|
|
23
|
+
import pyarrow as pa
|
|
24
|
+
|
|
25
|
+
from map_conform.transforms import vector
|
|
26
|
+
from map_conform.types.to_arrow import to_arrow
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
from map_conform.types.canonical import CType
|
|
30
|
+
|
|
31
|
+
# The pyarrow stubs cannot follow array-in, array-out kernels; tests/parity checks this module.
|
|
32
|
+
_pa: Any = pa
|
|
33
|
+
pc: Any = vector.pc
|
|
34
|
+
|
|
35
|
+
_SIMPLE_FORMAT = re.compile(r"^(?:%[YmdHMS]|[^%])+$")
|
|
36
|
+
_BREAKS = r"[\r\n]"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def available() -> bool:
|
|
40
|
+
"""Whether polars is installed."""
|
|
41
|
+
return importlib.util.find_spec("polars") is not None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _pl() -> Any: # noqa: ANN401 -- the polars module
|
|
45
|
+
import polars as pl # noqa: PLC0415 -- optional dependency
|
|
46
|
+
|
|
47
|
+
return pl
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _claimable_text(column: pa.Array) -> pa.Array:
|
|
51
|
+
"""Todo rows: not printable ASCII, or containing a line break."""
|
|
52
|
+
breaks = pc.fill_null(pc.match_substring_regex(column, _BREAKS), vector.FALSE)
|
|
53
|
+
return pc.or_(vector.unsafe_text(column), breaks)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _pattern(pattern: str, flags: str) -> str | None:
|
|
57
|
+
"""The polars pattern, or None when it cannot be claimed."""
|
|
58
|
+
if set(flags) - {"i"}:
|
|
59
|
+
return None
|
|
60
|
+
try:
|
|
61
|
+
if re.compile(pattern).search("") is not None:
|
|
62
|
+
return None # can match empty: Python and Rust place empty matches differently
|
|
63
|
+
except re.error:
|
|
64
|
+
return None
|
|
65
|
+
full = f"(?i){pattern}" if "i" in flags else pattern
|
|
66
|
+
try:
|
|
67
|
+
_pl().Series([""]).str.contains(full)
|
|
68
|
+
except Exception: # noqa: BLE001 -- polars rejects the pattern
|
|
69
|
+
return None
|
|
70
|
+
return full
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _replacement(repl: str) -> str | None:
|
|
74
|
+
"""A Python ``re.sub`` replacement in polars syntax, or None when it has other escapes."""
|
|
75
|
+
out: list[str] = []
|
|
76
|
+
i = 0
|
|
77
|
+
while i < len(repl):
|
|
78
|
+
char = repl[i]
|
|
79
|
+
if char == "$":
|
|
80
|
+
out.append("$$")
|
|
81
|
+
elif char == "\\":
|
|
82
|
+
group = re.match(r"\\(?:(\d{1,2})|g<(\w+)>)", repl[i:])
|
|
83
|
+
if group is None:
|
|
84
|
+
return None
|
|
85
|
+
out.append("${" + (group.group(1) or group.group(2)) + "}")
|
|
86
|
+
i += len(group.group(0))
|
|
87
|
+
continue
|
|
88
|
+
else:
|
|
89
|
+
out.append(char)
|
|
90
|
+
i += 1
|
|
91
|
+
return "".join(out)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def regex_replace(column: pa.Array, k: Any, _t: CType) -> tuple[pa.Array, pa.Array]: # noqa: ANN401
|
|
95
|
+
"""``regex_replace`` with polars."""
|
|
96
|
+
pattern = _pattern(k.pattern, k.flags)
|
|
97
|
+
repl = _replacement(k.repl)
|
|
98
|
+
if pattern is None or repl is None or not vector.is_text(column):
|
|
99
|
+
return _pa.nulls(len(column), pa.string()), vector.everything(column)
|
|
100
|
+
series = _pl().from_arrow(column)
|
|
101
|
+
result = series.str.replace_all(pattern, repl).to_arrow()
|
|
102
|
+
return pc.cast(result, pa.string()), _claimable_text(column)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def regex_extract(column: pa.Array, k: Any, _t: CType) -> tuple[pa.Array, pa.Array]: # noqa: ANN401
|
|
106
|
+
"""``regex_extract`` with polars (numbered groups)."""
|
|
107
|
+
pattern = _pattern(k.pattern, k.flags)
|
|
108
|
+
if pattern is None or not isinstance(k.group, int) or not vector.is_text(column):
|
|
109
|
+
return _pa.nulls(len(column), pa.string()), vector.everything(column)
|
|
110
|
+
groups = re.compile(k.pattern).groups
|
|
111
|
+
if k.group > groups:
|
|
112
|
+
return _pa.nulls(len(column), pa.string()), vector.everything(column)
|
|
113
|
+
series = _pl().from_arrow(column)
|
|
114
|
+
result = series.str.extract(pattern, k.group).to_arrow()
|
|
115
|
+
return pc.cast(result, pa.string()), _claimable_text(column)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def cast_temporal(column: pa.Array, args: Any, target: CType) -> tuple[pa.Array, pa.Array]: # noqa: ANN401
|
|
119
|
+
"""Temporal casts whose first format is a simple strptime pattern."""
|
|
120
|
+
options = args.options
|
|
121
|
+
fmt = options.formats[0] if options.formats else "iso"
|
|
122
|
+
arrow_type = to_arrow(target)
|
|
123
|
+
if fmt == "iso" or not _SIMPLE_FORMAT.match(fmt) or options.tz != "UTC":
|
|
124
|
+
return vector.cast_temporal(column, args, target)
|
|
125
|
+
if target.kind == "time" or not vector.is_text(column):
|
|
126
|
+
return _pa.nulls(len(column), arrow_type), vector.everything(column)
|
|
127
|
+
text, todo = vector.clean(column, options)
|
|
128
|
+
series = _pl().from_arrow(text)
|
|
129
|
+
parsed = series.str.to_datetime(fmt, strict=False, time_unit="us")
|
|
130
|
+
printed = parsed.dt.strftime(fmt).to_arrow()
|
|
131
|
+
exact = pc.fill_null(pc.equal(pc.cast(printed, pa.string()), text), vector.FALSE)
|
|
132
|
+
todo = pc.or_(todo, pc.and_(pc.is_valid(text), pc.invert(exact)))
|
|
133
|
+
naive = pc.cast(parsed.to_arrow(), pa.timestamp("us"))
|
|
134
|
+
todo = pc.or_(todo, vector.year_bounds(naive, options))
|
|
135
|
+
if target.kind == "timestamptz":
|
|
136
|
+
result = pc.assume_timezone(naive, timezone="UTC")
|
|
137
|
+
elif target.kind == "timestamp":
|
|
138
|
+
result = naive
|
|
139
|
+
else:
|
|
140
|
+
result = pc.cast(naive, pa.date32())
|
|
141
|
+
return pc.cast(result, arrow_type), todo
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
TRANSFORMS: dict[str, vector.Vector] = {
|
|
145
|
+
"regex_replace": regex_replace,
|
|
146
|
+
"regex_extract": regex_extract,
|
|
147
|
+
}
|
|
148
|
+
"""Builtins polars vectorises, by name."""
|
|
149
|
+
|
|
150
|
+
CASTS: dict[str, vector.Vector] = dict.fromkeys(("timestamptz", "timestamp", "date"), cast_temporal)
|
|
151
|
+
"""Casts polars vectorises (over the Arrow ones), by target kind."""
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"""Privacy builtins (detailed design §6.4, WBS 5.6 and 12.5).
|
|
2
|
+
|
|
3
|
+
These follow pipelinewise-transform-field's semantics, minus its bugs:
|
|
4
|
+
|
|
5
|
+
- ``HASH`` is ``hash``; ``HASH-SKIP-FIRST-n`` is ``{hash: {skip_first: n}}`` for any n,
|
|
6
|
+
where pipelinewise reads a single digit;
|
|
7
|
+
- ``MASK-DATE`` is ``{redact_date: {to: year}}`` and keeps the column's type. Unlike
|
|
8
|
+
pipelinewise it also clears the time of day, which can identify a person as well;
|
|
9
|
+
- ``MASK-NUMBER`` is ``mask_number``, giving 0 *in the column's type* (pipelinewise writes
|
|
10
|
+
the int 0 whatever the column);
|
|
11
|
+
- ``MASK-HIDDEN`` is ``mask_hidden``, allowed only where the column is a string
|
|
12
|
+
(pipelinewise writes ``"hidden"`` into numeric columns too, which targets reject);
|
|
13
|
+
- ``MASK-STRING-SKIP-ENDS-n`` is ``{mask: {keep_first: n, keep_last: n}}``, and a value too
|
|
14
|
+
short to show both ends is masked entirely rather than shown;
|
|
15
|
+
- ``SET-NULL`` is ``set_null``, which also makes the column nullable in the SCHEMA
|
|
16
|
+
(pipelinewise leaves the SCHEMA saying the column is never null).
|
|
17
|
+
|
|
18
|
+
``tokenize`` gives a keyed HMAC-SHA256: the same input gives the same token in every run, and
|
|
19
|
+
without the key the token cannot be recomputed from a guessed input, unlike a plain hash.
|
|
20
|
+
|
|
21
|
+
A typed value is hashed in a canonical text form (ISO dates, plain decimals), so the hash
|
|
22
|
+
does not depend on Python's repr.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import base64
|
|
28
|
+
import datetime as dt
|
|
29
|
+
import hashlib
|
|
30
|
+
import hmac
|
|
31
|
+
from dataclasses import dataclass
|
|
32
|
+
from decimal import Decimal
|
|
33
|
+
from typing import TYPE_CHECKING, Literal
|
|
34
|
+
|
|
35
|
+
from map_conform.errors import StepFailed
|
|
36
|
+
from map_conform.transforms.numeric import INT_BOUNDS
|
|
37
|
+
from map_conform.transforms.registry import ANY, NUMERIC, RAW, NoKwargs, Registry, Transform
|
|
38
|
+
from map_conform.types.canonical import CType
|
|
39
|
+
|
|
40
|
+
if TYPE_CHECKING:
|
|
41
|
+
from map_conform.transforms.registry import Context
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class HashKwargs:
|
|
46
|
+
"""A hex digest of the value, optionally keeping the first characters readable."""
|
|
47
|
+
|
|
48
|
+
algo: Literal["sha256", "md5", "sha1", "sha512"] = "sha256"
|
|
49
|
+
salt: str = ""
|
|
50
|
+
skip_first: int = 0
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True)
|
|
54
|
+
class MaskKwargs:
|
|
55
|
+
"""Mask the middle of a string."""
|
|
56
|
+
|
|
57
|
+
keep_first: int = 0
|
|
58
|
+
keep_last: int = 0
|
|
59
|
+
char: str = "*"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True)
|
|
63
|
+
class RedactDateKwargs:
|
|
64
|
+
"""Keep only the year (or year and month) of a date or timestamp."""
|
|
65
|
+
|
|
66
|
+
to: Literal["year", "month"] = "year"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _canonical_text(value: object) -> str:
|
|
70
|
+
"""A stable text form of a value, raw or typed, for hashing."""
|
|
71
|
+
if isinstance(value, str):
|
|
72
|
+
return value
|
|
73
|
+
if isinstance(value, bool):
|
|
74
|
+
return "true" if value else "false"
|
|
75
|
+
if isinstance(value, Decimal):
|
|
76
|
+
return format(value, "f")
|
|
77
|
+
if isinstance(value, (dt.datetime, dt.date, dt.time)):
|
|
78
|
+
return value.isoformat()
|
|
79
|
+
if isinstance(value, bytes):
|
|
80
|
+
return base64.b64encode(value).decode("ascii")
|
|
81
|
+
return str(value)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _hash(value: object, k: HashKwargs, _ctx: Context) -> object:
|
|
85
|
+
if k.skip_first < 0:
|
|
86
|
+
raise StepFailed("skip_first must not be negative")
|
|
87
|
+
text = _canonical_text(value)
|
|
88
|
+
head, tail = text[: k.skip_first], text[k.skip_first :]
|
|
89
|
+
digest = hashlib.new(k.algo, (k.salt + tail).encode("utf-8")).hexdigest()
|
|
90
|
+
return head + digest
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _mask(value: object, k: MaskKwargs, _ctx: Context) -> object:
|
|
94
|
+
if len(k.char) != 1:
|
|
95
|
+
raise StepFailed("char must be one character")
|
|
96
|
+
if k.keep_first < 0 or k.keep_last < 0:
|
|
97
|
+
raise StepFailed("keep_first and keep_last must not be negative")
|
|
98
|
+
text = value if isinstance(value, str) else str(value)
|
|
99
|
+
if len(text) <= k.keep_first + k.keep_last:
|
|
100
|
+
return k.char * len(text)
|
|
101
|
+
end = len(text) - k.keep_last
|
|
102
|
+
return text[: k.keep_first] + k.char * (end - k.keep_first) + text[end:]
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _redact_date(value: object, k: RedactDateKwargs, _ctx: Context) -> object:
|
|
106
|
+
if isinstance(value, dt.datetime):
|
|
107
|
+
month = value.month if k.to == "month" else 1
|
|
108
|
+
return value.replace(month=month, day=1, hour=0, minute=0, second=0, microsecond=0)
|
|
109
|
+
if isinstance(value, dt.date):
|
|
110
|
+
return value.replace(month=value.month if k.to == "month" else 1, day=1)
|
|
111
|
+
raise StepFailed(f"redact_date needs a date or timestamp, got {type(value).__name__}")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@dataclass(frozen=True)
|
|
115
|
+
class MaskNumberKwargs:
|
|
116
|
+
"""mask_number options."""
|
|
117
|
+
|
|
118
|
+
value: int | float = 0
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _mask_number(_value: object, k: MaskNumberKwargs, ctx: Context) -> object:
|
|
122
|
+
"""``value`` in the column's own type, so the SCHEMA stays true."""
|
|
123
|
+
kind = ctx.target.kind
|
|
124
|
+
if kind in INT_BOUNDS:
|
|
125
|
+
return int(k.value)
|
|
126
|
+
if kind in {"float32", "float64"}:
|
|
127
|
+
return float(k.value)
|
|
128
|
+
if kind == "decimal":
|
|
129
|
+
return Decimal(repr(k.value)).quantize(Decimal(1).scaleb(-(ctx.target.scale or 0)))
|
|
130
|
+
if kind == "string":
|
|
131
|
+
return format(k.value)
|
|
132
|
+
return k.value # called from an expression, where there is no column type
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@dataclass(frozen=True)
|
|
136
|
+
class MaskHiddenKwargs:
|
|
137
|
+
"""mask_hidden options."""
|
|
138
|
+
|
|
139
|
+
value: str = "hidden"
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@dataclass(frozen=True)
|
|
143
|
+
class TokenizeKwargs:
|
|
144
|
+
"""tokenize options."""
|
|
145
|
+
|
|
146
|
+
key: str
|
|
147
|
+
"""The secret, e.g. ``${env:TOKEN_KEY}``; keep it out of the spec file."""
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _tokenize(value: object, k: TokenizeKwargs, _ctx: Context) -> object:
|
|
151
|
+
if not k.key:
|
|
152
|
+
raise StepFailed("tokenize needs a non-empty key")
|
|
153
|
+
text = _canonical_text(value).encode("utf-8")
|
|
154
|
+
return hmac.new(k.key.encode("utf-8"), text, hashlib.sha256).hexdigest()
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def register(registry: Registry) -> None:
|
|
158
|
+
"""Add the privacy builtins."""
|
|
159
|
+
registry.register(
|
|
160
|
+
Transform(
|
|
161
|
+
"hash",
|
|
162
|
+
_hash,
|
|
163
|
+
kwargs=HashKwargs,
|
|
164
|
+
positional="algo",
|
|
165
|
+
accepts=frozenset({ANY}),
|
|
166
|
+
produces=lambda _stage, _k: CType("string"),
|
|
167
|
+
)
|
|
168
|
+
)
|
|
169
|
+
registry.register(
|
|
170
|
+
Transform("mask", _mask, kwargs=MaskKwargs, accepts=frozenset({RAW, "string"}))
|
|
171
|
+
)
|
|
172
|
+
registry.register(
|
|
173
|
+
Transform(
|
|
174
|
+
"set_null",
|
|
175
|
+
lambda _v, _k, _c: None,
|
|
176
|
+
kwargs=NoKwargs,
|
|
177
|
+
accepts=frozenset({ANY}),
|
|
178
|
+
forces_nullable=True,
|
|
179
|
+
)
|
|
180
|
+
)
|
|
181
|
+
registry.register(
|
|
182
|
+
Transform(
|
|
183
|
+
"redact_date",
|
|
184
|
+
_redact_date,
|
|
185
|
+
kwargs=RedactDateKwargs,
|
|
186
|
+
positional="to",
|
|
187
|
+
accepts=frozenset({"date", "timestamp", "timestamptz"}),
|
|
188
|
+
)
|
|
189
|
+
)
|
|
190
|
+
registry.register(
|
|
191
|
+
Transform(
|
|
192
|
+
"mask_number",
|
|
193
|
+
_mask_number,
|
|
194
|
+
kwargs=MaskNumberKwargs,
|
|
195
|
+
positional="value",
|
|
196
|
+
accepts=frozenset({RAW, "string", *NUMERIC}),
|
|
197
|
+
column_kinds=frozenset({"string", *NUMERIC}),
|
|
198
|
+
)
|
|
199
|
+
)
|
|
200
|
+
registry.register(
|
|
201
|
+
Transform(
|
|
202
|
+
"mask_hidden",
|
|
203
|
+
lambda _v, k, _c: k.value,
|
|
204
|
+
kwargs=MaskHiddenKwargs,
|
|
205
|
+
positional="value",
|
|
206
|
+
accepts=frozenset({RAW, "string"}),
|
|
207
|
+
produces=lambda _stage, _k: CType("string"),
|
|
208
|
+
column_kinds=frozenset({"string"}),
|
|
209
|
+
)
|
|
210
|
+
)
|
|
211
|
+
registry.register(
|
|
212
|
+
Transform(
|
|
213
|
+
"tokenize",
|
|
214
|
+
_tokenize,
|
|
215
|
+
kwargs=TokenizeKwargs,
|
|
216
|
+
positional="key",
|
|
217
|
+
accepts=frozenset({ANY}),
|
|
218
|
+
produces=lambda _stage, _k: CType("string"),
|
|
219
|
+
)
|
|
220
|
+
)
|