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,380 @@
|
|
|
1
|
+
"""Check a spec against a Singer catalog, and explain what it does to a stream.
|
|
2
|
+
|
|
3
|
+
``map-conform spec validate --catalog`` and ``spec explain`` are built on this module. The
|
|
4
|
+
column naming here (:func:`output_columns`) is the one the plan compiler uses, so what
|
|
5
|
+
``explain`` shows is what the mapper emits.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import sys
|
|
12
|
+
from collections.abc import Mapping
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any, Literal
|
|
16
|
+
|
|
17
|
+
from map_conform.naming.conform import NameConformer, NamingError
|
|
18
|
+
from map_conform.naming.streams import stream_name
|
|
19
|
+
from map_conform.spec._struct import Issue, child, dump, thaw
|
|
20
|
+
from map_conform.spec.errors import SpecError
|
|
21
|
+
from map_conform.spec.load import ResolvedStream, matching_keys, output_streams
|
|
22
|
+
from map_conform.spec.model import ColumnSpec, Defaults, Spec
|
|
23
|
+
|
|
24
|
+
if sys.version_info >= (3, 12):
|
|
25
|
+
from typing import override
|
|
26
|
+
else:
|
|
27
|
+
from typing_extensions import override
|
|
28
|
+
|
|
29
|
+
Severity = Literal["error", "warning"]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class Finding:
|
|
34
|
+
"""A problem found when checking a spec against a catalog."""
|
|
35
|
+
|
|
36
|
+
severity: Severity
|
|
37
|
+
path: str
|
|
38
|
+
message: str
|
|
39
|
+
|
|
40
|
+
@override
|
|
41
|
+
def __str__(self) -> str:
|
|
42
|
+
"""``warning: path: message`` or ``path: message``."""
|
|
43
|
+
prefix = "warning: " if self.severity == "warning" else ""
|
|
44
|
+
return f"{prefix}{self.path or '<root>'}: {self.message}"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True)
|
|
48
|
+
class CatalogStream:
|
|
49
|
+
"""The parts of a catalog entry the spec is checked against."""
|
|
50
|
+
|
|
51
|
+
name: str
|
|
52
|
+
properties: Mapping[str, Any]
|
|
53
|
+
key_properties: tuple[str, ...]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def read_catalog(path: str | Path) -> list[CatalogStream]:
|
|
57
|
+
"""Read a Singer catalog (``{"streams": [...]}``).
|
|
58
|
+
|
|
59
|
+
Raises:
|
|
60
|
+
SpecError: if the file is unreadable or not a catalog.
|
|
61
|
+
"""
|
|
62
|
+
source = str(path)
|
|
63
|
+
try:
|
|
64
|
+
document = json.loads(Path(path).read_text(encoding="utf-8"))
|
|
65
|
+
except OSError as exc:
|
|
66
|
+
raise SpecError([Issue("", f"cannot read the catalog: {exc.strerror}")], source) from exc
|
|
67
|
+
except json.JSONDecodeError as exc:
|
|
68
|
+
where = f"line {exc.lineno}, column {exc.colno}"
|
|
69
|
+
raise SpecError([Issue("", f"invalid JSON at {where}: {exc.msg}")], source) from exc
|
|
70
|
+
streams = document.get("streams") if isinstance(document, dict) else None
|
|
71
|
+
if not isinstance(streams, list):
|
|
72
|
+
raise SpecError([Issue("", "a Singer catalog needs a 'streams' list")], source)
|
|
73
|
+
out: list[CatalogStream] = []
|
|
74
|
+
for entry in streams:
|
|
75
|
+
name = entry.get("tap_stream_id") or entry.get("stream")
|
|
76
|
+
schema = entry.get("schema") or {}
|
|
77
|
+
keys = entry.get("key_properties")
|
|
78
|
+
if keys is None:
|
|
79
|
+
top: dict[str, Any] = next(
|
|
80
|
+
(m for m in entry.get("metadata", []) if m.get("breadcrumb") == []), {}
|
|
81
|
+
)
|
|
82
|
+
keys = top.get("metadata", {}).get("table-key-properties", [])
|
|
83
|
+
out.append(CatalogStream(name, schema.get("properties") or {}, tuple(keys)))
|
|
84
|
+
return out
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
# --- Columns -----------------------------------------------------------------------------------
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass(frozen=True)
|
|
91
|
+
class OutputColumn:
|
|
92
|
+
"""One column of an output stream, as the plan will emit it."""
|
|
93
|
+
|
|
94
|
+
key: str
|
|
95
|
+
"""The ``columns`` key, or the source property name for an undeclared column."""
|
|
96
|
+
name: str
|
|
97
|
+
"""The output name."""
|
|
98
|
+
spec: ColumnSpec | None
|
|
99
|
+
"""The column's rules, or None for an undeclared column."""
|
|
100
|
+
sources: tuple[str, ...]
|
|
101
|
+
"""Source properties read (empty for a derived column)."""
|
|
102
|
+
tap_schema: Mapping[str, Any] | None
|
|
103
|
+
"""The source property's JSON Schema, when there is exactly one source in the catalog."""
|
|
104
|
+
notes: tuple[str, ...] = field(default=())
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def output_columns(
|
|
108
|
+
resolved: ResolvedStream,
|
|
109
|
+
properties: Mapping[str, Any] | None,
|
|
110
|
+
findings: list[Finding],
|
|
111
|
+
path: str,
|
|
112
|
+
key_properties: tuple[str, ...] = (),
|
|
113
|
+
) -> list[OutputColumn]:
|
|
114
|
+
"""The output columns of a resolved stream, named and de-duplicated.
|
|
115
|
+
|
|
116
|
+
With ``properties`` (from a catalog or tap SCHEMA), undeclared columns follow
|
|
117
|
+
``undeclared`` and references are checked. Without them, only the spec's columns are
|
|
118
|
+
known. Problems are appended to ``findings``.
|
|
119
|
+
"""
|
|
120
|
+
if properties is not None:
|
|
121
|
+
# The tap's own _sdc_* columns are never ordinary columns: with add_record_metadata
|
|
122
|
+
# they feed the metadata columns; without it they are left out, as SDK targets do.
|
|
123
|
+
properties = {k: v for k, v in properties.items() if not k.startswith("_sdc_")}
|
|
124
|
+
conformer = NameConformer(resolved.settings.naming)
|
|
125
|
+
entries = _column_entries(resolved, properties, findings, path, key_properties)
|
|
126
|
+
explicit: dict[str, str] = {}
|
|
127
|
+
for key, spec, _ in entries:
|
|
128
|
+
if spec is not None and spec.name is not None:
|
|
129
|
+
fixed = conformer.conform(spec.name).name
|
|
130
|
+
if fixed != spec.name:
|
|
131
|
+
findings.append(
|
|
132
|
+
Finding(
|
|
133
|
+
"error",
|
|
134
|
+
child(child(path, "columns"), key),
|
|
135
|
+
f"name {spec.name!r} is not a legal name here; it "
|
|
136
|
+
f"would conform to {fixed!r}",
|
|
137
|
+
)
|
|
138
|
+
)
|
|
139
|
+
explicit[key] = spec.name
|
|
140
|
+
to_conform = [key for key, _, _ in entries if key not in explicit]
|
|
141
|
+
try:
|
|
142
|
+
conformed = {c.source: c for c in conformer.conform_all(to_conform)}
|
|
143
|
+
except NamingError as exc:
|
|
144
|
+
findings.append(Finding("error", child(path, "columns"), str(exc)))
|
|
145
|
+
conformed = {k: conformer.conform(k) for k in to_conform}
|
|
146
|
+
out: list[OutputColumn] = []
|
|
147
|
+
seen: dict[str, str] = {}
|
|
148
|
+
for key, spec, sources in entries:
|
|
149
|
+
name = explicit.get(key) or conformed[key].name
|
|
150
|
+
notes = () if key in explicit else conformed[key].notes
|
|
151
|
+
clash = seen.get(name.casefold())
|
|
152
|
+
if clash is not None:
|
|
153
|
+
findings.append(
|
|
154
|
+
Finding(
|
|
155
|
+
"error",
|
|
156
|
+
child(child(path, "columns"), key),
|
|
157
|
+
f"output name {name!r} is also used by {clash!r}",
|
|
158
|
+
)
|
|
159
|
+
)
|
|
160
|
+
seen[name.casefold()] = key
|
|
161
|
+
tap = properties.get(sources[0]) if properties and len(sources) == 1 else None
|
|
162
|
+
out.append(OutputColumn(key, name, spec, sources, tap, notes))
|
|
163
|
+
_check_key_properties(resolved, out, findings, path)
|
|
164
|
+
return out
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _column_entries(
|
|
168
|
+
resolved: ResolvedStream,
|
|
169
|
+
properties: Mapping[str, Any] | None,
|
|
170
|
+
findings: list[Finding],
|
|
171
|
+
path: str,
|
|
172
|
+
key_properties: tuple[str, ...],
|
|
173
|
+
) -> list[tuple[str, ColumnSpec | None, tuple[str, ...]]]:
|
|
174
|
+
"""(key, spec, sources) for each output column, in output order, drops removed.
|
|
175
|
+
|
|
176
|
+
Under ``undeclared: drop`` the key properties stay (the spec's ``key_properties`` if set,
|
|
177
|
+
else the tap's), as the SDK's ``__else__: null`` keeps them.
|
|
178
|
+
"""
|
|
179
|
+
settings, columns = resolved.settings, resolved.spec.columns
|
|
180
|
+
entries: list[tuple[str, ColumnSpec | None, tuple[str, ...]]] = []
|
|
181
|
+
known = properties if properties is not None else {}
|
|
182
|
+
for key, spec in columns.items():
|
|
183
|
+
col_path = child(child(path, "columns"), key)
|
|
184
|
+
sources = _sources(key, spec)
|
|
185
|
+
if properties is not None:
|
|
186
|
+
missing = [s for s in sources if s not in known]
|
|
187
|
+
if missing and spec.expr is None:
|
|
188
|
+
what = "source column" if spec.source is not None else "column"
|
|
189
|
+
findings.append(
|
|
190
|
+
Finding(
|
|
191
|
+
"error",
|
|
192
|
+
col_path,
|
|
193
|
+
f"{what} {', '.join(map(repr, missing))} is not in the "
|
|
194
|
+
"catalog stream; a new column needs expr",
|
|
195
|
+
)
|
|
196
|
+
)
|
|
197
|
+
if spec.drop:
|
|
198
|
+
continue
|
|
199
|
+
derived = spec.expr is not None and spec.source is None and key not in known
|
|
200
|
+
entries.append((key, spec, () if derived else sources))
|
|
201
|
+
if properties is None:
|
|
202
|
+
return entries
|
|
203
|
+
claimed = {s for _, _, sources in entries for s in sources} | {
|
|
204
|
+
k for k, s in columns.items() if s.drop
|
|
205
|
+
}
|
|
206
|
+
undeclared = [p for p in properties if p not in claimed and p not in columns]
|
|
207
|
+
if settings.undeclared == "error":
|
|
208
|
+
findings.extend(
|
|
209
|
+
Finding("error", child(path, "columns"), f"undeclared column {p!r} (undeclared: error)")
|
|
210
|
+
for p in undeclared
|
|
211
|
+
)
|
|
212
|
+
elif settings.undeclared == "conform":
|
|
213
|
+
entries.extend((p, None, (p,)) for p in undeclared)
|
|
214
|
+
else:
|
|
215
|
+
keys = resolved.spec.key_properties
|
|
216
|
+
kept = set(keys if keys is not None else key_properties)
|
|
217
|
+
entries.extend((p, None, (p,)) for p in undeclared if p in kept)
|
|
218
|
+
if resolved.spec.order == "source":
|
|
219
|
+
position = {name: i for i, name in enumerate(properties)}
|
|
220
|
+
entries.sort(key=lambda e: position.get(e[2][0] if e[2] else "", len(position)))
|
|
221
|
+
return entries
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _sources(key: str, spec: ColumnSpec) -> tuple[str, ...]:
|
|
225
|
+
if spec.source is None:
|
|
226
|
+
return (key,)
|
|
227
|
+
return (spec.source,) if isinstance(spec.source, str) else spec.source
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _check_key_properties(
|
|
231
|
+
resolved: ResolvedStream, columns: list[OutputColumn], findings: list[Finding], path: str
|
|
232
|
+
) -> None:
|
|
233
|
+
"""An overriding key_properties names source or output columns that exist."""
|
|
234
|
+
if resolved.spec.key_properties is None:
|
|
235
|
+
return
|
|
236
|
+
names = {c.name for c in columns} | {s for c in columns for s in c.sources}
|
|
237
|
+
findings.extend(
|
|
238
|
+
Finding(
|
|
239
|
+
"error",
|
|
240
|
+
child(path, "key_properties"),
|
|
241
|
+
f"{key!r} is neither a source nor an output column",
|
|
242
|
+
)
|
|
243
|
+
for key in resolved.spec.key_properties
|
|
244
|
+
if key not in names
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
# --- Whole-spec check ----------------------------------------------------------------------------
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def check_spec(spec: Spec, catalog: list[CatalogStream] | None) -> list[Finding]:
|
|
252
|
+
"""Everything wrong with ``spec``, checked against ``catalog`` when one is given."""
|
|
253
|
+
findings: list[Finding] = []
|
|
254
|
+
if catalog is None:
|
|
255
|
+
return findings
|
|
256
|
+
by_name = {s.name: s for s in catalog}
|
|
257
|
+
matched: set[str] = set()
|
|
258
|
+
outputs: dict[str, str] = {}
|
|
259
|
+
for stream in catalog:
|
|
260
|
+
matched.update(matching_keys(spec, stream.name))
|
|
261
|
+
for resolved in output_streams(spec, stream.name):
|
|
262
|
+
key = resolved.key or stream.name
|
|
263
|
+
path = child("streams", key)
|
|
264
|
+
try:
|
|
265
|
+
name = stream_name(resolved).name
|
|
266
|
+
except NamingError as exc:
|
|
267
|
+
findings.append(Finding("error", path, exc.reason))
|
|
268
|
+
continue
|
|
269
|
+
if (other := outputs.get(name.casefold())) is not None:
|
|
270
|
+
findings.append(
|
|
271
|
+
Finding("error", path, f"output stream {name!r} is also produced by {other!r}")
|
|
272
|
+
)
|
|
273
|
+
outputs[name.casefold()] = key
|
|
274
|
+
_check_stream_keys(resolved, stream, findings, path)
|
|
275
|
+
output_columns(resolved, stream.properties, findings, path, stream.key_properties)
|
|
276
|
+
for key, rules in spec.streams.items():
|
|
277
|
+
if rules.spec.source is not None:
|
|
278
|
+
matched.add(key)
|
|
279
|
+
if rules.spec.source not in by_name:
|
|
280
|
+
findings.append(
|
|
281
|
+
Finding(
|
|
282
|
+
"error",
|
|
283
|
+
child(child("streams", key), "source"),
|
|
284
|
+
f"tap stream {rules.spec.source!r} is not in the catalog",
|
|
285
|
+
)
|
|
286
|
+
)
|
|
287
|
+
elif key not in matched:
|
|
288
|
+
findings.append(
|
|
289
|
+
Finding("warning", child("streams", key), "matches no stream in the catalog")
|
|
290
|
+
)
|
|
291
|
+
return findings
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _check_stream_keys(
|
|
295
|
+
resolved: ResolvedStream, stream: CatalogStream, findings: list[Finding], path: str
|
|
296
|
+
) -> None:
|
|
297
|
+
for key in stream.key_properties:
|
|
298
|
+
column = resolved.spec.columns.get(key)
|
|
299
|
+
if column is not None and column.drop:
|
|
300
|
+
findings.append(
|
|
301
|
+
Finding(
|
|
302
|
+
"error", child(child(path, "columns"), key), "a key property cannot be dropped"
|
|
303
|
+
)
|
|
304
|
+
)
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
# --- Explain ---------------------------------------------------------------------------------
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def explain(spec: Spec, tap_stream: str, catalog: list[CatalogStream] | None) -> dict[str, Any]:
|
|
311
|
+
"""A plain-data account of what the spec does to one tap stream."""
|
|
312
|
+
entry = next((s for s in catalog or [] if s.name == tap_stream), None)
|
|
313
|
+
properties = entry.properties if entry is not None else None
|
|
314
|
+
report: dict[str, Any] = {
|
|
315
|
+
"tap_stream": tap_stream,
|
|
316
|
+
"in_catalog": entry is not None if catalog is not None else None,
|
|
317
|
+
"matched": matching_keys(spec, tap_stream),
|
|
318
|
+
"outputs": [],
|
|
319
|
+
"findings": [],
|
|
320
|
+
}
|
|
321
|
+
findings: list[Finding] = []
|
|
322
|
+
outputs = output_streams(spec, tap_stream)
|
|
323
|
+
if not outputs:
|
|
324
|
+
report["dropped"] = True
|
|
325
|
+
for resolved in outputs:
|
|
326
|
+
path = child("streams", resolved.key or tap_stream)
|
|
327
|
+
try:
|
|
328
|
+
name: str | None = stream_name(resolved).name
|
|
329
|
+
except NamingError as exc:
|
|
330
|
+
findings.append(Finding("error", path, exc.reason))
|
|
331
|
+
name = None
|
|
332
|
+
keys = entry.key_properties if entry is not None else ()
|
|
333
|
+
columns = output_columns(resolved, properties, findings, path, keys)
|
|
334
|
+
report["outputs"].append(
|
|
335
|
+
{
|
|
336
|
+
"name": name,
|
|
337
|
+
"key": resolved.key,
|
|
338
|
+
"settings": thaw(_changed(resolved.settings, spec.defaults)),
|
|
339
|
+
"key_properties": list(
|
|
340
|
+
resolved.spec.key_properties or (entry.key_properties if entry else ())
|
|
341
|
+
),
|
|
342
|
+
"filter": resolved.spec.filter,
|
|
343
|
+
"columns": [_column_report(c) for c in columns],
|
|
344
|
+
}
|
|
345
|
+
)
|
|
346
|
+
report["findings"] = [str(f) for f in findings]
|
|
347
|
+
return report
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _changed(settings: Defaults, defaults: Defaults) -> object:
|
|
351
|
+
"""The settings this stream overrides, relative to the spec's defaults."""
|
|
352
|
+
mine, base = thaw(dump(settings, full=True)), thaw(dump(defaults, full=True))
|
|
353
|
+
return _diff(mine, base)
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _diff(mine: object, base: object) -> object:
|
|
357
|
+
if isinstance(mine, dict) and isinstance(base, dict):
|
|
358
|
+
return {k: _diff(v, base.get(k)) for k, v in mine.items() if v != base.get(k)}
|
|
359
|
+
return mine
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def _column_report(column: OutputColumn) -> dict[str, Any]:
|
|
363
|
+
spec = column.spec
|
|
364
|
+
declared = spec.type if spec is not None else None
|
|
365
|
+
tap_type = column.tap_schema.get("type") if column.tap_schema else None
|
|
366
|
+
report: dict[str, Any] = {
|
|
367
|
+
"source": list(column.sources) or None,
|
|
368
|
+
"name": column.name,
|
|
369
|
+
"type": declared,
|
|
370
|
+
"tap_type": tap_type,
|
|
371
|
+
"declared": spec is not None,
|
|
372
|
+
}
|
|
373
|
+
if spec is not None:
|
|
374
|
+
if spec.expr is not None:
|
|
375
|
+
report["expr"] = spec.expr
|
|
376
|
+
if spec.transform is not None:
|
|
377
|
+
report["transform"] = thaw(dump(spec.transform))
|
|
378
|
+
if column.notes:
|
|
379
|
+
report["notes"] = list(column.notes)
|
|
380
|
+
return report
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Errors raised for an invalid spec."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from collections.abc import Sequence
|
|
9
|
+
|
|
10
|
+
from map_conform.spec._struct import Issue
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class SpecError(ValueError):
|
|
14
|
+
"""A spec with one or more problems; ``issues`` lists every one with its path."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, issues: Sequence[Issue], source: str | None = None) -> None:
|
|
17
|
+
"""Keep the issues and build a message listing them."""
|
|
18
|
+
self.issues = tuple(issues)
|
|
19
|
+
self.source = source
|
|
20
|
+
where = f" in {source}" if source else ""
|
|
21
|
+
lines = "\n".join(f" {issue}" for issue in self.issues)
|
|
22
|
+
super().__init__(f"{len(self.issues)} problem(s){where}:\n{lines}")
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""``map-conform spec import --stream-maps``: SDK settings to a native spec (WBS 12.8).
|
|
2
|
+
|
|
3
|
+
The SDK settings are translated as the mapper translates them at start-up
|
|
4
|
+
(:mod:`map_conform.spec.stream_maps`), and the result is written as a spec file, compatibility
|
|
5
|
+
defaults included, so a project can drop ``stream_maps`` and keep its output.
|
|
6
|
+
|
|
7
|
+
Types the SDK would infer are written out explicitly. A type decided by the expression's
|
|
8
|
+
prefix (``int(...)``) needs nothing more; one taken from a tap property needs the catalog
|
|
9
|
+
(``--catalog``). Without it, or when a glob matches streams that disagree, the column keeps
|
|
10
|
+
``infer_type: sdk`` and a note says so.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from fnmatch import fnmatchcase
|
|
16
|
+
from typing import TYPE_CHECKING, Any
|
|
17
|
+
|
|
18
|
+
from map_conform.spec._struct import Issues
|
|
19
|
+
from map_conform.spec.errors import SpecError
|
|
20
|
+
from map_conform.spec.stream_maps import SDK_SETTINGS, prefix_type, sdk_type, translate
|
|
21
|
+
from map_conform.types.from_jsonschema import from_jsonschema
|
|
22
|
+
|
|
23
|
+
if TYPE_CHECKING:
|
|
24
|
+
from collections.abc import Mapping
|
|
25
|
+
|
|
26
|
+
from map_conform.spec.check import CatalogStream
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def import_stream_maps(
|
|
30
|
+
config: Mapping[str, Any], catalog: list[CatalogStream] | None
|
|
31
|
+
) -> tuple[dict[str, Any], list[str]]:
|
|
32
|
+
"""The native spec for the SDK settings in ``config``, and notes for the user.
|
|
33
|
+
|
|
34
|
+
Raises:
|
|
35
|
+
SpecError: when the settings cannot be translated.
|
|
36
|
+
"""
|
|
37
|
+
issues = Issues()
|
|
38
|
+
spec = translate({k: config.get(k) for k in SDK_SETTINGS}, issues)
|
|
39
|
+
if issues:
|
|
40
|
+
raise SpecError(issues.items, "the stream_maps settings")
|
|
41
|
+
if spec is None:
|
|
42
|
+
raise SpecError([], "the settings: there are no stream_maps or flattening settings")
|
|
43
|
+
notes: list[str] = []
|
|
44
|
+
nested = spec.get("defaults", {}).get("nested", "keep")
|
|
45
|
+
for key, rules in spec.get("streams", {}).items():
|
|
46
|
+
for name, column in rules.get("columns", {}).items():
|
|
47
|
+
if column.get("infer_type") != "sdk":
|
|
48
|
+
continue
|
|
49
|
+
resolved = _explicit_type(
|
|
50
|
+
key, rules, name, column["expr"], catalog=catalog, nested=nested
|
|
51
|
+
)
|
|
52
|
+
if resolved is None:
|
|
53
|
+
where = "no --catalog" if catalog is None else "the streams it matches disagree"
|
|
54
|
+
notes.append(
|
|
55
|
+
f"streams.{key}.columns.{name}: kept infer_type: sdk ({where}); "
|
|
56
|
+
"declare its type"
|
|
57
|
+
)
|
|
58
|
+
continue
|
|
59
|
+
del column["infer_type"]
|
|
60
|
+
column["type"] = resolved
|
|
61
|
+
if config.get("stream_map_config"):
|
|
62
|
+
notes.append("stream_map_config is config in expressions: move it to the spec_vars setting")
|
|
63
|
+
return spec, notes
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _explicit_type( # noqa: PLR0913 -- the column and where it applies
|
|
67
|
+
key: str,
|
|
68
|
+
rules: Mapping[str, Any],
|
|
69
|
+
name: str,
|
|
70
|
+
expr: str,
|
|
71
|
+
*,
|
|
72
|
+
catalog: list[CatalogStream] | None,
|
|
73
|
+
nested: str,
|
|
74
|
+
) -> str | None:
|
|
75
|
+
"""The column's type as text, when every matching catalog stream gives the same one."""
|
|
76
|
+
if catalog is None: # only what the expression decides by itself
|
|
77
|
+
decided = prefix_type(expr) if expr.strip() != "record" else None
|
|
78
|
+
return None if decided is None else str(decided)
|
|
79
|
+
dropped = rules.get("undeclared") == "drop"
|
|
80
|
+
source = rules.get("source", key)
|
|
81
|
+
found: set[str] = set()
|
|
82
|
+
for stream in (s for s in catalog if fnmatchcase(s.name, source)):
|
|
83
|
+
ctype, schema = sdk_type(expr, name, stream.properties, undeclared_dropped=dropped)
|
|
84
|
+
if ctype is None and schema is not None:
|
|
85
|
+
ctype = from_jsonschema(schema, "json" if nested == "json" else "keep").ctype
|
|
86
|
+
found.add(str(ctype))
|
|
87
|
+
return found.pop() if len(found) == 1 else None
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""The conform spec's JSON Schema, generated from the model (detailed design §3.1).
|
|
2
|
+
|
|
3
|
+
The shipped copy is ``map_conform/map-conform-spec.schema.json``; a test fails when it is
|
|
4
|
+
stale. Regenerate it with::
|
|
5
|
+
|
|
6
|
+
uv run python -m map_conform.spec.jsonschema
|
|
7
|
+
|
|
8
|
+
Editors can use the schema for completion and validation. It cannot express everything the
|
|
9
|
+
loader checks (CType grammar, the first-key step rule, cross-references), so
|
|
10
|
+
``map-conform spec validate`` remains the authority.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from map_conform.spec._struct import schema
|
|
20
|
+
from map_conform.spec.model import Spec
|
|
21
|
+
|
|
22
|
+
SCHEMA_ID = (
|
|
23
|
+
"https://raw.githubusercontent.com/paulcaron16k/map-conform/main/"
|
|
24
|
+
"map_conform/map-conform-spec.schema.json"
|
|
25
|
+
)
|
|
26
|
+
SHIPPED = Path(__file__).resolve().parent.parent / "map-conform-spec.schema.json"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def spec_json_schema() -> dict[str, Any]:
|
|
30
|
+
"""The JSON Schema (draft 2020-12) of a version 1 conform spec."""
|
|
31
|
+
defs: dict[str, Any] = {}
|
|
32
|
+
root = schema(Spec, defs)
|
|
33
|
+
return {
|
|
34
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
35
|
+
"$id": SCHEMA_ID,
|
|
36
|
+
"title": "map-conform spec (version 1)",
|
|
37
|
+
**root,
|
|
38
|
+
"$defs": dict(sorted(defs.items())),
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def render() -> str:
|
|
43
|
+
"""The schema as the shipped file's text."""
|
|
44
|
+
return json.dumps(spec_json_schema(), indent=2, ensure_ascii=False) + "\n"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def main() -> int:
|
|
48
|
+
"""Write the shipped schema file."""
|
|
49
|
+
SHIPPED.write_text(render(), encoding="utf-8")
|
|
50
|
+
return 0
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
if __name__ == "__main__":
|
|
54
|
+
raise SystemExit(main())
|