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,249 @@
|
|
|
1
|
+
"""Text builtins, usually run before the cast (detailed design §6.1).
|
|
2
|
+
|
|
3
|
+
They take the raw value or a string. A raw value that is not a string (a number from a JSON
|
|
4
|
+
tap) is turned into text first. The stage is unchanged, except ``split``, which produces a
|
|
5
|
+
``list<string>``.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
import unicodedata
|
|
12
|
+
from collections.abc import Mapping
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from typing import TYPE_CHECKING, Any, Literal
|
|
15
|
+
|
|
16
|
+
from map_conform.errors import StepFailed
|
|
17
|
+
from map_conform.transforms.registry import NoKwargs, Registry, Transform
|
|
18
|
+
from map_conform.types.canonical import CType
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
from map_conform.transforms.registry import Context
|
|
22
|
+
|
|
23
|
+
_UNSET: Any = object()
|
|
24
|
+
_FLAGS = {"i": re.IGNORECASE, "m": re.MULTILINE, "s": re.DOTALL, "x": re.VERBOSE}
|
|
25
|
+
_CONTROL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]")
|
|
26
|
+
_WHITESPACE = re.compile(r"\s+")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _text(value: object) -> str:
|
|
30
|
+
if isinstance(value, str):
|
|
31
|
+
return value
|
|
32
|
+
if isinstance(value, bool):
|
|
33
|
+
return "true" if value else "false"
|
|
34
|
+
if isinstance(value, (Mapping, list)):
|
|
35
|
+
raise StepFailed(f"a text step got {type(value).__name__}")
|
|
36
|
+
return str(value)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _flags(text: str) -> int:
|
|
40
|
+
flags = 0
|
|
41
|
+
for letter in text:
|
|
42
|
+
if letter not in _FLAGS:
|
|
43
|
+
raise StepFailed(f"unknown regex flag {letter!r}; use i, m, s or x")
|
|
44
|
+
flags |= _FLAGS[letter]
|
|
45
|
+
return flags
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class TrimKwargs:
|
|
50
|
+
"""Characters to trim; whitespace by default."""
|
|
51
|
+
|
|
52
|
+
chars: str | None = None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class NullTokensKwargs:
|
|
57
|
+
"""Strings that become null."""
|
|
58
|
+
|
|
59
|
+
tokens: tuple[str, ...] = ()
|
|
60
|
+
case_sensitive: bool = False
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True)
|
|
64
|
+
class CharsKwargs:
|
|
65
|
+
"""Characters to strip from both ends."""
|
|
66
|
+
|
|
67
|
+
chars: str = ""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass(frozen=True)
|
|
71
|
+
class RegexReplaceKwargs:
|
|
72
|
+
"""A regular-expression substitution."""
|
|
73
|
+
|
|
74
|
+
pattern: str = ""
|
|
75
|
+
repl: str = ""
|
|
76
|
+
flags: str = ""
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass(frozen=True)
|
|
80
|
+
class RegexExtractKwargs:
|
|
81
|
+
"""Keep one group of the first match; no match gives null."""
|
|
82
|
+
|
|
83
|
+
pattern: str = ""
|
|
84
|
+
group: int | str = 1
|
|
85
|
+
flags: str = ""
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass(frozen=True)
|
|
89
|
+
class NormalizeKwargs:
|
|
90
|
+
"""A Unicode normalisation form."""
|
|
91
|
+
|
|
92
|
+
form: Literal["NFC", "NFD", "NFKC", "NFKD"] = "NFKC"
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@dataclass(frozen=True)
|
|
96
|
+
class PadKwargs:
|
|
97
|
+
"""Pad to a width."""
|
|
98
|
+
|
|
99
|
+
width: int = 0
|
|
100
|
+
fill: str = " "
|
|
101
|
+
side: Literal["left", "right"] = "left"
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@dataclass(frozen=True)
|
|
105
|
+
class LengthKwargs:
|
|
106
|
+
"""A number of characters."""
|
|
107
|
+
|
|
108
|
+
n: int = 0
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@dataclass(frozen=True)
|
|
112
|
+
class SubstringKwargs:
|
|
113
|
+
"""Characters from ``start`` (0-based), ``length`` of them or to the end."""
|
|
114
|
+
|
|
115
|
+
start: int = 0
|
|
116
|
+
length: int | None = None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@dataclass(frozen=True)
|
|
120
|
+
class MapValuesKwargs:
|
|
121
|
+
"""Replace whole values; unmapped values are kept unless ``default`` is given."""
|
|
122
|
+
|
|
123
|
+
values: Mapping[str, Any] = field(default_factory=dict)
|
|
124
|
+
default: Any = _UNSET
|
|
125
|
+
case_sensitive: bool = True
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@dataclass(frozen=True)
|
|
129
|
+
class SplitKwargs:
|
|
130
|
+
"""Split on a separator into a list of strings."""
|
|
131
|
+
|
|
132
|
+
sep: str = ","
|
|
133
|
+
trim: bool = True
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _trim(value: object, k: TrimKwargs, _ctx: Context) -> object:
|
|
137
|
+
return _text(value).strip(k.chars)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _null_tokens(value: object, k: NullTokensKwargs, _ctx: Context) -> object:
|
|
141
|
+
text = _text(value)
|
|
142
|
+
if k.case_sensitive:
|
|
143
|
+
return None if text in k.tokens else value
|
|
144
|
+
return None if any(text.casefold() == t.casefold() for t in k.tokens) else value
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _strip_chars(value: object, k: CharsKwargs, _ctx: Context) -> object:
|
|
148
|
+
return _text(value).strip(k.chars)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _regex_replace(value: object, k: RegexReplaceKwargs, _ctx: Context) -> object:
|
|
152
|
+
return re.sub(k.pattern, k.repl, _text(value), flags=_flags(k.flags))
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _regex_extract(value: object, k: RegexExtractKwargs, _ctx: Context) -> object:
|
|
156
|
+
match = re.search(k.pattern, _text(value), flags=_flags(k.flags))
|
|
157
|
+
if match is None:
|
|
158
|
+
return None
|
|
159
|
+
try:
|
|
160
|
+
return match.group(k.group)
|
|
161
|
+
except (IndexError, KeyError) as exc:
|
|
162
|
+
raise StepFailed(f"the pattern has no group {k.group!r}") from exc
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _pad(value: object, k: PadKwargs, _ctx: Context) -> object:
|
|
166
|
+
if len(k.fill) != 1:
|
|
167
|
+
raise StepFailed("fill must be one character")
|
|
168
|
+
text = _text(value)
|
|
169
|
+
return text.rjust(k.width, k.fill) if k.side == "left" else text.ljust(k.width, k.fill)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _map_values(value: object, k: MapValuesKwargs, _ctx: Context) -> object:
|
|
173
|
+
text = _text(value)
|
|
174
|
+
if k.case_sensitive:
|
|
175
|
+
if text in k.values:
|
|
176
|
+
return k.values[text]
|
|
177
|
+
else:
|
|
178
|
+
for source, target in k.values.items():
|
|
179
|
+
if source.casefold() == text.casefold():
|
|
180
|
+
return target
|
|
181
|
+
return value if k.default is _UNSET else k.default
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _split(value: object, k: SplitKwargs, _ctx: Context) -> object:
|
|
185
|
+
parts = _text(value).split(k.sep)
|
|
186
|
+
return [p.strip() for p in parts] if k.trim else parts
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def register(registry: Registry) -> None:
|
|
190
|
+
"""Add the text builtins."""
|
|
191
|
+
simple: list[tuple[str, Any]] = [
|
|
192
|
+
("lower", lambda v, _k, _c: _text(v).lower()),
|
|
193
|
+
("upper", lambda v, _k, _c: _text(v).upper()),
|
|
194
|
+
("title", lambda v, _k, _c: _text(v).title()),
|
|
195
|
+
("normalize_whitespace", lambda v, _k, _c: _WHITESPACE.sub(" ", _text(v)).strip()),
|
|
196
|
+
("remove_control_chars", lambda v, _k, _c: _CONTROL.sub("", _text(v))),
|
|
197
|
+
]
|
|
198
|
+
for name, fn in simple:
|
|
199
|
+
registry.register(Transform(name, fn, kwargs=NoKwargs))
|
|
200
|
+
registry.register(Transform("trim", _trim, kwargs=TrimKwargs, positional="chars"))
|
|
201
|
+
registry.register(
|
|
202
|
+
Transform("null_tokens", _null_tokens, kwargs=NullTokensKwargs, positional="tokens")
|
|
203
|
+
)
|
|
204
|
+
registry.register(
|
|
205
|
+
Transform("strip_chars", _strip_chars, kwargs=CharsKwargs, positional="chars")
|
|
206
|
+
)
|
|
207
|
+
registry.register(Transform("regex_replace", _regex_replace, kwargs=RegexReplaceKwargs))
|
|
208
|
+
registry.register(
|
|
209
|
+
Transform("regex_extract", _regex_extract, kwargs=RegexExtractKwargs, positional="pattern")
|
|
210
|
+
)
|
|
211
|
+
registry.register(
|
|
212
|
+
Transform(
|
|
213
|
+
"normalize_unicode",
|
|
214
|
+
lambda v, k, _c: unicodedata.normalize(k.form, _text(v)),
|
|
215
|
+
kwargs=NormalizeKwargs,
|
|
216
|
+
positional="form",
|
|
217
|
+
)
|
|
218
|
+
)
|
|
219
|
+
registry.register(Transform("pad", _pad, kwargs=PadKwargs, positional="width"))
|
|
220
|
+
registry.register(
|
|
221
|
+
Transform("left", lambda v, k, _c: _text(v)[: k.n], kwargs=LengthKwargs, positional="n")
|
|
222
|
+
)
|
|
223
|
+
registry.register(
|
|
224
|
+
Transform(
|
|
225
|
+
"right",
|
|
226
|
+
lambda v, k, _c: _text(v)[-k.n :] if k.n else "",
|
|
227
|
+
kwargs=LengthKwargs,
|
|
228
|
+
positional="n",
|
|
229
|
+
)
|
|
230
|
+
)
|
|
231
|
+
registry.register(
|
|
232
|
+
Transform(
|
|
233
|
+
"substring",
|
|
234
|
+
lambda v, k, _c: _text(v)[k.start : None if k.length is None else k.start + k.length],
|
|
235
|
+
kwargs=SubstringKwargs,
|
|
236
|
+
)
|
|
237
|
+
)
|
|
238
|
+
registry.register(
|
|
239
|
+
Transform("map_values", _map_values, kwargs=MapValuesKwargs, positional="values")
|
|
240
|
+
)
|
|
241
|
+
registry.register(
|
|
242
|
+
Transform(
|
|
243
|
+
"split",
|
|
244
|
+
_split,
|
|
245
|
+
kwargs=SplitKwargs,
|
|
246
|
+
positional="sep",
|
|
247
|
+
produces=lambda _stage, _k: CType("list", item=CType("string")),
|
|
248
|
+
)
|
|
249
|
+
)
|
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
"""Arrow implementations of the vectorisable builtins (detailed design §10.2, WBS 8.4).
|
|
2
|
+
|
|
3
|
+
A vector op takes the whole column and returns ``(result, todo)``. ``todo`` marks the rows
|
|
4
|
+
the op does not compute itself; the executor sends those through the scalar chain, so every
|
|
5
|
+
row gets exactly the scalar result (the *splice*, WBS 8.5). An op claims a row only when its
|
|
6
|
+
Arrow kernel is known to agree with the scalar code there, so it never fails: anything that
|
|
7
|
+
would be an error, or that needs the full grammar, is left to the scalar path.
|
|
8
|
+
|
|
9
|
+
The common case is claimed, the rest is spliced:
|
|
10
|
+
|
|
11
|
+
- **Text** ops claim rows of printable ASCII (plus tab, newline, carriage return), where
|
|
12
|
+
Arrow's string kernels and Python's ``str`` methods agree; other rows go row-wise.
|
|
13
|
+
- **Numeric casts** claim plain numbers (``-12``, ``3.50``) under the default grammar
|
|
14
|
+
(``us`` locale, no separators set) and integer, float or decimal input; currency,
|
|
15
|
+
separators, parentheses, percent and locales go row-wise.
|
|
16
|
+
- **Boolean casts** claim the configured true/false tokens and boolean input.
|
|
17
|
+
- **Temporal casts** to timestamptz, timestamp and date whose first format is ``iso`` and
|
|
18
|
+
whose zone is UTC claim strict ISO 8601 text (date, or date and time to the second) and
|
|
19
|
+
Arrow timestamps.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
from collections.abc import Callable
|
|
25
|
+
from decimal import Decimal
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
import pyarrow as pa
|
|
29
|
+
import pyarrow.compute as _compute
|
|
30
|
+
|
|
31
|
+
from map_conform.transforms.numeric import INT_BOUNDS
|
|
32
|
+
from map_conform.types.canonical import CType
|
|
33
|
+
from map_conform.types.to_arrow import to_arrow
|
|
34
|
+
|
|
35
|
+
Vector = Callable[[pa.Array, Any, CType], tuple[pa.Array, pa.Array]]
|
|
36
|
+
"""``(column, kwargs, column type) -> (result, todo mask)``."""
|
|
37
|
+
|
|
38
|
+
_SAFE = r"^[\x20-\x7e\t\n\r]*$"
|
|
39
|
+
_INTEGER = r"^[+-]?[0-9]{1,18}$"
|
|
40
|
+
_DECIMAL = r"^[+-]?[0-9]{1,20}(\.[0-9]{1,18})?$"
|
|
41
|
+
_FLOAT = r"^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][+-]?[0-9]+)?$"
|
|
42
|
+
_ISO = (
|
|
43
|
+
r"^[0-9]{4}-[0-9]{2}-[0-9]{2}([T ][0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]{1,6})?"
|
|
44
|
+
r"(Z|z|[+-][0-9]{2}:[0-9]{2})?)?$"
|
|
45
|
+
)
|
|
46
|
+
_ZONED = r"(Z|z|[+-][0-9]{2}:[0-9]{2})$"
|
|
47
|
+
|
|
48
|
+
# The pyarrow stubs type compute kernels as returning unions of arrays, chunked arrays and
|
|
49
|
+
# scalars, so array-in, array-out code cannot be checked through them. The parity suite
|
|
50
|
+
# (tests/parity) checks this module against the scalar path instead.
|
|
51
|
+
_pa: Any = pa
|
|
52
|
+
pc: Any = _compute
|
|
53
|
+
FALSE = _pa.scalar(value=False)
|
|
54
|
+
"""The fill value for masks."""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
# --- masks --------------------------------------------------------------------------------------
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _bool(mask: pa.Array, *, null: bool = False) -> pa.Array:
|
|
61
|
+
return pc.fill_null(mask, null)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def everything(column: pa.Array) -> pa.Array:
|
|
65
|
+
"""Every non-null row is todo (for input types an op does not handle)."""
|
|
66
|
+
return pc.is_valid(column)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def is_text(column: pa.Array) -> bool:
|
|
70
|
+
"""Whether the column holds text."""
|
|
71
|
+
return pa.types.is_string(column.type) or pa.types.is_large_string(column.type)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def unsafe_text(column: pa.Array) -> pa.Array:
|
|
75
|
+
"""Rows that are not plain printable ASCII (nulls are safe)."""
|
|
76
|
+
return pc.invert(_bool(pc.match_substring_regex(column, _SAFE), null=True))
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _or(*masks: pa.Array) -> pa.Array:
|
|
80
|
+
out = masks[0]
|
|
81
|
+
for mask in masks[1:]:
|
|
82
|
+
out = pc.or_(out, mask)
|
|
83
|
+
return out
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _text_op(
|
|
87
|
+
fn: Callable[[pa.Array], pa.Array],
|
|
88
|
+
) -> Callable[[pa.Array], tuple[pa.Array, pa.Array]]:
|
|
89
|
+
def run(column: pa.Array) -> tuple[pa.Array, pa.Array]:
|
|
90
|
+
if not is_text(column):
|
|
91
|
+
return _pa.nulls(len(column), pa.string()), everything(column)
|
|
92
|
+
return fn(column), unsafe_text(column)
|
|
93
|
+
|
|
94
|
+
return run
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
# --- text ---------------------------------------------------------------------------------------
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _ascii(chars: str | None) -> bool:
|
|
101
|
+
return chars is None or all(" " <= c <= "~" for c in chars)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def trim(column: pa.Array, k: Any, _t: CType) -> tuple[pa.Array, pa.Array]:
|
|
105
|
+
"""``trim``: whitespace, or the given characters."""
|
|
106
|
+
if not _ascii(k.chars):
|
|
107
|
+
return _pa.nulls(len(column), pa.string()), everything(column)
|
|
108
|
+
kernel = (
|
|
109
|
+
pc.utf8_trim_whitespace
|
|
110
|
+
if k.chars is None
|
|
111
|
+
else (lambda c: pc.utf8_trim(c, characters=k.chars))
|
|
112
|
+
)
|
|
113
|
+
return _text_op(kernel)(column)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def strip_chars(column: pa.Array, k: Any, _t: CType) -> tuple[pa.Array, pa.Array]:
|
|
117
|
+
"""``strip_chars``: the listed characters from both ends."""
|
|
118
|
+
if not _ascii(k.chars):
|
|
119
|
+
return _pa.nulls(len(column), pa.string()), everything(column)
|
|
120
|
+
return _text_op(lambda c: pc.utf8_trim(c, characters=k.chars))(column)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def lower(column: pa.Array, _k: Any, _t: CType) -> tuple[pa.Array, pa.Array]:
|
|
124
|
+
"""``lower`` on ASCII text."""
|
|
125
|
+
return _text_op(pc.ascii_lower)(column)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def upper(column: pa.Array, _k: Any, _t: CType) -> tuple[pa.Array, pa.Array]:
|
|
129
|
+
"""``upper`` on ASCII text."""
|
|
130
|
+
return _text_op(pc.ascii_upper)(column)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def left(column: pa.Array, k: Any, _t: CType) -> tuple[pa.Array, pa.Array]:
|
|
134
|
+
"""``left``: the first n characters."""
|
|
135
|
+
if k.n < 0:
|
|
136
|
+
return _pa.nulls(len(column), pa.string()), everything(column)
|
|
137
|
+
return _text_op(lambda c: pc.utf8_slice_codeunits(c, 0, k.n))(column)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def right(column: pa.Array, k: Any, _t: CType) -> tuple[pa.Array, pa.Array]:
|
|
141
|
+
"""``right``: the last n characters."""
|
|
142
|
+
if k.n <= 0:
|
|
143
|
+
return _pa.nulls(len(column), pa.string()), everything(column)
|
|
144
|
+
return _text_op(lambda c: pc.utf8_slice_codeunits(c, -k.n, 2**31 - 1))(column)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def set_null(column: pa.Array, _k: Any, _t: CType) -> tuple[pa.Array, pa.Array]:
|
|
148
|
+
"""``set_null``: every row null."""
|
|
149
|
+
return _pa.nulls(len(column), column.type), _pa.repeat(_pa.scalar(False), len(column)) # noqa: FBT003
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _null_tokens(text: pa.Array, tokens: tuple[str, ...], *, case_sensitive: bool) -> pa.Array:
|
|
153
|
+
"""Rows equal to a token (ASCII rows; the caller sends the others row-wise)."""
|
|
154
|
+
if not tokens:
|
|
155
|
+
return _pa.repeat(_pa.scalar(False), len(text)) # noqa: FBT003
|
|
156
|
+
if case_sensitive:
|
|
157
|
+
return _bool(pc.is_in(text, value_set=_pa.array(tokens)))
|
|
158
|
+
folded = _pa.array([t.casefold() for t in tokens])
|
|
159
|
+
return _bool(pc.is_in(pc.ascii_lower(text), value_set=folded))
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def null_tokens(column: pa.Array, k: Any, _t: CType) -> tuple[pa.Array, pa.Array]:
|
|
163
|
+
"""``null_tokens``: null for any token, the value otherwise."""
|
|
164
|
+
if not is_text(column) or not all(_ascii(t) for t in k.tokens):
|
|
165
|
+
return _pa.nulls(len(column), pa.string()), everything(column)
|
|
166
|
+
hit = _null_tokens(column, k.tokens, case_sensitive=k.case_sensitive)
|
|
167
|
+
return pc.if_else(hit, _pa.scalar(None, pa.string()), column), unsafe_text(column)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
# --- cleanup shared by casts ------------------------------------------------------------------
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def clean(column: pa.Array, options: Any) -> tuple[pa.Array, pa.Array]:
|
|
174
|
+
"""Trim and null tokens, as ``casts.clean`` does; non-ASCII rows are todo."""
|
|
175
|
+
text = pc.utf8_trim_whitespace(column) if options.trim else column
|
|
176
|
+
if not all(_ascii(t) for t in options.null_tokens):
|
|
177
|
+
return text, everything(column)
|
|
178
|
+
hit = _null_tokens(text, options.null_tokens, case_sensitive=options.null_tokens_case_sensitive)
|
|
179
|
+
return pc.if_else(hit, _pa.scalar(None, pa.string()), text), unsafe_text(column)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _matches(column: pa.Array, pattern: str) -> pa.Array:
|
|
183
|
+
return _bool(pc.match_substring_regex(column, pattern))
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
# --- casts ----------------------------------------------------------------------------------------
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def cast_string(column: pa.Array, args: Any, target: CType) -> tuple[pa.Array, pa.Array]:
|
|
190
|
+
"""Cast to string from text: cleanup, empty strings, length limits."""
|
|
191
|
+
options = args.options
|
|
192
|
+
if not is_text(column):
|
|
193
|
+
return _pa.nulls(len(column), pa.string()), everything(column)
|
|
194
|
+
trimmed = pc.utf8_trim_whitespace(column) if options.trim else column
|
|
195
|
+
empty = _bool(pc.equal(trimmed, ""))
|
|
196
|
+
cleaned, todo = clean(column, options)
|
|
197
|
+
if options.empty_string_for_string == "keep":
|
|
198
|
+
cleaned = pc.if_else(empty, _pa.scalar(""), cleaned)
|
|
199
|
+
else:
|
|
200
|
+
cleaned = pc.if_else(empty, _pa.scalar(None, pa.string()), cleaned)
|
|
201
|
+
limit = target.length if target.length is not None else options.max_length
|
|
202
|
+
if limit is not None:
|
|
203
|
+
too_long = _bool(pc.greater(pc.utf8_length(cleaned), limit))
|
|
204
|
+
todo = _or(todo, too_long) # truncation or the error: the scalar path decides
|
|
205
|
+
return cleaned, todo
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _numeric_text(column: pa.Array, options: Any, pattern: str) -> tuple[pa.Array, pa.Array]:
|
|
209
|
+
"""Cleaned text that is a plain number under the default grammar; todo for the rest."""
|
|
210
|
+
cleaned, todo = clean(column, options)
|
|
211
|
+
default_grammar = (
|
|
212
|
+
options.locale == "us" and options.thousands is None and options.decimal_point is None
|
|
213
|
+
)
|
|
214
|
+
if not default_grammar:
|
|
215
|
+
return cleaned, everything(column)
|
|
216
|
+
plain = pc.or_(pc.is_null(cleaned), _matches(cleaned, pattern))
|
|
217
|
+
unsigned = pc.replace_substring_regex(cleaned, r"^\+", "") # Arrow does not parse "+"
|
|
218
|
+
return unsigned, _or(todo, pc.invert(_bool(plain)))
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _bounded_int(values: pa.Array, target: CType) -> tuple[pa.Array, pa.Array]:
|
|
222
|
+
low, high = INT_BOUNDS[target.kind]
|
|
223
|
+
outside = _bool(pc.or_(pc.less(values, low), pc.greater(values, high)))
|
|
224
|
+
safe = pc.if_else(outside, _pa.scalar(None, values.type), values)
|
|
225
|
+
return pc.cast(safe, to_arrow(target)), outside
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def cast_int(column: pa.Array, args: Any, target: CType) -> tuple[pa.Array, pa.Array]:
|
|
229
|
+
"""Cast to int16/32/64 from integers and plain integer text."""
|
|
230
|
+
if pa.types.is_integer(column.type):
|
|
231
|
+
return _bounded_int(pc.cast(column, pa.int64()), target)
|
|
232
|
+
if not is_text(column):
|
|
233
|
+
return _pa.nulls(len(column), to_arrow(target)), everything(column)
|
|
234
|
+
text, todo = _numeric_text(column, args.options, _INTEGER)
|
|
235
|
+
values = pc.cast(pc.if_else(todo, _pa.scalar(None, pa.string()), text), pa.int64())
|
|
236
|
+
result, outside = _bounded_int(values, target)
|
|
237
|
+
return result, _or(todo, outside)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def cast_float(column: pa.Array, args: Any, target: CType) -> tuple[pa.Array, pa.Array]:
|
|
241
|
+
"""Cast to float32/64 from finite numbers and plain number text."""
|
|
242
|
+
arrow_type = to_arrow(target)
|
|
243
|
+
if pa.types.is_integer(column.type) or pa.types.is_floating(column.type):
|
|
244
|
+
values = pc.cast(column, pa.float64())
|
|
245
|
+
elif is_text(column):
|
|
246
|
+
text, todo = _numeric_text(column, args.options, _FLOAT)
|
|
247
|
+
values = pc.cast(pc.if_else(todo, _pa.scalar(None, pa.string()), text), pa.float64())
|
|
248
|
+
finite = _bool(pc.is_finite(values), null=True)
|
|
249
|
+
result = pc.cast(values, arrow_type, safe=False)
|
|
250
|
+
overflow = _bool(pc.invert(pc.is_finite(result)))
|
|
251
|
+
return result, _or(todo, pc.invert(finite), overflow)
|
|
252
|
+
else:
|
|
253
|
+
return _pa.nulls(len(column), arrow_type), everything(column)
|
|
254
|
+
finite = _bool(pc.is_finite(values), null=True)
|
|
255
|
+
result = pc.cast(values, arrow_type, safe=False)
|
|
256
|
+
overflow = _bool(pc.invert(pc.is_finite(result)))
|
|
257
|
+
return result, _or(pc.invert(finite), overflow)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def cast_decimal(column: pa.Array, args: Any, target: CType) -> tuple[pa.Array, pa.Array]:
|
|
261
|
+
"""Cast to decimal(p,s) from integers and plain decimal text, rounding half away from 0."""
|
|
262
|
+
precision, scale = target.decimal_params
|
|
263
|
+
rounding = args.options.rounding or "half_up"
|
|
264
|
+
if rounding != "half_up":
|
|
265
|
+
return _pa.nulls(len(column), to_arrow(target)), everything(column)
|
|
266
|
+
if pa.types.is_integer(column.type):
|
|
267
|
+
wide, todo = (
|
|
268
|
+
pc.cast(column, pa.decimal128(38, 18)),
|
|
269
|
+
_pa.repeat(_pa.scalar(value=False), len(column)),
|
|
270
|
+
)
|
|
271
|
+
elif is_text(column):
|
|
272
|
+
text, todo = _numeric_text(column, args.options, _DECIMAL)
|
|
273
|
+
wide = pc.cast(pc.if_else(todo, _pa.scalar(None, pa.string()), text), pa.decimal128(38, 18))
|
|
274
|
+
else:
|
|
275
|
+
return _pa.nulls(len(column), to_arrow(target)), everything(column)
|
|
276
|
+
rounded = pc.round(wide, ndigits=scale, round_mode="half_towards_infinity")
|
|
277
|
+
limit = Decimal(10) ** (precision - scale)
|
|
278
|
+
too_big = _bool(pc.greater_equal(pc.abs(rounded), _pa.scalar(limit, pa.decimal128(38, 18))))
|
|
279
|
+
safe = pc.if_else(too_big, _pa.scalar(None, rounded.type), rounded)
|
|
280
|
+
return pc.cast(safe, to_arrow(target)), _or(todo, too_big)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def cast_boolean(column: pa.Array, args: Any, _target: CType) -> tuple[pa.Array, pa.Array]:
|
|
284
|
+
"""Cast to boolean from booleans and the configured true/false tokens."""
|
|
285
|
+
options = args.options
|
|
286
|
+
if pa.types.is_boolean(column.type):
|
|
287
|
+
return column, _pa.repeat(_pa.scalar(False), len(column)) # noqa: FBT003
|
|
288
|
+
tokens = (*options.true_values, *options.false_values)
|
|
289
|
+
if not is_text(column) or not all(_ascii(t) for t in tokens):
|
|
290
|
+
return _pa.nulls(len(column), pa.bool_()), everything(column)
|
|
291
|
+
text, todo = clean(column, options)
|
|
292
|
+
if not options.case_sensitive:
|
|
293
|
+
text = pc.ascii_lower(text)
|
|
294
|
+
fold = (lambda t: t) if options.case_sensitive else str.lower
|
|
295
|
+
is_true = _bool(pc.is_in(text, value_set=_pa.array([fold(t) for t in options.true_values])))
|
|
296
|
+
is_false = _bool(pc.is_in(text, value_set=_pa.array([fold(t) for t in options.false_values])))
|
|
297
|
+
known = _or(is_true, is_false, pc.is_null(text))
|
|
298
|
+
result = pc.if_else(is_true, True, pc.if_else(is_false, False, _pa.scalar(None, pa.bool_()))) # noqa: FBT003
|
|
299
|
+
return result, _or(todo, pc.invert(known), pc.and_(is_true, is_false))
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _precision(values: pa.Array, precision: str) -> pa.Array:
|
|
303
|
+
if precision == "s":
|
|
304
|
+
return pc.floor_temporal(values, unit="second")
|
|
305
|
+
if precision == "ms":
|
|
306
|
+
return pc.floor_temporal(values, unit="millisecond")
|
|
307
|
+
return values
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def year_bounds(values: pa.Array, options: Any) -> pa.Array:
|
|
311
|
+
"""Rows outside ``min_year``/``max_year``."""
|
|
312
|
+
years = pc.year(values)
|
|
313
|
+
outside = _pa.repeat(_pa.scalar(False), len(values)) # noqa: FBT003
|
|
314
|
+
if options.min_year is not None:
|
|
315
|
+
outside = pc.or_(outside, _bool(pc.less(years, options.min_year)))
|
|
316
|
+
if options.max_year is not None:
|
|
317
|
+
outside = pc.or_(outside, _bool(pc.greater(years, options.max_year)))
|
|
318
|
+
return outside
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _iso_utc(text: pa.Array) -> pa.Array:
|
|
322
|
+
"""Claimed ISO text as UTC instants.
|
|
323
|
+
|
|
324
|
+
A space becomes T, a date gets midnight, a naive value gets Z (only claimed when the zone
|
|
325
|
+
is UTC), and a lowercase z becomes Z.
|
|
326
|
+
"""
|
|
327
|
+
text = pc.replace_substring(text, " ", "T")
|
|
328
|
+
text = pc.replace_substring_regex(text, r"^([0-9]{4}-[0-9]{2}-[0-9]{2})$", r"\1T00:00:00")
|
|
329
|
+
text = pc.replace_substring_regex(text, r"z$", "Z")
|
|
330
|
+
zoned = _matches(text, _ZONED)
|
|
331
|
+
text = pc.if_else(zoned, text, pc.binary_join_element_wise(text, "Z", ""))
|
|
332
|
+
return pc.cast(text, pa.timestamp("us", tz="UTC"))
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def cast_temporal(column: pa.Array, args: Any, target: CType) -> tuple[pa.Array, pa.Array]:
|
|
336
|
+
"""Cast to timestamptz, timestamp or date from ISO text or Arrow timestamps (zone UTC)."""
|
|
337
|
+
options = args.options
|
|
338
|
+
kind = target.kind
|
|
339
|
+
arrow_type = to_arrow(target)
|
|
340
|
+
nothing = _pa.nulls(len(column), arrow_type)
|
|
341
|
+
if options.tz != "UTC" or not options.formats or options.formats[0] != "iso":
|
|
342
|
+
return nothing, everything(column)
|
|
343
|
+
if pa.types.is_timestamp(column.type):
|
|
344
|
+
utc = pc.cast(column, pa.timestamp("us", tz="UTC")) # naive values are UTC
|
|
345
|
+
todo = _pa.repeat(_pa.scalar(False), len(column)) # noqa: FBT003
|
|
346
|
+
elif is_text(column):
|
|
347
|
+
text, todo = clean(column, options)
|
|
348
|
+
iso = pc.or_(pc.is_null(text), _matches(text, _ISO))
|
|
349
|
+
todo = _or(todo, pc.invert(_bool(iso)))
|
|
350
|
+
try:
|
|
351
|
+
utc = _iso_utc(pc.if_else(todo, _pa.scalar(None, pa.string()), text))
|
|
352
|
+
except (pa.ArrowInvalid, pa.ArrowNotImplementedError):
|
|
353
|
+
return nothing, everything(column) # e.g. a month 13: the scalar path reports it
|
|
354
|
+
else:
|
|
355
|
+
return nothing, everything(column)
|
|
356
|
+
todo = _or(todo, year_bounds(utc, options))
|
|
357
|
+
if kind == "timestamptz":
|
|
358
|
+
result = _precision(utc, options.output_precision)
|
|
359
|
+
elif kind == "timestamp": # the wall time in UTC
|
|
360
|
+
result = _precision(pc.cast(utc, pa.timestamp("us")), options.output_precision)
|
|
361
|
+
else:
|
|
362
|
+
result = pc.cast(pc.cast(utc, pa.timestamp("us")), pa.date32())
|
|
363
|
+
return result, todo
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
TRANSFORMS: dict[str, Vector] = {
|
|
367
|
+
"trim": trim,
|
|
368
|
+
"strip_chars": strip_chars,
|
|
369
|
+
"lower": lower,
|
|
370
|
+
"upper": upper,
|
|
371
|
+
"left": left,
|
|
372
|
+
"right": right,
|
|
373
|
+
"set_null": set_null,
|
|
374
|
+
"null_tokens": null_tokens,
|
|
375
|
+
}
|
|
376
|
+
"""Builtins with an Arrow implementation, by name."""
|
|
377
|
+
|
|
378
|
+
CASTS: dict[str, Vector] = {
|
|
379
|
+
"string": cast_string,
|
|
380
|
+
**dict.fromkeys(("int16", "int32", "int64"), cast_int),
|
|
381
|
+
**dict.fromkeys(("float32", "float64"), cast_float),
|
|
382
|
+
"decimal": cast_decimal,
|
|
383
|
+
"boolean": cast_boolean,
|
|
384
|
+
**dict.fromkeys(("timestamptz", "timestamp", "date"), cast_temporal),
|
|
385
|
+
}
|
|
386
|
+
"""Casts with an Arrow implementation, by target kind."""
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""The canonical type system (CType)."""
|