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,116 @@
|
|
|
1
|
+
"""The Transform protocol and the builtin registry (detailed design §6).
|
|
2
|
+
|
|
3
|
+
A transform is a name, a frozen kwargs dataclass (validated at plan compile time by the same
|
|
4
|
+
strict parser as the spec), the types it accepts and produces, and a scalar function. An
|
|
5
|
+
optional Arrow function marks it vectorisable for the columnar executor.
|
|
6
|
+
|
|
7
|
+
Types are tracked through a chain as a *stage*: ``None`` means the raw value from the tap,
|
|
8
|
+
before the cast; otherwise it is the CType the value has at that point. A step's ``accepts``
|
|
9
|
+
lists kinds, plus ``"raw"`` for steps that may run before the cast.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from collections.abc import Callable, Mapping
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from typing import TYPE_CHECKING, Any
|
|
17
|
+
|
|
18
|
+
from map_conform.spec.model import ColumnSpec, Defaults
|
|
19
|
+
from map_conform.types.canonical import CType
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
from _typeshed import DataclassInstance # noqa: TC004 -- typing only
|
|
23
|
+
|
|
24
|
+
RAW = "raw"
|
|
25
|
+
ANY = "any"
|
|
26
|
+
NUMERIC = frozenset({"int16", "int32", "int64", "float32", "float64", "decimal"})
|
|
27
|
+
TEMPORAL = frozenset({"date", "time", "timestamp", "timestamptz"})
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class Context:
|
|
32
|
+
"""What a step knows about the value it is working on."""
|
|
33
|
+
|
|
34
|
+
stream: str
|
|
35
|
+
column: str
|
|
36
|
+
settings: Defaults
|
|
37
|
+
target: CType
|
|
38
|
+
"""The column's declared output type."""
|
|
39
|
+
row: int | None = None
|
|
40
|
+
fake: Any = None
|
|
41
|
+
"""The stream's :class:`~map_conform.transforms.fake.FakeData`, for the fake step."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class NoKwargs:
|
|
46
|
+
"""For transforms that take no keyword arguments."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class Transform:
|
|
51
|
+
"""One builtin step."""
|
|
52
|
+
|
|
53
|
+
name: str
|
|
54
|
+
scalar: Callable[[Any, Any, Context], Any]
|
|
55
|
+
"""``(value, kwargs, ctx) -> value``; raises :class:`~map_conform.errors.StepFailed`."""
|
|
56
|
+
kwargs: type[DataclassInstance] = NoKwargs
|
|
57
|
+
accepts: frozenset[str] = frozenset({RAW, "string"})
|
|
58
|
+
produces: Callable[[CType | None, Any], CType | None] | None = None
|
|
59
|
+
"""``(input stage, kwargs) -> output stage``; None keeps the input stage."""
|
|
60
|
+
positional: str | None = None
|
|
61
|
+
"""The kwarg a scalar step argument fills, e.g. ``chars`` for ``{strip_chars: "$, "}``."""
|
|
62
|
+
arrow: Callable[..., Any] | None = None
|
|
63
|
+
doc: str = ""
|
|
64
|
+
null_safe: bool = False
|
|
65
|
+
"""True when the step must see nulls; otherwise nulls pass through untouched."""
|
|
66
|
+
defaults: Callable[[Defaults, ColumnSpec | None], dict[str, Any]] | None = None
|
|
67
|
+
"""For casts: kwargs taken from the stream defaults and column overrides."""
|
|
68
|
+
forces_nullable: bool = False
|
|
69
|
+
"""The step can produce null whatever the input (set_null), so the column is nullable."""
|
|
70
|
+
column_kinds: frozenset[str] | None = None
|
|
71
|
+
"""The column types the step may be used in, when it is restricted (mask_hidden)."""
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def vectorised(self) -> bool:
|
|
75
|
+
"""Whether the columnar executor can run this step on whole arrays."""
|
|
76
|
+
return self.arrow is not None
|
|
77
|
+
|
|
78
|
+
def accepts_stage(self, stage: CType | None) -> bool:
|
|
79
|
+
"""Whether a value at ``stage`` may enter this step."""
|
|
80
|
+
if ANY in self.accepts:
|
|
81
|
+
return True
|
|
82
|
+
if stage is None:
|
|
83
|
+
return RAW in self.accepts
|
|
84
|
+
return stage.kind in self.accepts
|
|
85
|
+
|
|
86
|
+
def output_stage(self, stage: CType | None, kwargs: object) -> CType | None:
|
|
87
|
+
"""The stage after this step."""
|
|
88
|
+
return stage if self.produces is None else self.produces(stage, kwargs)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@dataclass
|
|
92
|
+
class Registry:
|
|
93
|
+
"""Builtins by name. Casts are registered per target kind."""
|
|
94
|
+
|
|
95
|
+
transforms: dict[str, Transform] = field(default_factory=dict)
|
|
96
|
+
casts: dict[str, Transform] = field(default_factory=dict)
|
|
97
|
+
|
|
98
|
+
def register(self, transform: Transform) -> Transform:
|
|
99
|
+
"""Add a builtin; names are unique."""
|
|
100
|
+
if transform.name in self.transforms or transform.name == "cast":
|
|
101
|
+
msg = f"a transform named {transform.name!r} is already registered"
|
|
102
|
+
raise ValueError(msg)
|
|
103
|
+
self.transforms[transform.name] = transform
|
|
104
|
+
return transform
|
|
105
|
+
|
|
106
|
+
def register_cast(self, kinds: frozenset[str] | set[str], transform: Transform) -> None:
|
|
107
|
+
"""Add the caster for these target kinds."""
|
|
108
|
+
for kind in kinds:
|
|
109
|
+
if kind in self.casts:
|
|
110
|
+
msg = f"a cast to {kind!r} is already registered"
|
|
111
|
+
raise ValueError(msg)
|
|
112
|
+
self.casts[kind] = transform
|
|
113
|
+
|
|
114
|
+
def names(self) -> Mapping[str, Transform]:
|
|
115
|
+
"""Every registered builtin."""
|
|
116
|
+
return self.transforms
|
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
"""Temporal casts and builtins (detailed design §6.3).
|
|
2
|
+
|
|
3
|
+
Formats are tried in order; the first that parses wins:
|
|
4
|
+
|
|
5
|
+
- a ``strptime`` pattern (anything containing ``%``);
|
|
6
|
+
- ``iso``: ISO-8601 dates, times and timestamps, leniently: ``Z``/``z``, a space or ``t``
|
|
7
|
+
separator, any number of fraction digits (kept to microseconds), date-only;
|
|
8
|
+
- ``excel_serial``: the 1900 date system, with Lotus's bug: serials below 60 count from
|
|
9
|
+
1899-12-31, and 60 (the 1900-02-29 that never existed) is an error;
|
|
10
|
+
``excel_serial_1904``: the 1904 system;
|
|
11
|
+
- ``epoch_s`` / ``epoch_ms`` / ``epoch_us`` / ``epoch_ns``, and ``epoch_auto`` by magnitude;
|
|
12
|
+
- ``rfc2822``.
|
|
13
|
+
|
|
14
|
+
A naive result is placed in ``tz`` (default: the stream's ``assume_tz``). A wall time that
|
|
15
|
+
happens twice (DST ends) follows ``ambiguous``; one that never happens (DST starts) follows
|
|
16
|
+
``nonexistent``. Both default to ``error``. ``timestamptz`` values are UTC.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import datetime as dt
|
|
22
|
+
import re
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
|
25
|
+
from email.utils import parsedate_to_datetime
|
|
26
|
+
from typing import TYPE_CHECKING, Any, Literal
|
|
27
|
+
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
|
28
|
+
|
|
29
|
+
from map_conform.errors import StepFailed
|
|
30
|
+
from map_conform.spec._struct import documented
|
|
31
|
+
from map_conform.transforms.casts import Cleanup, clean, cleanup_defaults
|
|
32
|
+
from map_conform.transforms.registry import RAW, TEMPORAL, Registry, Transform
|
|
33
|
+
from map_conform.types.canonical import CType, Kind
|
|
34
|
+
|
|
35
|
+
if TYPE_CHECKING:
|
|
36
|
+
from collections.abc import Callable
|
|
37
|
+
|
|
38
|
+
from map_conform.plan.ops import CastArgs
|
|
39
|
+
from map_conform.spec.model import ColumnSpec, Defaults
|
|
40
|
+
from map_conform.transforms.registry import Context
|
|
41
|
+
|
|
42
|
+
NAMED_FORMATS = frozenset(
|
|
43
|
+
{
|
|
44
|
+
"iso",
|
|
45
|
+
"excel_serial",
|
|
46
|
+
"excel_serial_1904",
|
|
47
|
+
"epoch_s",
|
|
48
|
+
"epoch_ms",
|
|
49
|
+
"epoch_us",
|
|
50
|
+
"epoch_ns",
|
|
51
|
+
"epoch_auto",
|
|
52
|
+
"rfc2822",
|
|
53
|
+
}
|
|
54
|
+
)
|
|
55
|
+
_EXCEL_1900 = dt.datetime(1899, 12, 30) # noqa: DTZ001 -- serials are naive wall time
|
|
56
|
+
_EXCEL_EARLY = dt.datetime(1899, 12, 31) # noqa: DTZ001
|
|
57
|
+
_EXCEL_1904 = dt.datetime(1904, 1, 1) # noqa: DTZ001
|
|
58
|
+
_LOTUS_LEAP_DAY = 60
|
|
59
|
+
_EPOCH_DIVISORS = {"epoch_s": 1, "epoch_ms": 10**3, "epoch_us": 10**6, "epoch_ns": 10**9}
|
|
60
|
+
_MICROS_PER_DAY = 86_400 * 10**6
|
|
61
|
+
_ISO_DATE = r"(?P<date>\d{4}-\d{2}-\d{2})"
|
|
62
|
+
_ISO_TIME = r"(?P<h>\d{2}):(?P<m>\d{2})(?::(?P<s>\d{2})(?:[.,](?P<f>\d+))?)?"
|
|
63
|
+
_ISO_ZONE = r"(?P<z>[Zz]|[+-]\d{2}(?::?\d{2})?)?"
|
|
64
|
+
_ISO_TIMESTAMP = re.compile(rf"^{_ISO_DATE}(?:[Tt ]{_ISO_TIME})?\s*{_ISO_ZONE}$")
|
|
65
|
+
_ISO_TIME_ONLY = re.compile(rf"^{_ISO_TIME}\s*{_ISO_ZONE}$")
|
|
66
|
+
_NUMBER = re.compile(r"^[+-]?\d+(?:\.\d+)?$")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _formats_problem(formats: tuple[str, ...]) -> str | None:
|
|
70
|
+
unknown = [f for f in formats if "%" not in f and f not in NAMED_FORMATS]
|
|
71
|
+
if unknown:
|
|
72
|
+
return (
|
|
73
|
+
f"unknown format(s) {unknown}; use a strptime pattern or one of {sorted(NAMED_FORMATS)}"
|
|
74
|
+
)
|
|
75
|
+
return None if formats else "give at least one format"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _zone_problem(tz: str) -> str | None:
|
|
79
|
+
try:
|
|
80
|
+
ZoneInfo(tz)
|
|
81
|
+
except (ZoneInfoNotFoundError, ValueError):
|
|
82
|
+
return f"unknown time zone {tz!r}"
|
|
83
|
+
return None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass(frozen=True)
|
|
87
|
+
class TemporalCast(Cleanup):
|
|
88
|
+
"""Options for casts to timestamptz, timestamp, date and time."""
|
|
89
|
+
|
|
90
|
+
formats: tuple[str, ...] = documented(
|
|
91
|
+
"Formats tried in order.", default=("iso",), metadata={"check": _formats_problem}
|
|
92
|
+
)
|
|
93
|
+
tz: str = documented("Zone of naive input.", default="UTC", metadata={"check": _zone_problem})
|
|
94
|
+
ambiguous: Literal["error", "earliest", "latest"] = "error"
|
|
95
|
+
nonexistent: Literal["error", "shift"] = "error"
|
|
96
|
+
min_year: int | None = None
|
|
97
|
+
max_year: int | None = None
|
|
98
|
+
output_precision: Literal["s", "ms", "us"] = "us"
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _temporal_defaults(settings: Defaults, column: ColumnSpec | None) -> dict[str, Any]:
|
|
102
|
+
out = cleanup_defaults(settings, column)
|
|
103
|
+
out["formats"] = list(settings.timestamp.formats)
|
|
104
|
+
out["tz"] = settings.timestamp.assume_tz
|
|
105
|
+
out["output_precision"] = settings.timestamp.output_precision
|
|
106
|
+
return out
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# --- parsing ----------------------------------------------------------------------------------
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _offset(zone: str) -> dt.tzinfo:
|
|
113
|
+
if zone in {"Z", "z"}:
|
|
114
|
+
return dt.UTC
|
|
115
|
+
sign = -1 if zone[0] == "-" else 1
|
|
116
|
+
digits = zone[1:].replace(":", "")
|
|
117
|
+
hours, minutes = int(digits[:2]), int(digits[2:4] or 0)
|
|
118
|
+
return dt.timezone(sign * dt.timedelta(hours=hours, minutes=minutes))
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _iso(text: str) -> dt.datetime | dt.time | None:
|
|
122
|
+
if match := _ISO_TIMESTAMP.match(text):
|
|
123
|
+
day = dt.date.fromisoformat(match["date"])
|
|
124
|
+
clock = _clock(match) if match["h"] else dt.time()
|
|
125
|
+
tzinfo = _offset(match["z"]) if match["z"] else None
|
|
126
|
+
return dt.datetime.combine(day, clock, tzinfo)
|
|
127
|
+
if match := _ISO_TIME_ONLY.match(text):
|
|
128
|
+
clock = _clock(match)
|
|
129
|
+
return clock.replace(tzinfo=_offset(match["z"])) if match["z"] else clock
|
|
130
|
+
return None
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _clock(match: re.Match[str]) -> dt.time:
|
|
134
|
+
fraction = (match["f"] or "")[:6].ljust(6, "0")
|
|
135
|
+
return dt.time(int(match["h"]), int(match["m"]), int(match["s"] or 0), int(fraction))
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _serial(text: str, *, system_1904: bool) -> dt.datetime | None:
|
|
139
|
+
if not _NUMBER.match(text):
|
|
140
|
+
return None
|
|
141
|
+
serial = Decimal(text)
|
|
142
|
+
if serial <= 0:
|
|
143
|
+
raise StepFailed(f"Excel serial {text} is before the epoch")
|
|
144
|
+
days = int(serial)
|
|
145
|
+
micros = int(((serial - days) * _MICROS_PER_DAY).to_integral_value(ROUND_HALF_UP))
|
|
146
|
+
if system_1904:
|
|
147
|
+
base = _EXCEL_1904
|
|
148
|
+
elif days == _LOTUS_LEAP_DAY:
|
|
149
|
+
raise StepFailed("Excel serial 60 is 1900-02-29, which never existed")
|
|
150
|
+
else:
|
|
151
|
+
base = _EXCEL_EARLY if days < _LOTUS_LEAP_DAY else _EXCEL_1900
|
|
152
|
+
return base + dt.timedelta(days=days, microseconds=micros)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _epoch(text: str, unit: str) -> dt.datetime | None:
|
|
156
|
+
if not _NUMBER.match(text):
|
|
157
|
+
return None
|
|
158
|
+
number = Decimal(text)
|
|
159
|
+
if unit == "epoch_auto":
|
|
160
|
+
size = abs(number)
|
|
161
|
+
unit = (
|
|
162
|
+
"epoch_s"
|
|
163
|
+
if size < 10**11
|
|
164
|
+
else "epoch_ms"
|
|
165
|
+
if size < 10**14
|
|
166
|
+
else "epoch_us"
|
|
167
|
+
if size < 10**17
|
|
168
|
+
else "epoch_ns"
|
|
169
|
+
)
|
|
170
|
+
micros = int(number * 10**6 / _EPOCH_DIVISORS[unit]) # truncates below a microsecond
|
|
171
|
+
return dt.datetime(1970, 1, 1, tzinfo=dt.UTC) + dt.timedelta(microseconds=micros)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _rfc2822(text: str) -> dt.datetime | None:
|
|
175
|
+
return parsedate_to_datetime(text)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _parser(fmt: str) -> Callable[[str], dt.datetime | dt.time | None]:
|
|
179
|
+
if "%" in fmt:
|
|
180
|
+
return lambda text: dt.datetime.strptime(text, fmt) # noqa: DTZ007 -- zoned later
|
|
181
|
+
if fmt in {"excel_serial", "excel_serial_1904"}:
|
|
182
|
+
return lambda text: _serial(text, system_1904=fmt == "excel_serial_1904")
|
|
183
|
+
if fmt.startswith("epoch_"):
|
|
184
|
+
return lambda text: _epoch(text, fmt)
|
|
185
|
+
return {"iso": _iso, "rfc2822": _rfc2822}[fmt]
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _one_format(text: str, fmt: str) -> dt.datetime | dt.time | None:
|
|
189
|
+
"""Parse with one format; None when it does not apply."""
|
|
190
|
+
try:
|
|
191
|
+
return _parser(fmt)(text)
|
|
192
|
+
except (ValueError, OverflowError, InvalidOperation, TypeError, IndexError):
|
|
193
|
+
return None
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def parse_temporal(value: object, options: TemporalCast) -> dt.datetime | dt.time | dt.date | None:
|
|
197
|
+
"""Parse a raw value with the configured formats, before zones and target types."""
|
|
198
|
+
cleaned = clean(value, options)
|
|
199
|
+
if cleaned is None or isinstance(cleaned, (dt.datetime, dt.date, dt.time)):
|
|
200
|
+
return cleaned
|
|
201
|
+
if isinstance(cleaned, bool):
|
|
202
|
+
raise StepFailed("a boolean is not a date")
|
|
203
|
+
if isinstance(cleaned, str):
|
|
204
|
+
text = cleaned
|
|
205
|
+
elif isinstance(cleaned, Decimal): # the SDK decodes JSON fractions as Decimal
|
|
206
|
+
text = format(cleaned, "f")
|
|
207
|
+
else:
|
|
208
|
+
text = repr(cleaned)
|
|
209
|
+
for fmt in options.formats:
|
|
210
|
+
parsed = _one_format(text, fmt)
|
|
211
|
+
if parsed is not None:
|
|
212
|
+
return parsed
|
|
213
|
+
raise StepFailed(f"matches none of the formats {list(options.formats)}")
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
# --- zones ------------------------------------------------------------------------------------
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def localize(naive: dt.datetime, options: TemporalCast) -> dt.datetime:
|
|
220
|
+
"""Place a naive wall time in ``options.tz``, applying the DST policies."""
|
|
221
|
+
zone = ZoneInfo(options.tz)
|
|
222
|
+
early, late = naive.replace(tzinfo=zone, fold=0), naive.replace(tzinfo=zone, fold=1)
|
|
223
|
+
exists = early.astimezone(dt.UTC).astimezone(zone).replace(tzinfo=None) == naive
|
|
224
|
+
if not exists:
|
|
225
|
+
if options.nonexistent == "error":
|
|
226
|
+
raise StepFailed(f"{naive} does not exist in {options.tz} (a DST gap)")
|
|
227
|
+
return early # converts to the instant after the gap
|
|
228
|
+
if early.utcoffset() != late.utcoffset():
|
|
229
|
+
if options.ambiguous == "error":
|
|
230
|
+
raise StepFailed(f"{naive} happens twice in {options.tz} (DST ends)")
|
|
231
|
+
return early if options.ambiguous == "earliest" else late
|
|
232
|
+
return early
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _precision(value: dt.datetime | dt.time, precision: str) -> Any: # noqa: ANN401
|
|
236
|
+
if precision == "s":
|
|
237
|
+
return value.replace(microsecond=0)
|
|
238
|
+
if precision == "ms":
|
|
239
|
+
return value.replace(microsecond=value.microsecond // 1000 * 1000)
|
|
240
|
+
return value
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _check_year(day: dt.date, options: TemporalCast) -> None:
|
|
244
|
+
if options.min_year is not None and day.year < options.min_year:
|
|
245
|
+
raise StepFailed(f"year {day.year} is before min_year {options.min_year}")
|
|
246
|
+
if options.max_year is not None and day.year > options.max_year:
|
|
247
|
+
raise StepFailed(f"year {day.year} is after max_year {options.max_year}")
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def cast_temporal(value: object, args: CastArgs, _ctx: Context) -> object:
|
|
251
|
+
"""Cast to timestamptz, timestamp, date or time."""
|
|
252
|
+
options: TemporalCast = args.options
|
|
253
|
+
parsed = parse_temporal(value, options)
|
|
254
|
+
if parsed is None:
|
|
255
|
+
return None
|
|
256
|
+
kind = args.target.kind
|
|
257
|
+
if isinstance(parsed, dt.time):
|
|
258
|
+
if kind != "time":
|
|
259
|
+
raise StepFailed(f"a time of day is not a {kind}")
|
|
260
|
+
return _precision(parsed.replace(tzinfo=None), options.output_precision)
|
|
261
|
+
if not isinstance(parsed, dt.datetime): # a date object
|
|
262
|
+
parsed = dt.datetime.combine(parsed, dt.time())
|
|
263
|
+
if kind == "time":
|
|
264
|
+
return _precision(parsed.timetz().replace(tzinfo=None), options.output_precision)
|
|
265
|
+
if kind == "timestamptz":
|
|
266
|
+
aware = parsed if parsed.tzinfo else localize(parsed, options)
|
|
267
|
+
result = aware.astimezone(dt.UTC)
|
|
268
|
+
else: # timestamp and date: the wall time in tz
|
|
269
|
+
result = (
|
|
270
|
+
parsed.astimezone(ZoneInfo(options.tz)).replace(tzinfo=None)
|
|
271
|
+
if parsed.tzinfo
|
|
272
|
+
else parsed
|
|
273
|
+
)
|
|
274
|
+
_check_year(result.date(), options)
|
|
275
|
+
if kind == "date":
|
|
276
|
+
return result.date()
|
|
277
|
+
return _precision(result, options.output_precision)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
# --- builtins after the cast -------------------------------------------------------------------
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
@dataclass(frozen=True)
|
|
284
|
+
class ZoneKwargs:
|
|
285
|
+
"""A time zone."""
|
|
286
|
+
|
|
287
|
+
tz: str = documented(
|
|
288
|
+
"IANA zone, e.g. America/New_York.", default="UTC", metadata={"check": _zone_problem}
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
@dataclass(frozen=True)
|
|
293
|
+
class OptionalZoneKwargs:
|
|
294
|
+
"""An optional time zone (default: the value's own, UTC for timestamptz)."""
|
|
295
|
+
|
|
296
|
+
tz: str | None = documented("IANA zone.", default=None, metadata={"check": _zone_problem})
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
@dataclass(frozen=True)
|
|
300
|
+
class TruncateKwargs:
|
|
301
|
+
"""Truncate to a unit."""
|
|
302
|
+
|
|
303
|
+
unit: Literal["year", "month", "day", "hour", "minute", "second"] = "day"
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _truncate_datetime(value: dt.datetime, unit: str) -> dt.datetime:
|
|
307
|
+
if unit == "second":
|
|
308
|
+
return value.replace(microsecond=0)
|
|
309
|
+
if unit == "minute":
|
|
310
|
+
return value.replace(second=0, microsecond=0)
|
|
311
|
+
if unit == "hour":
|
|
312
|
+
return value.replace(minute=0, second=0, microsecond=0)
|
|
313
|
+
day = _truncate_date(value.date(), unit)
|
|
314
|
+
return dt.datetime.combine(day, dt.time(), value.tzinfo)
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _truncate_date(value: dt.date, unit: str) -> dt.date:
|
|
318
|
+
if unit == "year":
|
|
319
|
+
return value.replace(month=1, day=1)
|
|
320
|
+
if unit == "month":
|
|
321
|
+
return value.replace(day=1)
|
|
322
|
+
return value
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _truncate(value: object, k: TruncateKwargs, _ctx: Context) -> object:
|
|
326
|
+
if isinstance(value, dt.datetime):
|
|
327
|
+
return _truncate_datetime(value, k.unit)
|
|
328
|
+
if isinstance(value, dt.date):
|
|
329
|
+
return _truncate_date(value, k.unit)
|
|
330
|
+
raise StepFailed(f"truncate needs a date or timestamp, got {type(value).__name__}")
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _assume_tz(value: object, k: ZoneKwargs, _ctx: Context) -> object:
|
|
334
|
+
options = TemporalCast(tz=k.tz)
|
|
335
|
+
if not isinstance(value, dt.datetime):
|
|
336
|
+
raise StepFailed("assume_tz needs a timestamp")
|
|
337
|
+
return localize(value, options).astimezone(dt.UTC)
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _to_local(value: object, k: ZoneKwargs, _ctx: Context) -> object:
|
|
341
|
+
if not isinstance(value, dt.datetime):
|
|
342
|
+
raise StepFailed("to_local needs a timestamptz")
|
|
343
|
+
return value.astimezone(ZoneInfo(k.tz)).replace(tzinfo=None)
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def _date_from_timestamp(value: object, k: OptionalZoneKwargs, _ctx: Context) -> object:
|
|
347
|
+
if not isinstance(value, dt.datetime):
|
|
348
|
+
raise StepFailed("date_from_timestamp needs a timestamp")
|
|
349
|
+
if value.tzinfo is not None and k.tz is not None:
|
|
350
|
+
value = value.astimezone(ZoneInfo(k.tz))
|
|
351
|
+
return value.date()
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _stage(kind: Kind) -> Callable[[CType | None, object], CType]:
|
|
355
|
+
"""A produces() callback giving a fixed type."""
|
|
356
|
+
return lambda _stage, _k: CType(kind)
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def register(registry: Registry) -> None:
|
|
360
|
+
"""Add the temporal casts and builtins."""
|
|
361
|
+
registry.register_cast(
|
|
362
|
+
TEMPORAL,
|
|
363
|
+
Transform(
|
|
364
|
+
"cast",
|
|
365
|
+
cast_temporal,
|
|
366
|
+
kwargs=TemporalCast,
|
|
367
|
+
defaults=_temporal_defaults,
|
|
368
|
+
accepts=frozenset({RAW, "string", *TEMPORAL}),
|
|
369
|
+
),
|
|
370
|
+
)
|
|
371
|
+
registry.register(Transform("to_utc", lambda v, _k, _c: v, accepts=frozenset({"timestamptz"})))
|
|
372
|
+
registry.register(
|
|
373
|
+
Transform(
|
|
374
|
+
"assume_tz",
|
|
375
|
+
_assume_tz,
|
|
376
|
+
kwargs=ZoneKwargs,
|
|
377
|
+
positional="tz",
|
|
378
|
+
accepts=frozenset({"timestamp"}),
|
|
379
|
+
produces=_stage("timestamptz"),
|
|
380
|
+
)
|
|
381
|
+
)
|
|
382
|
+
registry.register(
|
|
383
|
+
Transform(
|
|
384
|
+
"to_local",
|
|
385
|
+
_to_local,
|
|
386
|
+
kwargs=ZoneKwargs,
|
|
387
|
+
positional="tz",
|
|
388
|
+
accepts=frozenset({"timestamptz"}),
|
|
389
|
+
produces=_stage("timestamp"),
|
|
390
|
+
)
|
|
391
|
+
)
|
|
392
|
+
registry.register(
|
|
393
|
+
Transform(
|
|
394
|
+
"truncate",
|
|
395
|
+
_truncate,
|
|
396
|
+
kwargs=TruncateKwargs,
|
|
397
|
+
positional="unit",
|
|
398
|
+
accepts=frozenset({"date", "timestamp", "timestamptz"}),
|
|
399
|
+
)
|
|
400
|
+
)
|
|
401
|
+
registry.register(
|
|
402
|
+
Transform(
|
|
403
|
+
"date_from_timestamp",
|
|
404
|
+
_date_from_timestamp,
|
|
405
|
+
kwargs=OptionalZoneKwargs,
|
|
406
|
+
positional="tz",
|
|
407
|
+
accepts=frozenset({"timestamp", "timestamptz"}),
|
|
408
|
+
produces=_stage("date"),
|
|
409
|
+
)
|
|
410
|
+
)
|