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,297 @@
|
|
|
1
|
+
"""Transform chains, steps and macros (detailed design §3.4).
|
|
2
|
+
|
|
3
|
+
A chain is one step or a list of steps. In mapping form, the **first key other than**
|
|
4
|
+
``when`` names the step; its value is the step's argument and the remaining keys are keyword
|
|
5
|
+
arguments::
|
|
6
|
+
|
|
7
|
+
trim -> CallStep("trim")
|
|
8
|
+
{strip_chars: "$, "} -> CallStep("strip_chars", arg="$, ")
|
|
9
|
+
{cast: decimal, rounding: half_even} -> CallStep("cast", arg="decimal", kwargs={rounding})
|
|
10
|
+
{hash: {}, when: "country == 'DE'"} -> CallStep("hash", arg={}, when=...)
|
|
11
|
+
{expr: "value.strip()"} -> ExprStep("value.strip()")
|
|
12
|
+
{case: [{when: .., then: ..}, {else: ..}]} -> CaseStep(...)
|
|
13
|
+
|
|
14
|
+
Whether a name is a builtin, a macro or a UDF, and whether its arguments fit, is checked when
|
|
15
|
+
the plan is compiled against the registries.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import re
|
|
21
|
+
from collections.abc import Mapping
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
from types import MappingProxyType
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
from map_conform.spec._struct import INVALID, Issues, child, dump, freeze, freeze_mapping, thaw
|
|
27
|
+
|
|
28
|
+
_STEP_NAME = r"^[A-Za-z_][A-Za-z0-9_]*$"
|
|
29
|
+
_RESERVED = frozenset({"when", "expr", "case"})
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _empty() -> Mapping[str, Any]:
|
|
33
|
+
return MappingProxyType({})
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _parse_when(data: Mapping[str, object], path: str, issues: Issues) -> str | None:
|
|
37
|
+
when = data.get("when")
|
|
38
|
+
if when is None and "when" in data:
|
|
39
|
+
issues.add(child(path, "when"), "expected an expression string, got null")
|
|
40
|
+
if when is not None and not isinstance(when, str):
|
|
41
|
+
issues.add(child(path, "when"), "expected an expression string")
|
|
42
|
+
return None
|
|
43
|
+
return when
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class CallStep:
|
|
48
|
+
"""A builtin, macro or UDF applied with an argument and keyword arguments."""
|
|
49
|
+
|
|
50
|
+
name: str
|
|
51
|
+
arg: Any = None
|
|
52
|
+
kwargs: Mapping[str, Any] = field(default_factory=_empty)
|
|
53
|
+
when: str | None = None
|
|
54
|
+
|
|
55
|
+
def spec_dump(self) -> object:
|
|
56
|
+
"""A bare name when there is nothing else, otherwise ``{name: arg, **kwargs}``."""
|
|
57
|
+
if self.arg is None and not self.kwargs and self.when is None:
|
|
58
|
+
return self.name
|
|
59
|
+
out: dict[str, object] = {self.name: thaw(self.arg)}
|
|
60
|
+
out.update({k: thaw(v) for k, v in self.kwargs.items()})
|
|
61
|
+
if self.when is not None:
|
|
62
|
+
out["when"] = self.when
|
|
63
|
+
return out
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True)
|
|
67
|
+
class ExprStep:
|
|
68
|
+
"""A step whose result is an expression over ``value`` and the row."""
|
|
69
|
+
|
|
70
|
+
expr: str
|
|
71
|
+
when: str | None = None
|
|
72
|
+
|
|
73
|
+
def spec_dump(self) -> object:
|
|
74
|
+
"""``{expr: ...}``."""
|
|
75
|
+
out: dict[str, object] = {"expr": self.expr}
|
|
76
|
+
if self.when is not None:
|
|
77
|
+
out["when"] = self.when
|
|
78
|
+
return out
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass(frozen=True)
|
|
82
|
+
class CaseBranch:
|
|
83
|
+
"""``{when: <expr>, then: <chain>}``."""
|
|
84
|
+
|
|
85
|
+
when: str
|
|
86
|
+
then: Chain
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@dataclass(frozen=True)
|
|
90
|
+
class CaseStep:
|
|
91
|
+
"""Conditional chains: the first branch whose ``when`` is truthy runs, else ``otherwise``."""
|
|
92
|
+
|
|
93
|
+
branches: tuple[CaseBranch, ...]
|
|
94
|
+
otherwise: Chain | None = None
|
|
95
|
+
when: str | None = None
|
|
96
|
+
|
|
97
|
+
def spec_dump(self) -> object:
|
|
98
|
+
"""``{case: [{when, then}, ..., {else}]}``."""
|
|
99
|
+
items: list[object] = [{"when": b.when, "then": dump(b.then)} for b in self.branches]
|
|
100
|
+
if self.otherwise is not None:
|
|
101
|
+
items.append({"else": dump(self.otherwise)})
|
|
102
|
+
out: dict[str, object] = {"case": items}
|
|
103
|
+
if self.when is not None:
|
|
104
|
+
out["when"] = self.when
|
|
105
|
+
return out
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
Step = CallStep | ExprStep | CaseStep
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _parse_step(data: object, path: str, issues: Issues) -> Step | None: # noqa: PLR0911 -- one early return per malformed shape
|
|
112
|
+
if isinstance(data, str):
|
|
113
|
+
if not re.match(_STEP_NAME, data) or data in _RESERVED:
|
|
114
|
+
issues.add(path, f"{data!r} is not a step name")
|
|
115
|
+
return None
|
|
116
|
+
return CallStep(data)
|
|
117
|
+
if not isinstance(data, dict) or not data:
|
|
118
|
+
issues.add(path, "a step is a name or a non-empty mapping")
|
|
119
|
+
return None
|
|
120
|
+
when = _parse_when(data, path, issues)
|
|
121
|
+
keys = [k for k in data if k != "when"]
|
|
122
|
+
if not keys:
|
|
123
|
+
issues.add(path, "a step needs a name besides 'when'")
|
|
124
|
+
return None
|
|
125
|
+
name, rest = keys[0], keys[1:]
|
|
126
|
+
if not isinstance(name, str) or not re.match(_STEP_NAME, name):
|
|
127
|
+
issues.add(path, f"{name!r} is not a step name")
|
|
128
|
+
return None
|
|
129
|
+
if name == "expr":
|
|
130
|
+
return _parse_expr_step(data, rest, when, path, issues)
|
|
131
|
+
if name == "case":
|
|
132
|
+
return _parse_case(data, rest, when, path, issues)
|
|
133
|
+
return CallStep(
|
|
134
|
+
name,
|
|
135
|
+
arg=freeze(data[name]),
|
|
136
|
+
kwargs=MappingProxyType({k: freeze(data[k]) for k in rest}),
|
|
137
|
+
when=when,
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _parse_expr_step(
|
|
142
|
+
data: Mapping[str, object], rest: list[str], when: str | None, path: str, issues: Issues
|
|
143
|
+
) -> ExprStep | None:
|
|
144
|
+
expr = data["expr"]
|
|
145
|
+
for key in rest:
|
|
146
|
+
issues.add(child(path, key), "unknown key; an expr step allows only 'when'")
|
|
147
|
+
if not isinstance(expr, str):
|
|
148
|
+
issues.add(child(path, "expr"), "expected an expression string")
|
|
149
|
+
return None
|
|
150
|
+
return None if rest else ExprStep(expr, when)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _parse_case(
|
|
154
|
+
data: Mapping[str, object], rest: list[str], when: str | None, path: str, issues: Issues
|
|
155
|
+
) -> CaseStep | None:
|
|
156
|
+
for key in rest:
|
|
157
|
+
issues.add(child(path, key), "unknown key; a case step allows only 'when'")
|
|
158
|
+
items = data["case"]
|
|
159
|
+
case_path = child(path, "case")
|
|
160
|
+
if not isinstance(items, list) or not items:
|
|
161
|
+
issues.add(case_path, "expected a non-empty list of {when, then} and an optional {else}")
|
|
162
|
+
return None
|
|
163
|
+
branches: list[CaseBranch] = []
|
|
164
|
+
otherwise: Chain | None = None
|
|
165
|
+
ok = not rest
|
|
166
|
+
for i, item in enumerate(items):
|
|
167
|
+
item_path = child(case_path, i)
|
|
168
|
+
if isinstance(item, dict) and set(item) == {"else"}:
|
|
169
|
+
if i != len(items) - 1:
|
|
170
|
+
issues.add(item_path, "'else' must be the last branch")
|
|
171
|
+
ok = False
|
|
172
|
+
parsed = Chain.spec_parse(item["else"], child(item_path, "else"), issues)
|
|
173
|
+
ok = ok and parsed is not INVALID
|
|
174
|
+
otherwise = parsed if isinstance(parsed, Chain) else None
|
|
175
|
+
continue
|
|
176
|
+
if not isinstance(item, dict) or set(item) != {"when", "then"}:
|
|
177
|
+
issues.add(item_path, "a branch is {when: <expr>, then: <chain>} or {else: <chain>}")
|
|
178
|
+
ok = False
|
|
179
|
+
continue
|
|
180
|
+
if not isinstance(item["when"], str):
|
|
181
|
+
issues.add(child(item_path, "when"), "expected an expression string")
|
|
182
|
+
ok = False
|
|
183
|
+
continue
|
|
184
|
+
then = Chain.spec_parse(item["then"], child(item_path, "then"), issues)
|
|
185
|
+
if isinstance(then, Chain):
|
|
186
|
+
branches.append(CaseBranch(item["when"], then))
|
|
187
|
+
else:
|
|
188
|
+
ok = False
|
|
189
|
+
if not branches and ok:
|
|
190
|
+
issues.add(case_path, "a case needs at least one {when, then} branch")
|
|
191
|
+
ok = False
|
|
192
|
+
return CaseStep(tuple(branches), otherwise, when) if ok else None
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
@dataclass(frozen=True)
|
|
196
|
+
class Chain:
|
|
197
|
+
"""An ordered list of steps. The implicit cast to the column type is added at compile time."""
|
|
198
|
+
|
|
199
|
+
steps: tuple[Step, ...]
|
|
200
|
+
|
|
201
|
+
@classmethod
|
|
202
|
+
def spec_parse(cls, data: object, path: str, issues: Issues) -> Chain | Any: # noqa: ANN401
|
|
203
|
+
"""Parse one step or a list of steps."""
|
|
204
|
+
raw = data if isinstance(data, list) else [data]
|
|
205
|
+
if not raw:
|
|
206
|
+
issues.add(path, "a chain needs at least one step")
|
|
207
|
+
return INVALID
|
|
208
|
+
many = isinstance(data, list)
|
|
209
|
+
steps = [
|
|
210
|
+
_parse_step(s, child(path, i) if many else path, issues) for i, s in enumerate(raw)
|
|
211
|
+
]
|
|
212
|
+
if any(s is None for s in steps):
|
|
213
|
+
return INVALID
|
|
214
|
+
return cls(tuple(s for s in steps if s is not None))
|
|
215
|
+
|
|
216
|
+
def spec_dump(self) -> object:
|
|
217
|
+
"""A single step stays a single step; otherwise a list."""
|
|
218
|
+
dumped = [dump(s) for s in self.steps]
|
|
219
|
+
return dumped[0] if len(dumped) == 1 else dumped
|
|
220
|
+
|
|
221
|
+
@classmethod
|
|
222
|
+
def spec_schema(cls, defs: dict[str, Any]) -> dict[str, Any]:
|
|
223
|
+
"""A step or a list of steps."""
|
|
224
|
+
if "Step" not in defs:
|
|
225
|
+
defs["Step"] = {
|
|
226
|
+
"description": (
|
|
227
|
+
"A step name, or a mapping whose first key (other than 'when') names the "
|
|
228
|
+
"step: its value is the argument and the other keys are keyword arguments. "
|
|
229
|
+
"{expr: ...} and {case: [...]} are built in."
|
|
230
|
+
),
|
|
231
|
+
"anyOf": [
|
|
232
|
+
{"type": "string", "pattern": _STEP_NAME},
|
|
233
|
+
{"type": "object", "minProperties": 1},
|
|
234
|
+
],
|
|
235
|
+
}
|
|
236
|
+
step = {"$ref": "#/$defs/Step"}
|
|
237
|
+
return {"anyOf": [step, {"type": "array", "items": step, "minItems": 1}]}
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
@dataclass(frozen=True)
|
|
241
|
+
class Macro:
|
|
242
|
+
"""A named, parameterised chain. ``${param}`` in its steps is filled at expansion."""
|
|
243
|
+
|
|
244
|
+
steps: Chain
|
|
245
|
+
params: Mapping[str, Any] = field(default_factory=_empty)
|
|
246
|
+
doc: str | None = None
|
|
247
|
+
|
|
248
|
+
@classmethod
|
|
249
|
+
def spec_parse(cls, data: object, path: str, issues: Issues) -> Macro | Any: # noqa: ANN401
|
|
250
|
+
"""Either a chain, or ``{steps, params?, doc?}``."""
|
|
251
|
+
if isinstance(data, dict) and "steps" in data and set(data) <= {"steps", "params", "doc"}:
|
|
252
|
+
steps = Chain.spec_parse(data["steps"], child(path, "steps"), issues)
|
|
253
|
+
params = data.get("params", {})
|
|
254
|
+
doc = data.get("doc")
|
|
255
|
+
ok = isinstance(steps, Chain)
|
|
256
|
+
if not isinstance(params, dict) or not all(isinstance(k, str) for k in params):
|
|
257
|
+
issues.add(child(path, "params"), "expected a mapping of parameter defaults")
|
|
258
|
+
ok = False
|
|
259
|
+
if doc is not None and not isinstance(doc, str):
|
|
260
|
+
issues.add(child(path, "doc"), "expected a string")
|
|
261
|
+
ok = False
|
|
262
|
+
if not ok:
|
|
263
|
+
return INVALID
|
|
264
|
+
return cls(steps, freeze_mapping(params), doc)
|
|
265
|
+
steps = Chain.spec_parse(data, path, issues)
|
|
266
|
+
return cls(steps) if isinstance(steps, Chain) else INVALID
|
|
267
|
+
|
|
268
|
+
def spec_dump(self) -> object:
|
|
269
|
+
"""The short chain form when there are no params or doc."""
|
|
270
|
+
if not self.params and self.doc is None:
|
|
271
|
+
return dump(self.steps)
|
|
272
|
+
out: dict[str, object] = {"steps": dump(self.steps)}
|
|
273
|
+
if self.params:
|
|
274
|
+
out["params"] = thaw(self.params)
|
|
275
|
+
if self.doc is not None:
|
|
276
|
+
out["doc"] = self.doc
|
|
277
|
+
return out
|
|
278
|
+
|
|
279
|
+
@classmethod
|
|
280
|
+
def spec_schema(cls, defs: dict[str, Any]) -> dict[str, Any]:
|
|
281
|
+
"""A chain, or an object with steps, params and doc."""
|
|
282
|
+
chain = Chain.spec_schema(defs)
|
|
283
|
+
return {
|
|
284
|
+
"anyOf": [
|
|
285
|
+
chain,
|
|
286
|
+
{
|
|
287
|
+
"type": "object",
|
|
288
|
+
"additionalProperties": False,
|
|
289
|
+
"required": ["steps"],
|
|
290
|
+
"properties": {
|
|
291
|
+
"steps": chain,
|
|
292
|
+
"params": {"type": "object"},
|
|
293
|
+
"doc": {"type": "string"},
|
|
294
|
+
},
|
|
295
|
+
},
|
|
296
|
+
]
|
|
297
|
+
}
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"""Translate Singer SDK stream-map settings into a native spec (detailed design §15).
|
|
2
|
+
|
|
3
|
+
map-conform accepts the settings of meltano-map-transformer unchanged: ``stream_maps``,
|
|
4
|
+
``stream_map_config``, ``faker_config`` and ``flattening_*``. They are translated once, at
|
|
5
|
+
start-up, into a raw spec merged *under* the native one, so the native spec wins column by
|
|
6
|
+
column. Every SDK feature has a native equivalent:
|
|
7
|
+
|
|
8
|
+
============================================== =============================================
|
|
9
|
+
SDK native
|
|
10
|
+
============================================== =============================================
|
|
11
|
+
``stream_maps.<stream or glob>`` ``streams.<stream or glob>``
|
|
12
|
+
``<stream>: null`` / ``"__NULL__"`` ``drop: true``
|
|
13
|
+
``__else__: null`` (top level) ``else: drop``
|
|
14
|
+
``__alias__`` ``alias`` (a literal, or ``{expr: ...}``)
|
|
15
|
+
``__source__`` ``source`` on a new output-stream key
|
|
16
|
+
``__filter__`` ``filter``
|
|
17
|
+
``__key_properties__`` ``key_properties`` (null: none)
|
|
18
|
+
``__else__: null`` (stream level) ``undeclared: drop`` (key properties kept)
|
|
19
|
+
``<property>: null`` / ``"__NULL__"`` ``{drop: true}``
|
|
20
|
+
``<property>: "<expr>"`` ``{expr: ..., infer_type: sdk}``
|
|
21
|
+
``faker_config`` ``defaults.faker``
|
|
22
|
+
``flattening_enabled`` and friends ``defaults.nested: flatten`` and ``flatten``
|
|
23
|
+
``add_record_metadata`` ``defaults.add_record_metadata``
|
|
24
|
+
============================================== =============================================
|
|
25
|
+
|
|
26
|
+
Expressions are rewritten so that bare record names read ``record['...']``
|
|
27
|
+
(:func:`~map_conform.expr.sdk.rewrite_sdk_expression`). An alias is an expression when it
|
|
28
|
+
parses and uses no name but ``__stream_name__``; otherwise it is the literal name, as in the
|
|
29
|
+
SDK (``aliased.stream`` is a name, ``'aliased_' + __stream_name__`` an expression).
|
|
30
|
+
|
|
31
|
+
With ``stream_maps`` set, these **compatibility defaults** apply unless the spec sets them,
|
|
32
|
+
so that a project moving from meltano-map-transformer keeps its output: column names follow
|
|
33
|
+
the SDK's ``conform_name`` (what an SDK SQL target creates), stream names are kept as they
|
|
34
|
+
are, nested values keep their shape, and text is not trimmed or nulled by tokens. The
|
|
35
|
+
``add_record_metadata`` setting alone decides the ``_sdc_*`` columns.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
from __future__ import annotations
|
|
39
|
+
|
|
40
|
+
import ast
|
|
41
|
+
import re
|
|
42
|
+
from collections.abc import Mapping
|
|
43
|
+
from typing import Any
|
|
44
|
+
|
|
45
|
+
from map_conform.expr.sdk import rewrite_sdk_expression
|
|
46
|
+
from map_conform.spec._struct import Issues, child
|
|
47
|
+
from map_conform.types.canonical import CType
|
|
48
|
+
|
|
49
|
+
SDK_SETTINGS = (
|
|
50
|
+
"stream_maps",
|
|
51
|
+
"stream_map_config",
|
|
52
|
+
"faker_config",
|
|
53
|
+
"flattening_enabled",
|
|
54
|
+
"flattening_max_depth",
|
|
55
|
+
"flattening_separator",
|
|
56
|
+
"flattening_max_key_length",
|
|
57
|
+
"add_record_metadata",
|
|
58
|
+
)
|
|
59
|
+
"""The plugin settings meltano-map-transformer takes, accepted here unchanged."""
|
|
60
|
+
|
|
61
|
+
NULL_STRING = "__NULL__"
|
|
62
|
+
ELSE = "__else__"
|
|
63
|
+
SPECIAL = frozenset({"__alias__", "__source__", "__filter__", "__key_properties__", ELSE})
|
|
64
|
+
|
|
65
|
+
COMPAT_DEFAULTS: Mapping[str, Any] = {
|
|
66
|
+
"naming": {"preset": "sdk"},
|
|
67
|
+
"stream": {"name": "preserve"},
|
|
68
|
+
"nested": "keep",
|
|
69
|
+
"values": {"trim": False, "null_tokens": []},
|
|
70
|
+
}
|
|
71
|
+
"""Defaults that make translated stream maps give the SDK mapper's output."""
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _is_null(value: object) -> bool:
|
|
75
|
+
return value is None or value == NULL_STRING
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _alias(text: object, path: str, issues: Issues) -> object:
|
|
79
|
+
"""A literal alias, or ``{expr: ...}`` when the SDK would evaluate it."""
|
|
80
|
+
if not isinstance(text, str):
|
|
81
|
+
issues.add(path, "an alias is a string")
|
|
82
|
+
return None
|
|
83
|
+
try:
|
|
84
|
+
tree = ast.parse(text.strip(), mode="eval")
|
|
85
|
+
except SyntaxError:
|
|
86
|
+
return text
|
|
87
|
+
names = {n.id for n in ast.walk(tree) if isinstance(n, ast.Name)}
|
|
88
|
+
if names - {"__stream_name__"}:
|
|
89
|
+
return text # the SDK falls back to the literal on an unknown name
|
|
90
|
+
return {"expr": text}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _special(name: str, value: object, where: str, issues: Issues) -> dict[str, Any]: # noqa: PLR0911 -- one per option
|
|
94
|
+
"""The native keys for one of the SDK's ``__option__`` keys of a stream map."""
|
|
95
|
+
if name == "__source__":
|
|
96
|
+
return {"source": value}
|
|
97
|
+
if name == "__alias__":
|
|
98
|
+
return {"alias": _alias(value, where, issues)}
|
|
99
|
+
if name == "__filter__":
|
|
100
|
+
if not isinstance(value, str):
|
|
101
|
+
issues.add(where, "a filter is an expression string")
|
|
102
|
+
return {}
|
|
103
|
+
return {"filter": rewrite_sdk_expression(value)}
|
|
104
|
+
if name == "__key_properties__":
|
|
105
|
+
if value is not None and not isinstance(value, (list, tuple)):
|
|
106
|
+
issues.add(where, "key properties are a list of names, or null for none")
|
|
107
|
+
return {}
|
|
108
|
+
return {"key_properties": list(value or [])}
|
|
109
|
+
if not _is_null(value): # __else__
|
|
110
|
+
issues.add(where, f"only {ELSE}: null is supported, as in the SDK")
|
|
111
|
+
return {}
|
|
112
|
+
return {"undeclared": "drop"}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _stream(key: str, rules: Mapping[str, Any], path: str, issues: Issues) -> dict[str, Any]:
|
|
116
|
+
out: dict[str, Any] = {}
|
|
117
|
+
columns: dict[str, Any] = {}
|
|
118
|
+
for name, value in rules.items():
|
|
119
|
+
where = child(path, name)
|
|
120
|
+
if name in SPECIAL:
|
|
121
|
+
out.update(_special(name, value, where, issues))
|
|
122
|
+
elif _is_null(value):
|
|
123
|
+
columns[name] = {"drop": True}
|
|
124
|
+
elif isinstance(value, str):
|
|
125
|
+
columns[name] = {"expr": rewrite_sdk_expression(value), "infer_type": "sdk"}
|
|
126
|
+
else:
|
|
127
|
+
issues.add(where, f"expected an expression string or null for {key}.{name}")
|
|
128
|
+
if columns:
|
|
129
|
+
out["columns"] = columns
|
|
130
|
+
return out
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _streams(stream_maps: Mapping[str, Any], issues: Issues) -> dict[str, Any]:
|
|
134
|
+
"""The ``streams`` (and ``else``) of the translated spec."""
|
|
135
|
+
out: dict[str, Any] = {"streams": {}}
|
|
136
|
+
for key, rules in stream_maps.items():
|
|
137
|
+
path = child("stream_maps", key)
|
|
138
|
+
if key == ELSE:
|
|
139
|
+
if _is_null(rules):
|
|
140
|
+
out["else"] = "drop"
|
|
141
|
+
else:
|
|
142
|
+
issues.add(path, f"only {ELSE}: null is supported, as in the SDK")
|
|
143
|
+
elif key.startswith("__"):
|
|
144
|
+
issues.add(path, f"option {key!r} is not expected here")
|
|
145
|
+
elif _is_null(rules):
|
|
146
|
+
out["streams"][key] = {"drop": True}
|
|
147
|
+
elif isinstance(rules, Mapping):
|
|
148
|
+
out["streams"][key] = _stream(key, rules, path, issues)
|
|
149
|
+
else:
|
|
150
|
+
issues.add(path, "a stream map is a mapping, null or __NULL__")
|
|
151
|
+
return out
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _sdk_defaults(settings: Mapping[str, Any]) -> dict[str, Any]:
|
|
155
|
+
"""``defaults`` from faker_config and the flattening settings."""
|
|
156
|
+
defaults: dict[str, Any] = {}
|
|
157
|
+
if settings.get("add_record_metadata") is not None:
|
|
158
|
+
defaults["add_record_metadata"] = settings["add_record_metadata"]
|
|
159
|
+
if faker := settings.get("faker_config"):
|
|
160
|
+
defaults["faker"] = {k: faker[k] for k in ("seed", "locale") if k in faker}
|
|
161
|
+
if settings.get("flattening_enabled"):
|
|
162
|
+
defaults["nested"] = "flatten"
|
|
163
|
+
flatten = {
|
|
164
|
+
option: settings[f"flattening_{option}"]
|
|
165
|
+
for option in ("separator", "max_depth", "max_key_length")
|
|
166
|
+
if settings.get(f"flattening_{option}") is not None
|
|
167
|
+
}
|
|
168
|
+
if flatten:
|
|
169
|
+
defaults["flatten"] = flatten
|
|
170
|
+
return defaults
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def translate(settings: Mapping[str, Any], issues: Issues) -> dict[str, Any] | None:
|
|
174
|
+
"""The raw spec for the SDK settings in ``settings``, or None when there are none.
|
|
175
|
+
|
|
176
|
+
Problems are recorded in ``issues`` with their setting paths.
|
|
177
|
+
"""
|
|
178
|
+
defaults = _sdk_defaults(settings)
|
|
179
|
+
stream_maps = settings.get("stream_maps")
|
|
180
|
+
if stream_maps is None:
|
|
181
|
+
return {"version": 1, "defaults": defaults} if defaults else None
|
|
182
|
+
compat = {k: dict(v) if isinstance(v, Mapping) else v for k, v in COMPAT_DEFAULTS.items()}
|
|
183
|
+
return {"version": 1, "defaults": {**compat, **defaults}, **_streams(stream_maps, issues)}
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
# --- SDK type inference (WBS 12.2) --------------------------------------------------------------
|
|
187
|
+
|
|
188
|
+
_PASSTHROUGH = re.compile(r"""^record\[(['"])(?P<name>.+)\1\]$""")
|
|
189
|
+
_PREFIXES: tuple[tuple[tuple[str, ...], CType], ...] = (
|
|
190
|
+
(("float(",), CType("float64")),
|
|
191
|
+
(("int(",), CType("int64")),
|
|
192
|
+
(("str(",), CType("string")),
|
|
193
|
+
(("bool(",), CType("boolean")),
|
|
194
|
+
(("json.dumps(",), CType("string")),
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def prefix_type(expr: str) -> CType | None:
|
|
199
|
+
"""The type the SDK decides from the expression's text alone, or None."""
|
|
200
|
+
text = expr.strip()
|
|
201
|
+
for prefixes, ctype in _PREFIXES:
|
|
202
|
+
if text.startswith(prefixes):
|
|
203
|
+
return ctype
|
|
204
|
+
if text.startswith(("datetime.date.", "datetime.date(")) or text.endswith(".date()"):
|
|
205
|
+
return CType("date")
|
|
206
|
+
if text.startswith(("datetime.datetime.", "datetime.datetime(")):
|
|
207
|
+
return CType("timestamptz")
|
|
208
|
+
if len(text) > 1 and text[0] == text[-1] == "'":
|
|
209
|
+
return CType("string")
|
|
210
|
+
return None
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def sdk_type(
|
|
214
|
+
expr: str, key: str, properties: Mapping[str, Any], *, undeclared_dropped: bool
|
|
215
|
+
) -> tuple[CType | None, Mapping[str, Any] | None]:
|
|
216
|
+
"""The column type the SDK mapper would declare for ``key: <expr>``.
|
|
217
|
+
|
|
218
|
+
Returns:
|
|
219
|
+
``(ctype, None)`` for a type the expression decides, or ``(None, schema)`` for the
|
|
220
|
+
JSON Schema to take the type from (the record's, an existing property's, or a string).
|
|
221
|
+
"""
|
|
222
|
+
text = expr.strip()
|
|
223
|
+
if text == "record": # the whole record, typed by the tap SCHEMA, as the SDK declares it
|
|
224
|
+
return None, {"type": ["object", "null"], "properties": dict(properties)}
|
|
225
|
+
if (decided := prefix_type(text)) is not None:
|
|
226
|
+
return decided, None
|
|
227
|
+
match = _PASSTHROUGH.match(text)
|
|
228
|
+
passthrough = match["name"] if match else None
|
|
229
|
+
existing = None if undeclared_dropped else properties.get(key)
|
|
230
|
+
existing = existing or (properties.get(passthrough) if passthrough else None)
|
|
231
|
+
if existing:
|
|
232
|
+
return None, existing
|
|
233
|
+
return CType("string"), None
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""The bridge to Zamboni table-config ``columns`` (ADR-0003, WBS 9.2).
|
|
2
|
+
|
|
3
|
+
Zamboni's table-config (version 2) describes physical layout per table; its ``columns``
|
|
4
|
+
block maps a column name to a type string, which Zamboni itself only checks for shape. The
|
|
5
|
+
bridge fills it with map-conform's canonical types and reads it back:
|
|
6
|
+
|
|
7
|
+
- ``spec export SPEC --zamboni TC --catalog C`` compiles each catalog stream's plans and
|
|
8
|
+
writes ``namespaces.<ns>.tables.<output stream>.columns`` as ``{output column: CType}``,
|
|
9
|
+
``_sdc_*`` columns included when they are added. Everything else in the file is kept as
|
|
10
|
+
it was; a missing table entry is created with just its columns.
|
|
11
|
+
- ``spec import --catalog C --zamboni TC`` drafts a spec whose column types come from the
|
|
12
|
+
Zamboni table (matched by output stream and column names), falling back to the catalog.
|
|
13
|
+
``defaults.columns`` applies to every table, under its own.
|
|
14
|
+
|
|
15
|
+
Tables are matched by the conformed output stream name. With one namespace in the file it
|
|
16
|
+
is used; with several, ``--namespace`` says which.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import json
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
import yaml
|
|
26
|
+
|
|
27
|
+
from map_conform.spec._struct import Issue
|
|
28
|
+
from map_conform.spec.errors import SpecError
|
|
29
|
+
|
|
30
|
+
SUPPORTED_VERSION = 2
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _problem(path: str | Path, message: str) -> SpecError:
|
|
34
|
+
return SpecError([Issue("", message)], str(path))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def read_table_config(path: str | Path) -> dict[str, Any]:
|
|
38
|
+
"""Read a Zamboni table-config file (JSON or YAML), version 2.
|
|
39
|
+
|
|
40
|
+
Raises:
|
|
41
|
+
SpecError: if the file cannot be read or is not a version 2 table-config.
|
|
42
|
+
"""
|
|
43
|
+
file = Path(path)
|
|
44
|
+
try:
|
|
45
|
+
text = file.read_text(encoding="utf-8")
|
|
46
|
+
except OSError as exc:
|
|
47
|
+
raise _problem(path, f"cannot read the table-config: {exc.strerror}") from exc
|
|
48
|
+
try:
|
|
49
|
+
document = json.loads(text) if file.suffix.lower() == ".json" else yaml.safe_load(text)
|
|
50
|
+
except (json.JSONDecodeError, yaml.YAMLError) as exc:
|
|
51
|
+
raise _problem(path, f"not a table-config: {exc}") from exc
|
|
52
|
+
if not isinstance(document, dict):
|
|
53
|
+
raise _problem(path, "a table-config is a mapping")
|
|
54
|
+
if document.get("version") != SUPPORTED_VERSION:
|
|
55
|
+
raise _problem(path, f"only Zamboni table-config version 2 is supported, got "
|
|
56
|
+
f"{document.get('version')!r}") # fmt: skip
|
|
57
|
+
return document
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def write_table_config(document: dict[str, Any], path: str | Path) -> None:
|
|
61
|
+
"""Write the table-config back in the file's own format."""
|
|
62
|
+
file = Path(path)
|
|
63
|
+
if file.suffix.lower() == ".json":
|
|
64
|
+
text = json.dumps(document, indent=2, ensure_ascii=False) + "\n"
|
|
65
|
+
else:
|
|
66
|
+
text = yaml.safe_dump(document, sort_keys=False, allow_unicode=True)
|
|
67
|
+
file.write_text(text, encoding="utf-8")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def namespace_of(document: dict[str, Any], namespace: str | None, path: str | Path) -> str:
|
|
71
|
+
"""The namespace to use: the one given, or the file's only one.
|
|
72
|
+
|
|
73
|
+
Raises:
|
|
74
|
+
SpecError: when the namespace is ambiguous.
|
|
75
|
+
"""
|
|
76
|
+
names = list((document.get("namespaces") or {}).keys())
|
|
77
|
+
if namespace is not None:
|
|
78
|
+
return namespace
|
|
79
|
+
if len(names) == 1:
|
|
80
|
+
return names[0]
|
|
81
|
+
choices = ", ".join(names) or "none"
|
|
82
|
+
raise _problem(path, f"choose a namespace with --namespace (the file has: {choices})")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def table_columns(document: dict[str, Any], namespace: str, table: str) -> dict[str, str]:
|
|
86
|
+
"""A table's ``columns``, over ``defaults.columns``."""
|
|
87
|
+
columns = dict((document.get("defaults") or {}).get("columns") or {})
|
|
88
|
+
tables = ((document.get("namespaces") or {}).get(namespace) or {}).get("tables") or {}
|
|
89
|
+
columns.update((tables.get(table) or {}).get("columns") or {})
|
|
90
|
+
return columns
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def set_table_columns(
|
|
94
|
+
document: dict[str, Any], namespace: str, table: str, columns: dict[str, str]
|
|
95
|
+
) -> None:
|
|
96
|
+
"""Replace a table's ``columns``, creating the namespace and table entries if needed."""
|
|
97
|
+
namespaces = document.setdefault("namespaces", {})
|
|
98
|
+
tables = namespaces.setdefault(namespace, {}).setdefault("tables", {})
|
|
99
|
+
tables.setdefault(table, {})["columns"] = columns
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Builtin transforms and their registry."""
|