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,483 @@
|
|
|
1
|
+
"""Strict parsing, dumping and JSON Schema generation for the spec's frozen dataclasses.
|
|
2
|
+
|
|
3
|
+
One set of type hints drives all three, so the model, the parser and the shipped JSON Schema
|
|
4
|
+
cannot drift apart (the Zamboni pattern). Parsing collects every problem with its path rather
|
|
5
|
+
than stopping at the first.
|
|
6
|
+
|
|
7
|
+
Supported annotations: ``str``, ``int``, ``float``, ``bool``, ``None``, ``Any``, ``Literal``,
|
|
8
|
+
unions, ``tuple[T, ...]``, ``Mapping[str, T]``, dataclasses, and classes that implement
|
|
9
|
+
:class:`Custom`.
|
|
10
|
+
|
|
11
|
+
Field metadata keys: ``key`` (the spec spelling, e.g. ``else`` for ``else_``), ``doc``
|
|
12
|
+
(becomes the schema ``description``), ``check`` (``value -> problem | None``) and
|
|
13
|
+
``null_hint`` (the message for an explicit null, where YAML's bare ``null`` is a trap).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import dataclasses
|
|
19
|
+
import functools
|
|
20
|
+
import re
|
|
21
|
+
import sys
|
|
22
|
+
import types
|
|
23
|
+
import typing
|
|
24
|
+
from collections.abc import Mapping
|
|
25
|
+
from dataclasses import dataclass
|
|
26
|
+
from typing import (
|
|
27
|
+
TYPE_CHECKING,
|
|
28
|
+
Any,
|
|
29
|
+
Literal,
|
|
30
|
+
Protocol,
|
|
31
|
+
TypeVar,
|
|
32
|
+
Union,
|
|
33
|
+
get_args,
|
|
34
|
+
get_origin,
|
|
35
|
+
runtime_checkable,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
if sys.version_info >= (3, 12):
|
|
39
|
+
from typing import override
|
|
40
|
+
else:
|
|
41
|
+
from typing_extensions import override
|
|
42
|
+
|
|
43
|
+
if TYPE_CHECKING:
|
|
44
|
+
from _typeshed import DataclassInstance
|
|
45
|
+
|
|
46
|
+
DC = TypeVar("DC", bound="DataclassInstance")
|
|
47
|
+
|
|
48
|
+
_PLAIN_KEY = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class Issue:
|
|
53
|
+
"""One problem found in a spec, at a path such as ``streams["sheets-*"].columns.id``."""
|
|
54
|
+
|
|
55
|
+
path: str
|
|
56
|
+
message: str
|
|
57
|
+
|
|
58
|
+
@override
|
|
59
|
+
def __str__(self) -> str:
|
|
60
|
+
"""``path: message``."""
|
|
61
|
+
return f"{self.path or '<root>'}: {self.message}"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class Issues:
|
|
65
|
+
"""Collects :class:`Issue` objects while a document is parsed."""
|
|
66
|
+
|
|
67
|
+
def __init__(self) -> None:
|
|
68
|
+
"""Start empty."""
|
|
69
|
+
self.items: list[Issue] = []
|
|
70
|
+
|
|
71
|
+
def add(self, path: str, message: str) -> None:
|
|
72
|
+
"""Record a problem at ``path``."""
|
|
73
|
+
self.items.append(Issue(path, message))
|
|
74
|
+
|
|
75
|
+
def __bool__(self) -> bool:
|
|
76
|
+
"""True when any problem was recorded."""
|
|
77
|
+
return bool(self.items)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class Invalid:
|
|
81
|
+
"""The type of :data:`INVALID`: a value that had problems, already recorded."""
|
|
82
|
+
|
|
83
|
+
@override
|
|
84
|
+
def __repr__(self) -> str:
|
|
85
|
+
"""``INVALID``."""
|
|
86
|
+
return "INVALID"
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
INVALID = Invalid()
|
|
90
|
+
"""The one instance of :class:`Invalid`; compare with ``is``."""
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@runtime_checkable
|
|
94
|
+
class Dumpable(Protocol):
|
|
95
|
+
"""A value that knows its own plain-data form."""
|
|
96
|
+
|
|
97
|
+
def spec_dump(self) -> object:
|
|
98
|
+
"""Return the plain data form of this value."""
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class Custom(Protocol):
|
|
102
|
+
"""A type that parses, dumps and describes itself."""
|
|
103
|
+
|
|
104
|
+
@classmethod
|
|
105
|
+
def spec_parse(cls, data: object, path: str, issues: Issues) -> Any: # noqa: ANN401
|
|
106
|
+
"""Parse ``data`` found at ``path``; return the value or ``INVALID``."""
|
|
107
|
+
|
|
108
|
+
def spec_dump(self) -> object:
|
|
109
|
+
"""Return the plain data form of this value."""
|
|
110
|
+
|
|
111
|
+
@classmethod
|
|
112
|
+
def spec_schema(cls, defs: dict[str, Any]) -> dict[str, Any]:
|
|
113
|
+
"""Return the JSON Schema of this type, registering shared parts in ``defs``."""
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def documented(text: str, **kwargs: Any) -> Any: # noqa: ANN401 -- dataclasses.field's own type
|
|
117
|
+
"""A dataclass field with a schema description (and optional ``check`` metadata)."""
|
|
118
|
+
metadata = {"doc": text}
|
|
119
|
+
metadata.update(kwargs.pop("metadata", {}))
|
|
120
|
+
return dataclasses.field(metadata=metadata, **kwargs)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def empty_mapping() -> Mapping[str, Any]:
|
|
124
|
+
"""A read-only empty mapping, for ``default_factory``."""
|
|
125
|
+
return types.MappingProxyType({})
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def positive(value: int) -> str | None:
|
|
129
|
+
"""A ``check``: at least 1."""
|
|
130
|
+
return None if value > 0 else "must be at least 1"
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def non_negative(value: int) -> str | None:
|
|
134
|
+
"""A ``check``: zero or more."""
|
|
135
|
+
return None if value >= 0 else "must not be negative"
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def child(path: str, key: str | int) -> str:
|
|
139
|
+
"""The path of ``key`` inside ``path``: ``a.b``, ``a["odd key"]`` or ``a[3]``."""
|
|
140
|
+
if isinstance(key, int):
|
|
141
|
+
return f"{path}[{key}]"
|
|
142
|
+
if _PLAIN_KEY.match(key):
|
|
143
|
+
return f"{path}.{key}" if path else key
|
|
144
|
+
quoted = key.replace("\\", "\\\\").replace('"', '\\"')
|
|
145
|
+
return f'{path}["{quoted}"]'
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def spec_key(field: dataclasses.Field[Any]) -> str:
|
|
149
|
+
"""The key a dataclass field is written as in a spec."""
|
|
150
|
+
return field.metadata.get("key", field.name)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
@functools.cache
|
|
154
|
+
def _hints(cls: type[DataclassInstance]) -> dict[str, Any]:
|
|
155
|
+
return typing.get_type_hints(cls)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def fields_of(cls: type[DataclassInstance]) -> list[tuple[dataclasses.Field[Any], Any]]:
|
|
159
|
+
"""The dataclass fields of ``cls`` with their resolved annotations."""
|
|
160
|
+
hints = _hints(cls)
|
|
161
|
+
return [(f, hints[f.name]) for f in dataclasses.fields(cls)]
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _has_default(field: dataclasses.Field[Any]) -> bool:
|
|
165
|
+
return (
|
|
166
|
+
field.default is not dataclasses.MISSING or field.default_factory is not dataclasses.MISSING
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _default(field: dataclasses.Field[Any]) -> object:
|
|
171
|
+
if field.default is not dataclasses.MISSING:
|
|
172
|
+
return field.default
|
|
173
|
+
if field.default_factory is not dataclasses.MISSING:
|
|
174
|
+
return field.default_factory()
|
|
175
|
+
return dataclasses.MISSING
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _type_name(data: object) -> str:
|
|
179
|
+
return {
|
|
180
|
+
type(None): "null",
|
|
181
|
+
bool: "a boolean",
|
|
182
|
+
int: "an integer",
|
|
183
|
+
float: "a number",
|
|
184
|
+
str: "a string",
|
|
185
|
+
list: "a list",
|
|
186
|
+
dict: "a mapping",
|
|
187
|
+
}.get(type(data), type(data).__name__)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _is_union(tp: object) -> bool:
|
|
191
|
+
return get_origin(tp) in (Union, types.UnionType)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def freeze(data: object) -> object:
|
|
195
|
+
"""Make plain data immutable: lists become tuples, mappings become read-only."""
|
|
196
|
+
if isinstance(data, Mapping):
|
|
197
|
+
return types.MappingProxyType({k: freeze(v) for k, v in data.items()})
|
|
198
|
+
if isinstance(data, (list, tuple)):
|
|
199
|
+
return tuple(freeze(v) for v in data)
|
|
200
|
+
return data
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def freeze_mapping(data: Mapping[str, object]) -> Mapping[str, Any]:
|
|
204
|
+
""":func:`freeze` for a mapping, typed as one."""
|
|
205
|
+
return types.MappingProxyType({k: freeze(v) for k, v in data.items()})
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def thaw_mapping(data: Mapping[str, object]) -> dict[str, Any]:
|
|
209
|
+
""":func:`thaw` for a mapping, typed as a plain dict."""
|
|
210
|
+
return {k: thaw(v) for k, v in data.items()}
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def thaw(data: object) -> object:
|
|
214
|
+
"""Undo :func:`freeze`: tuples become lists and mappings become dicts."""
|
|
215
|
+
if isinstance(data, Mapping):
|
|
216
|
+
return {k: thaw(v) for k, v in data.items()}
|
|
217
|
+
if isinstance(data, tuple):
|
|
218
|
+
return [thaw(v) for v in data]
|
|
219
|
+
return data
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def parse(tp: Any, data: object, path: str, issues: Issues) -> Any: # noqa: ANN401, C901, PLR0911, PLR0912
|
|
223
|
+
"""Parse ``data`` as type ``tp``; record problems in ``issues`` and return ``INVALID``."""
|
|
224
|
+
origin = get_origin(tp)
|
|
225
|
+
if tp is Any:
|
|
226
|
+
return freeze(data)
|
|
227
|
+
if tp is type(None) or tp is None:
|
|
228
|
+
if data is None:
|
|
229
|
+
return None
|
|
230
|
+
issues.add(path, f"expected null, got {_type_name(data)}")
|
|
231
|
+
return INVALID
|
|
232
|
+
if isinstance(tp, type) and hasattr(tp, "spec_parse"):
|
|
233
|
+
return tp.spec_parse(data, path, issues)
|
|
234
|
+
if dataclasses.is_dataclass(tp) and isinstance(tp, type):
|
|
235
|
+
return parse_dataclass(tp, data, path, issues)
|
|
236
|
+
if tp is bool:
|
|
237
|
+
if isinstance(data, bool):
|
|
238
|
+
return data
|
|
239
|
+
issues.add(path, f"expected a boolean, got {_type_name(data)}")
|
|
240
|
+
return INVALID
|
|
241
|
+
if tp is int:
|
|
242
|
+
if isinstance(data, int) and not isinstance(data, bool):
|
|
243
|
+
return data
|
|
244
|
+
issues.add(path, f"expected an integer, got {_type_name(data)}")
|
|
245
|
+
return INVALID
|
|
246
|
+
if tp is float:
|
|
247
|
+
if isinstance(data, (int, float)) and not isinstance(data, bool):
|
|
248
|
+
return float(data)
|
|
249
|
+
issues.add(path, f"expected a number, got {_type_name(data)}")
|
|
250
|
+
return INVALID
|
|
251
|
+
if tp is str:
|
|
252
|
+
if isinstance(data, str):
|
|
253
|
+
return data
|
|
254
|
+
issues.add(path, f"expected a string, got {_type_name(data)}")
|
|
255
|
+
return INVALID
|
|
256
|
+
if origin is Literal:
|
|
257
|
+
allowed = get_args(tp)
|
|
258
|
+
if any(data == a and type(data) is type(a) for a in allowed):
|
|
259
|
+
return data
|
|
260
|
+
issues.add(path, f"expected one of {', '.join(map(repr, allowed))}, got {data!r}")
|
|
261
|
+
return INVALID
|
|
262
|
+
if _is_union(tp):
|
|
263
|
+
return _parse_union(tp, data, path, issues)
|
|
264
|
+
if origin is tuple:
|
|
265
|
+
item_type = get_args(tp)[0]
|
|
266
|
+
if not isinstance(data, list):
|
|
267
|
+
issues.add(path, f"expected a list, got {_type_name(data)}")
|
|
268
|
+
return INVALID
|
|
269
|
+
items = [parse(item_type, v, child(path, i), issues) for i, v in enumerate(data)]
|
|
270
|
+
return INVALID if any(i is INVALID for i in items) else tuple(items)
|
|
271
|
+
if origin is Mapping or origin is dict:
|
|
272
|
+
_, value_type = get_args(tp)
|
|
273
|
+
if not isinstance(data, dict):
|
|
274
|
+
issues.add(path, f"expected a mapping, got {_type_name(data)}")
|
|
275
|
+
return INVALID
|
|
276
|
+
out: dict[str, Any] = {}
|
|
277
|
+
for key, value in data.items():
|
|
278
|
+
if not isinstance(key, str):
|
|
279
|
+
issues.add(path, f"keys must be strings, got {key!r}")
|
|
280
|
+
continue
|
|
281
|
+
out[key] = parse(value_type, value, child(path, key), issues)
|
|
282
|
+
if any(v is INVALID for v in out.values()):
|
|
283
|
+
return INVALID
|
|
284
|
+
return types.MappingProxyType(out)
|
|
285
|
+
msg = f"unsupported annotation {tp!r}"
|
|
286
|
+
raise TypeError(msg)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _parse_union(tp: Any, data: object, path: str, issues: Issues) -> Any: # noqa: ANN401
|
|
290
|
+
arms = get_args(tp)
|
|
291
|
+
attempts: list[Issues] = []
|
|
292
|
+
for arm in arms:
|
|
293
|
+
scratch = Issues()
|
|
294
|
+
value = parse(arm, data, path, scratch)
|
|
295
|
+
if value is not INVALID and not scratch:
|
|
296
|
+
return value
|
|
297
|
+
attempts.append(scratch)
|
|
298
|
+
# An arm whose shape fits the data explains the problem best ("unknown key" inside a
|
|
299
|
+
# mapping); when no arm fits, say what was expected.
|
|
300
|
+
for arm, scratch in zip(arms, attempts, strict=True):
|
|
301
|
+
if _shape_fits(arm, data) and scratch.items:
|
|
302
|
+
issues.items.extend(scratch.items)
|
|
303
|
+
return INVALID
|
|
304
|
+
names = " or ".join(_describe(a) for a in arms)
|
|
305
|
+
issues.add(path, f"expected {names}, got {_type_name(data)}")
|
|
306
|
+
return INVALID
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _shape_fits(tp: object, data: object) -> bool:
|
|
310
|
+
"""Whether ``data`` has the JSON shape ``tp`` parses (its content may still be wrong)."""
|
|
311
|
+
if isinstance(tp, type) and hasattr(tp, "spec_parse"):
|
|
312
|
+
return True
|
|
313
|
+
if dataclasses.is_dataclass(tp) or get_origin(tp) in (Mapping, dict):
|
|
314
|
+
return isinstance(data, dict)
|
|
315
|
+
if get_origin(tp) is tuple:
|
|
316
|
+
return isinstance(data, list)
|
|
317
|
+
return False
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _describe(tp: object) -> str:
|
|
321
|
+
if tp is type(None):
|
|
322
|
+
return "null"
|
|
323
|
+
if get_origin(tp) is Literal:
|
|
324
|
+
return " or ".join(map(repr, get_args(tp)))
|
|
325
|
+
if get_origin(tp) is tuple:
|
|
326
|
+
return "a list"
|
|
327
|
+
if get_origin(tp) in (Mapping, dict) or dataclasses.is_dataclass(tp):
|
|
328
|
+
return "a mapping"
|
|
329
|
+
return {bool: "a boolean", int: "an integer", float: "a number", str: "a string"}.get(
|
|
330
|
+
tp, # type: ignore[call-overload]
|
|
331
|
+
getattr(tp, "__name__", str(tp)),
|
|
332
|
+
)
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def parse_dataclass(cls: type[DC], data: object, path: str, issues: Issues) -> DC | Invalid:
|
|
336
|
+
"""Parse a mapping into dataclass ``cls``, rejecting unknown keys."""
|
|
337
|
+
if not isinstance(data, dict):
|
|
338
|
+
issues.add(path, f"expected a mapping, got {_type_name(data)}")
|
|
339
|
+
return INVALID
|
|
340
|
+
fields = fields_of(cls)
|
|
341
|
+
by_key = {spec_key(f): (f, tp) for f, tp in fields}
|
|
342
|
+
for key in data:
|
|
343
|
+
if key not in by_key:
|
|
344
|
+
allowed = ", ".join(sorted(by_key))
|
|
345
|
+
issues.add(child(path, str(key)), f"unknown key; allowed here: {allowed}")
|
|
346
|
+
values: dict[str, Any] = {}
|
|
347
|
+
ok = True
|
|
348
|
+
for key, (field, tp) in by_key.items():
|
|
349
|
+
if key not in data:
|
|
350
|
+
if not _has_default(field):
|
|
351
|
+
issues.add(child(path, key), "required")
|
|
352
|
+
ok = False
|
|
353
|
+
continue
|
|
354
|
+
if data[key] is None and (hint := field.metadata.get("null_hint")):
|
|
355
|
+
issues.add(child(path, key), hint)
|
|
356
|
+
ok = False
|
|
357
|
+
continue
|
|
358
|
+
value = _parse_field(field, tp, data[key], child(path, key), issues)
|
|
359
|
+
if value is INVALID:
|
|
360
|
+
ok = False
|
|
361
|
+
else:
|
|
362
|
+
values[field.name] = value
|
|
363
|
+
if not ok or any(k not in by_key for k in data):
|
|
364
|
+
return INVALID
|
|
365
|
+
return cls(**values)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _parse_field(
|
|
369
|
+
field: dataclasses.Field[Any],
|
|
370
|
+
tp: object,
|
|
371
|
+
data: object,
|
|
372
|
+
path: str,
|
|
373
|
+
issues: Issues,
|
|
374
|
+
) -> Any: # noqa: ANN401
|
|
375
|
+
value = parse(tp, data, path, issues)
|
|
376
|
+
check = field.metadata.get("check")
|
|
377
|
+
if value is INVALID or value is None or check is None:
|
|
378
|
+
return value
|
|
379
|
+
if problem := check(value):
|
|
380
|
+
issues.add(path, problem)
|
|
381
|
+
return INVALID
|
|
382
|
+
return value
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def dump(value: object, *, full: bool = False) -> object:
|
|
386
|
+
"""The plain-data form of a parsed value.
|
|
387
|
+
|
|
388
|
+
Dataclass fields left at their default are omitted unless ``full`` is set.
|
|
389
|
+
"""
|
|
390
|
+
if isinstance(value, Dumpable):
|
|
391
|
+
return value.spec_dump()
|
|
392
|
+
if dataclasses.is_dataclass(value) and not isinstance(value, type):
|
|
393
|
+
out: dict[str, object] = {}
|
|
394
|
+
for field, _ in fields_of(type(value)):
|
|
395
|
+
item = getattr(value, field.name)
|
|
396
|
+
if not full and _has_default(field) and item == _default(field):
|
|
397
|
+
continue
|
|
398
|
+
out[spec_key(field)] = dump(item, full=full)
|
|
399
|
+
return out
|
|
400
|
+
if isinstance(value, Mapping):
|
|
401
|
+
return {k: dump(v, full=full) for k, v in value.items()}
|
|
402
|
+
if isinstance(value, tuple):
|
|
403
|
+
return [dump(v, full=full) for v in value]
|
|
404
|
+
return value
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def schema(tp: Any, defs: dict[str, Any]) -> dict[str, Any]: # noqa: ANN401, PLR0911
|
|
408
|
+
"""The JSON Schema (2020-12) for annotation ``tp``; dataclasses go into ``defs``."""
|
|
409
|
+
origin = get_origin(tp)
|
|
410
|
+
if tp is Any:
|
|
411
|
+
return {}
|
|
412
|
+
if tp is type(None) or tp is None:
|
|
413
|
+
return {"type": "null"}
|
|
414
|
+
if isinstance(tp, type) and hasattr(tp, "spec_schema"):
|
|
415
|
+
return tp.spec_schema(defs)
|
|
416
|
+
if dataclasses.is_dataclass(tp) and isinstance(tp, type):
|
|
417
|
+
return dataclass_schema(tp, defs)
|
|
418
|
+
simple = {bool: "boolean", int: "integer", float: "number", str: "string"}
|
|
419
|
+
if tp in simple:
|
|
420
|
+
return {"type": simple[tp]}
|
|
421
|
+
if origin is Literal:
|
|
422
|
+
return {"enum": list(get_args(tp))}
|
|
423
|
+
if _is_union(tp):
|
|
424
|
+
return _union_schema([schema(a, defs) for a in get_args(tp)])
|
|
425
|
+
if origin is tuple:
|
|
426
|
+
return {"type": "array", "items": schema(get_args(tp)[0], defs)}
|
|
427
|
+
if origin in (Mapping, dict):
|
|
428
|
+
return {"type": "object", "additionalProperties": schema(get_args(tp)[1], defs)}
|
|
429
|
+
msg = f"unsupported annotation {tp!r}"
|
|
430
|
+
raise TypeError(msg)
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def _union_schema(arms: list[dict[str, Any]]) -> dict[str, Any]:
|
|
434
|
+
"""Collapse simple unions to ``{"type": [...]}`` or an enum; otherwise ``anyOf``.
|
|
435
|
+
|
|
436
|
+
``str | None`` becomes ``{"type": ["string", "null"]}``, ``Literal["a"] | None`` becomes
|
|
437
|
+
``{"enum": ["a", None]}`` and ``Mapping[str, X] | None`` keeps its keywords with a nullable
|
|
438
|
+
type. Tools that read ``type`` (the Singer SDK's ``--about``, Meltano) then see it.
|
|
439
|
+
"""
|
|
440
|
+
if all(set(a) == {"enum"} or a == {"type": "null"} for a in arms):
|
|
441
|
+
values: list[object] = []
|
|
442
|
+
for arm in arms:
|
|
443
|
+
values.extend(arm.get("enum", [None]))
|
|
444
|
+
return {"enum": values}
|
|
445
|
+
typed = [a for a in arms if isinstance(a.get("type"), str)]
|
|
446
|
+
detailed = [a for a in typed if set(a) != {"type"}]
|
|
447
|
+
if len(typed) == len(arms) and len(detailed) <= 1:
|
|
448
|
+
merged = dict(detailed[0]) if detailed else {}
|
|
449
|
+
merged["type"] = [a["type"] for a in arms]
|
|
450
|
+
return merged
|
|
451
|
+
return {"anyOf": arms}
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def dataclass_schema(cls: type[DataclassInstance], defs: dict[str, Any]) -> dict[str, Any]:
|
|
455
|
+
"""Register ``cls`` in ``defs`` and return a ``$ref`` to it."""
|
|
456
|
+
name = cls.__name__
|
|
457
|
+
if name not in defs:
|
|
458
|
+
defs[name] = {} # placeholder, so recursive references terminate
|
|
459
|
+
properties: dict[str, Any] = {}
|
|
460
|
+
required: list[str] = []
|
|
461
|
+
for field, tp in fields_of(cls):
|
|
462
|
+
prop = schema(tp, defs)
|
|
463
|
+
if doc := field.metadata.get("doc"):
|
|
464
|
+
prop = {**prop, "description": doc}
|
|
465
|
+
default = _default(field)
|
|
466
|
+
if default is not dataclasses.MISSING:
|
|
467
|
+
# Complete defaults: validators that fill defaults in (the Singer SDK's) would
|
|
468
|
+
# otherwise write into a shared, partial default object.
|
|
469
|
+
prop = {**prop, "default": thaw(dump(default, full=True))}
|
|
470
|
+
else:
|
|
471
|
+
required.append(spec_key(field))
|
|
472
|
+
properties[spec_key(field)] = prop
|
|
473
|
+
body: dict[str, Any] = {
|
|
474
|
+
"type": "object",
|
|
475
|
+
"additionalProperties": False,
|
|
476
|
+
"properties": properties,
|
|
477
|
+
}
|
|
478
|
+
if cls.__doc__:
|
|
479
|
+
body = {"description": " ".join(cls.__doc__.split()), **body}
|
|
480
|
+
if required:
|
|
481
|
+
body["required"] = required
|
|
482
|
+
defs[name] = body
|
|
483
|
+
return {"$ref": f"#/$defs/{name}"}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Draft a spec from a catalog, and export canonical types to Zamboni (WBS 9.1, 9.2).
|
|
2
|
+
|
|
3
|
+
``spec import --catalog`` writes a starting spec: one stream rule per catalog stream, its
|
|
4
|
+
key properties, and each property as a column with an explicit canonical type (from the
|
|
5
|
+
catalog, or from a Zamboni table-config's ``columns``) and its description as ``doc``.
|
|
6
|
+
Names are left to the conformer; the draft validates against the catalog it came from.
|
|
7
|
+
|
|
8
|
+
``spec export --zamboni`` compiles each catalog stream exactly as the mapper would and
|
|
9
|
+
writes the output columns' types into the table-config (:mod:`map_conform.spec.zamboni`).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from typing import TYPE_CHECKING, Any
|
|
15
|
+
|
|
16
|
+
from map_conform.metadata import INTEGER_COLUMNS, TIMESTAMP_COLUMNS
|
|
17
|
+
from map_conform.naming.streams import stream_name
|
|
18
|
+
from map_conform.plan.compile import compile_stream
|
|
19
|
+
from map_conform.spec.check import Finding, output_columns
|
|
20
|
+
from map_conform.spec.load import ResolvedStream, output_streams, resolve_stream
|
|
21
|
+
from map_conform.spec.model import parse_spec
|
|
22
|
+
from map_conform.spec.zamboni import set_table_columns, table_columns
|
|
23
|
+
from map_conform.types.canonical import CTypeError, parse_ctype
|
|
24
|
+
from map_conform.types.from_jsonschema import from_jsonschema
|
|
25
|
+
|
|
26
|
+
if TYPE_CHECKING:
|
|
27
|
+
from map_conform.spec.check import CatalogStream
|
|
28
|
+
from map_conform.spec.model import Spec
|
|
29
|
+
from map_conform.transforms.registry import Registry
|
|
30
|
+
|
|
31
|
+
_DEFAULT = parse_spec({"version": 1}, "the default spec")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def draft_from_catalog(
|
|
35
|
+
catalog: list[CatalogStream],
|
|
36
|
+
zamboni: dict[str, Any] | None = None,
|
|
37
|
+
namespace: str | None = None,
|
|
38
|
+
) -> tuple[dict[str, Any], list[str]]:
|
|
39
|
+
"""A spec for the catalog's streams, and notes for the user."""
|
|
40
|
+
notes: list[str] = []
|
|
41
|
+
streams: dict[str, Any] = {}
|
|
42
|
+
for entry in catalog:
|
|
43
|
+
resolved = _default_rules(entry.name)
|
|
44
|
+
findings: list[Finding] = []
|
|
45
|
+
named = output_columns(resolved, entry.properties, findings, entry.name)
|
|
46
|
+
table = stream_name(resolved).name
|
|
47
|
+
declared = table_columns(zamboni, namespace, table) if zamboni and namespace else {}
|
|
48
|
+
columns: dict[str, Any] = {}
|
|
49
|
+
for column in named:
|
|
50
|
+
if not column.sources:
|
|
51
|
+
continue
|
|
52
|
+
source = column.sources[0]
|
|
53
|
+
schema = entry.properties.get(source) or {}
|
|
54
|
+
inferred = from_jsonschema(schema, "json")
|
|
55
|
+
notes.extend(f"{entry.name}.{source}: {w}" for w in inferred.warnings)
|
|
56
|
+
type_ = str(inferred.ctype)
|
|
57
|
+
if column.name in declared:
|
|
58
|
+
try:
|
|
59
|
+
type_ = str(parse_ctype(declared[column.name]))
|
|
60
|
+
except CTypeError:
|
|
61
|
+
notes.append(
|
|
62
|
+
f"{entry.name}.{source}: Zamboni type {declared[column.name]!r} is not "
|
|
63
|
+
f"a canonical type; kept {type_} from the catalog"
|
|
64
|
+
)
|
|
65
|
+
rule: dict[str, Any] = {"type": type_}
|
|
66
|
+
if isinstance(schema.get("description"), str):
|
|
67
|
+
rule["doc"] = schema["description"]
|
|
68
|
+
columns[source] = rule
|
|
69
|
+
stream: dict[str, Any] = {}
|
|
70
|
+
if entry.key_properties:
|
|
71
|
+
stream["key_properties"] = list(entry.key_properties)
|
|
72
|
+
stream["columns"] = columns
|
|
73
|
+
streams[entry.name] = stream
|
|
74
|
+
return {"version": 1, "streams": streams}, notes
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _default_rules(tap_stream: str) -> ResolvedStream:
|
|
78
|
+
resolved = resolve_stream(_DEFAULT, tap_stream)
|
|
79
|
+
if resolved is None: # pragma: no cover -- the default spec keeps every stream
|
|
80
|
+
msg = f"the default spec dropped {tap_stream!r}"
|
|
81
|
+
raise AssertionError(msg)
|
|
82
|
+
return resolved
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def export_columns( # noqa: PLR0913 -- the spec, the catalog and the file to fill
|
|
86
|
+
spec: Spec,
|
|
87
|
+
catalog: list[CatalogStream],
|
|
88
|
+
document: dict[str, Any],
|
|
89
|
+
namespace: str,
|
|
90
|
+
*,
|
|
91
|
+
registry: Registry,
|
|
92
|
+
config: dict[str, Any] | None = None,
|
|
93
|
+
) -> list[str]:
|
|
94
|
+
"""Write each output stream's column types into the table-config; the tables written."""
|
|
95
|
+
written: list[str] = []
|
|
96
|
+
for entry in catalog:
|
|
97
|
+
schema = {"type": "object", "properties": dict(entry.properties)}
|
|
98
|
+
for resolved in output_streams(spec, entry.name):
|
|
99
|
+
plan = compile_stream(
|
|
100
|
+
spec, resolved, schema, registry, key_properties=entry.key_properties,
|
|
101
|
+
config=config,
|
|
102
|
+
) # fmt: skip
|
|
103
|
+
columns = {c.name: str(c.ctype) for c in plan.columns}
|
|
104
|
+
if resolved.settings.add_record_metadata:
|
|
105
|
+
columns.update(dict.fromkeys(TIMESTAMP_COLUMNS, "timestamptz"))
|
|
106
|
+
columns.update(dict.fromkeys(INTEGER_COLUMNS, "int64"))
|
|
107
|
+
set_table_columns(document, namespace, plan.name, columns)
|
|
108
|
+
written.append(f"{namespace}.{plan.name}")
|
|
109
|
+
return written
|