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.
Files changed (79) hide show
  1. map_conform/__init__.py +5 -0
  2. map_conform/__main__.py +7 -0
  3. map_conform/batch/__init__.py +1 -0
  4. map_conform/batch/arrow.py +80 -0
  5. map_conform/batch/columnar.py +125 -0
  6. map_conform/batch/engine.py +191 -0
  7. map_conform/batch/files.py +207 -0
  8. map_conform/cli.py +460 -0
  9. map_conform/doctor.py +178 -0
  10. map_conform/errors.py +107 -0
  11. map_conform/expr/__init__.py +6 -0
  12. map_conform/expr/compiler.py +562 -0
  13. map_conform/expr/functions.py +542 -0
  14. map_conform/expr/sandbox.py +333 -0
  15. map_conform/expr/sdk.py +116 -0
  16. map_conform/map-conform-spec.schema.json +1204 -0
  17. map_conform/mapper.py +355 -0
  18. map_conform/metadata.py +73 -0
  19. map_conform/metrics.py +62 -0
  20. map_conform/naming/__init__.py +1 -0
  21. map_conform/naming/ascii-table.json +980 -0
  22. map_conform/naming/conform.py +262 -0
  23. map_conform/naming/flatten.py +148 -0
  24. map_conform/naming/nested.py +117 -0
  25. map_conform/naming/reserved/ansi.txt +369 -0
  26. map_conform/naming/reserved/duckdb.txt +114 -0
  27. map_conform/naming/reserved/postgres.txt +105 -0
  28. map_conform/naming/reserved/snowflake.txt +90 -0
  29. map_conform/naming/reserved.py +34 -0
  30. map_conform/naming/shape.py +96 -0
  31. map_conform/naming/streams.py +76 -0
  32. map_conform/naming/translit.py +170 -0
  33. map_conform/plan/__init__.py +1 -0
  34. map_conform/plan/chain.py +667 -0
  35. map_conform/plan/compile.py +551 -0
  36. map_conform/plan/lower.py +281 -0
  37. map_conform/plan/ops.py +336 -0
  38. map_conform/plan/row.py +212 -0
  39. map_conform/plan/vector.py +71 -0
  40. map_conform/rejects.py +92 -0
  41. map_conform/settings.py +157 -0
  42. map_conform/spec/__init__.py +1 -0
  43. map_conform/spec/_struct.py +483 -0
  44. map_conform/spec/bridge.py +109 -0
  45. map_conform/spec/check.py +380 -0
  46. map_conform/spec/errors.py +22 -0
  47. map_conform/spec/importer.py +87 -0
  48. map_conform/spec/jsonschema.py +54 -0
  49. map_conform/spec/load.py +357 -0
  50. map_conform/spec/model.py +473 -0
  51. map_conform/spec/reference.py +179 -0
  52. map_conform/spec/steps.py +297 -0
  53. map_conform/spec/stream_maps.py +233 -0
  54. map_conform/spec/zamboni.py +99 -0
  55. map_conform/transforms/__init__.py +1 -0
  56. map_conform/transforms/builtins.py +63 -0
  57. map_conform/transforms/casts.py +310 -0
  58. map_conform/transforms/fake.py +150 -0
  59. map_conform/transforms/nested.py +111 -0
  60. map_conform/transforms/numeric.py +318 -0
  61. map_conform/transforms/polars_vector.py +151 -0
  62. map_conform/transforms/privacy.py +220 -0
  63. map_conform/transforms/registry.py +116 -0
  64. map_conform/transforms/temporal.py +410 -0
  65. map_conform/transforms/text.py +249 -0
  66. map_conform/transforms/vector.py +386 -0
  67. map_conform/types/__init__.py +1 -0
  68. map_conform/types/canonical.py +255 -0
  69. map_conform/types/from_jsonschema.py +177 -0
  70. map_conform/types/jsontext.py +63 -0
  71. map_conform/types/to_arrow.py +52 -0
  72. map_conform/types/to_jsonschema.py +65 -0
  73. map_conform/types/wire.py +53 -0
  74. map_conform/udfs.py +327 -0
  75. map_conform-0.1.0.dist-info/METADATA +157 -0
  76. map_conform-0.1.0.dist-info/RECORD +79 -0
  77. map_conform-0.1.0.dist-info/WHEEL +4 -0
  78. map_conform-0.1.0.dist-info/entry_points.txt +2 -0
  79. map_conform-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,473 @@
1
+ """The conform spec as frozen dataclasses (detailed design §3).
2
+
3
+ These classes are the single source of truth for the spec grammar: the strict parser, the
4
+ dump used for round trips and the shipped JSON Schema are all derived from them.
5
+
6
+ Inheritance by presence (defaults -> matching globs -> exact name) happens on the raw
7
+ mappings before parsing, in :mod:`map_conform.spec.load`. A :class:`StreamSpec` therefore
8
+ carries only the stream's own keys; the :class:`Defaults` keys it overrides are parsed into
9
+ the merged :class:`Defaults` of the resolved stream.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import dataclasses
15
+ import re
16
+ from collections.abc import Mapping
17
+ from dataclasses import dataclass
18
+ from typing import Any, Literal
19
+
20
+ from map_conform.spec._struct import (
21
+ INVALID,
22
+ Issues,
23
+ child,
24
+ dataclass_schema,
25
+ documented,
26
+ empty_mapping,
27
+ freeze_mapping,
28
+ non_negative,
29
+ parse_dataclass,
30
+ positive,
31
+ spec_key,
32
+ thaw,
33
+ )
34
+ from map_conform.spec.errors import SpecError
35
+ from map_conform.spec.steps import Chain, Macro
36
+ from map_conform.types.canonical import ctype_problem
37
+
38
+ OnError = Literal["raise", "null", "keep", "reject"]
39
+ Dialect = Literal["postgres", "duckdb", "snowflake", "ansi"]
40
+
41
+ _NULL_POLICY_HINT = (
42
+ "YAML reads a bare null as 'no value'; to choose the null policy, quote it: on_error: \"null\""
43
+ )
44
+ _UDF_TARGET = re.compile(r"^[A-Za-z_][\w.]*:[A-Za-z_]\w*$")
45
+
46
+
47
+ MIN_NAME_LENGTH = 8
48
+ """Room for at least one character, '_' and a 6-hex hash suffix."""
49
+
50
+
51
+ def _name_length(value: int) -> str | None:
52
+ return None if value >= MIN_NAME_LENGTH else f"must be at least {MIN_NAME_LENGTH}"
53
+
54
+
55
+ def _fraction(value: float) -> str | None:
56
+ return None if 0 <= value <= 1 else "must be between 0 and 1"
57
+
58
+
59
+ def _udf_problem(target: str) -> str | None:
60
+ return None if _UDF_TARGET.match(target) else "expected 'package.module:function'"
61
+
62
+
63
+ # --- Defaults ---------------------------------------------------------------------------------
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class NamingDefaults:
68
+ """How column names are conformed. ``naming: sdk`` is short for ``{preset: sdk}``."""
69
+
70
+ preset: Literal["map-conform", "sdk"] = documented(
71
+ "sdk reproduces the Singer SDK's SQL conform_name byte for byte (for migrations); "
72
+ "only on_collision applies then.",
73
+ default="map-conform",
74
+ )
75
+ case: Literal["snake", "lower", "upper", "preserve"] = documented(
76
+ "snake splits camelCase and lowercases; lower and upper only change case.",
77
+ default="snake",
78
+ )
79
+ split_camel: bool = documented(
80
+ "customerID -> customer_id; HTTPServer -> http_server.", default=True
81
+ )
82
+ ascii: Literal["transliterate", "strip", "keep"] = documented(
83
+ "transliterate with the bundled table (ADR-0012), strip non-ASCII, or keep it.",
84
+ default="transliterate",
85
+ )
86
+ replace_invalid: str = documented(
87
+ "Replacement for characters outside [a-z0-9_] after casing.", default="_"
88
+ )
89
+ collapse: bool = documented("Collapse runs of '_' and trim it from both ends.", default=True)
90
+ leading_digit: Literal["prefix", "letter", "error"] = documented(
91
+ "prefix '_', letter (SDK style: 0 -> a), or error.", default="prefix"
92
+ )
93
+ max_length: int = documented(
94
+ "Longer names are truncated (see truncate). At least 8, room for a hash suffix.",
95
+ default=63,
96
+ metadata={"check": _name_length},
97
+ )
98
+ truncate: Literal["hash", "error"] = documented(
99
+ "hash keeps the head plus '_' and 6 hex digits of a hash of the full name.",
100
+ default="hash",
101
+ )
102
+ reserved_words: Literal["suffix", "prefix", "error", "ignore"] = documented(
103
+ "What to do with a reserved word: suffix '_', prefix '_', error or ignore.",
104
+ default="suffix",
105
+ )
106
+ reserved_dialects: tuple[Dialect, ...] = documented(
107
+ "Reserved-word lists to union. ansi (SQL:2016) is opt-in: it reserves common column "
108
+ "names such as date, year and value.",
109
+ default=("postgres", "duckdb", "snowflake"),
110
+ )
111
+ on_collision: Literal["error", "suffix"] = documented(
112
+ "Two names conforming to the same output: error, or add _2, _3, ...", default="error"
113
+ )
114
+ nested: bool = documented("Also conform the member names of struct columns.", default=True)
115
+
116
+ @classmethod
117
+ def spec_parse(cls, data: object, path: str, issues: Issues) -> NamingDefaults | Any: # noqa: ANN401
118
+ """A mapping of options, or the preset name ``sdk``."""
119
+ if data == "sdk":
120
+ return cls(preset="sdk")
121
+ if isinstance(data, str):
122
+ issues.add(path, f"expected a mapping of naming options or 'sdk', got {data!r}")
123
+ return INVALID
124
+ return parse_dataclass(cls, data, path, issues)
125
+
126
+ @classmethod
127
+ def spec_schema(cls, defs: dict[str, Any]) -> dict[str, Any]:
128
+ """The options object, or the string ``sdk``."""
129
+ options = dataclass_schema(cls, defs)
130
+ return {"anyOf": [options, {"const": "sdk", "description": "Short for {preset: sdk}."}]}
131
+
132
+
133
+ @dataclass(frozen=True)
134
+ class StreamNaming:
135
+ """How stream names are conformed."""
136
+
137
+ name: Literal["conform", "preserve"] = documented(
138
+ "Conform stream names like column names, or keep them.", default="conform"
139
+ )
140
+ prefix: str = documented("Added after conforming.", default="")
141
+ split: str | None = documented(
142
+ "Emit only the part after the last occurrence of this separator.", default=None
143
+ )
144
+
145
+
146
+ @dataclass(frozen=True)
147
+ class ValuesDefaults:
148
+ """Value cleanup applied before casting."""
149
+
150
+ trim: bool = documented("Trim surrounding whitespace from strings.", default=True)
151
+ null_tokens: tuple[str, ...] = documented(
152
+ "Strings that mean null.",
153
+ default=("", "NULL", "null", "N/A", "n/a", "#N/A", "NaN", "-"),
154
+ )
155
+ null_tokens_case_sensitive: bool = documented(
156
+ "Match null tokens case-sensitively.", default=False
157
+ )
158
+ empty_string_for_string: Literal["keep", "null"] = documented(
159
+ 'What "" becomes in a string column.', default="keep"
160
+ )
161
+
162
+
163
+ @dataclass(frozen=True)
164
+ class TimestampDefaults:
165
+ """Defaults for temporal casts."""
166
+
167
+ assume_tz: str = documented("Time zone of naive input cast to timestamptz.", default="UTC")
168
+ output_precision: Literal["s", "ms", "us"] = documented(
169
+ "Fractional precision on output.", default="us"
170
+ )
171
+ formats: tuple[str, ...] = documented(
172
+ "Formats tried in order: strftime patterns, iso, excel_serial, epoch_*, rfc2822.",
173
+ default=("iso",),
174
+ )
175
+
176
+
177
+ @dataclass(frozen=True)
178
+ class BooleanDefaults:
179
+ """Words that cast to booleans (case-insensitive unless the cast says otherwise)."""
180
+
181
+ true_values: tuple[str, ...] = documented(
182
+ "Strings that mean true.", default=("true", "t", "yes", "y", "1", "on")
183
+ )
184
+ false_values: tuple[str, ...] = documented(
185
+ "Strings that mean false.", default=("false", "f", "no", "n", "0", "off")
186
+ )
187
+
188
+
189
+ @dataclass(frozen=True)
190
+ class FlattenDefaults:
191
+ """Singer SDK flattening semantics, for nested: flatten."""
192
+
193
+ separator: str = documented("Joins parent and child keys.", default="__")
194
+ max_depth: int = documented(
195
+ "Levels of nesting to flatten.", default=1, metadata={"check": non_negative}
196
+ )
197
+ max_key_length: int = documented(
198
+ "Longest flattened key.", default=255, metadata={"check": positive}
199
+ )
200
+
201
+
202
+ @dataclass(frozen=True)
203
+ class FakerDefaults:
204
+ """Settings for the fake builtin (needs the faker extra)."""
205
+
206
+ seed: int | None = documented("Seed for reproducible fake values.", default=None)
207
+ locale: str | tuple[str, ...] | None = documented("Faker locale or locales.", default=None)
208
+
209
+
210
+ @dataclass(frozen=True)
211
+ class Defaults:
212
+ """Settings inherited by every stream. A stream may override any of them."""
213
+
214
+ naming: NamingDefaults = documented("Column naming.", default_factory=NamingDefaults)
215
+ stream: StreamNaming = documented("Stream naming.", default_factory=StreamNaming)
216
+ values: ValuesDefaults = documented("Value cleanup.", default_factory=ValuesDefaults)
217
+ timestamp: TimestampDefaults = documented("Temporal casts.", default_factory=TimestampDefaults)
218
+ boolean: BooleanDefaults = documented("Boolean casts.", default_factory=BooleanDefaults)
219
+ on_error: OnError = documented(
220
+ "What a failed cast or transform does: raise, null, keep the raw value, or reject the "
221
+ "row to the dead-letter sink.",
222
+ default="raise",
223
+ metadata={"null_hint": _NULL_POLICY_HINT},
224
+ )
225
+ add_record_metadata: bool = documented(
226
+ "Add the seven Singer SDK _sdc_* columns to SCHEMA, RECORD and BATCH output, as SDK "
227
+ "targets do with their setting of the same name.",
228
+ default=False,
229
+ )
230
+ undeclared: Literal["conform", "drop", "error"] = documented(
231
+ "Columns the spec does not mention: conform them from the tap SCHEMA, drop them, or fail.",
232
+ default="conform",
233
+ )
234
+ nested: Literal["json", "flatten", "keep"] = documented(
235
+ "Undeclared object and array columns: JSON text, flattened, or typed struct/list.",
236
+ default="json",
237
+ )
238
+ flatten: FlattenDefaults = documented("Flattening settings.", default_factory=FlattenDefaults)
239
+ faker: FakerDefaults = documented("Fake data settings.", default_factory=FakerDefaults)
240
+ engine: Literal["arrow", "polars"] = documented(
241
+ "Vectorised BATCH engine: Arrow, or polars (the polars extra), which also vectorises "
242
+ "regular expressions and strptime date formats.",
243
+ default="arrow",
244
+ )
245
+ max_reject_rate: float | None = documented(
246
+ "Fail the run when more than this fraction of a stream's rows is rejected (0-1).",
247
+ default=None,
248
+ metadata={"check": _fraction},
249
+ )
250
+ max_null_rate: float | None = documented(
251
+ "Fail the run when on_error: null nulls values in more than this fraction of a "
252
+ "stream's rows (0-1).",
253
+ default=None,
254
+ metadata={"check": _fraction},
255
+ )
256
+
257
+
258
+ # --- Columns and streams ------------------------------------------------------------------------
259
+
260
+
261
+ @dataclass(frozen=True)
262
+ class ExprRef:
263
+ """A value computed by an expression."""
264
+
265
+ expr: str = documented("The expression.")
266
+
267
+
268
+ @dataclass(frozen=True)
269
+ class FieldSpec:
270
+ """Transforms on a nested member of a struct or json column, by dotted path."""
271
+
272
+ transform: Chain | None = documented("Steps applied to the member.", default=None)
273
+ when: str | None = documented("Apply only where this expression is truthy.", default=None)
274
+ drop: bool = documented("Remove the member.", default=False)
275
+
276
+
277
+ @dataclass(frozen=True)
278
+ class ColumnSpec:
279
+ """One output column. Unset keys inherit from the stream's defaults or the tap SCHEMA."""
280
+
281
+ name: str | None = documented(
282
+ "Output name. It is checked, never silently conformed.", default=None
283
+ )
284
+ type: str | None = documented(
285
+ "Declared CType, e.g. int64, decimal(18,2), timestamptz. From the tap SCHEMA if absent.",
286
+ default=None,
287
+ metadata={"check": ctype_problem},
288
+ )
289
+ nullable: bool = documented("If false, a null is an error under on_error.", default=True)
290
+ source: str | tuple[str, ...] | None = documented(
291
+ "Source column(s) if not the key; a list coalesces in order.", default=None
292
+ )
293
+ expr: str | None = documented(
294
+ "Derived value. Without source, it creates a new column.", default=None
295
+ )
296
+ default: Any = documented(
297
+ "Used when the value is missing or null after transforms.", default=None
298
+ )
299
+ transform: Chain | None = documented("Steps run before the implicit cast.", default=None)
300
+ parse: Mapping[str, Any] | None = documented(
301
+ "Keyword arguments for the implicit cast, e.g. {formats: [...], tz: ...}.", default=None
302
+ )
303
+ true_values: tuple[str, ...] | None = documented("Overrides boolean.true_values.", default=None)
304
+ false_values: tuple[str, ...] | None = documented(
305
+ "Overrides boolean.false_values.", default=None
306
+ )
307
+ null_tokens: tuple[str, ...] | None = documented("Overrides values.null_tokens.", default=None)
308
+ trim: bool | None = documented("Overrides values.trim.", default=None)
309
+ on_error: OnError | None = documented(
310
+ "Overrides on_error.", default=None, metadata={"null_hint": _NULL_POLICY_HINT}
311
+ )
312
+ max_length: int | None = documented(
313
+ "Longest string allowed.", default=None, metadata={"check": positive}
314
+ )
315
+ on_overflow: Literal["truncate", "error"] = documented(
316
+ "What a string longer than max_length does.", default="error"
317
+ )
318
+ enum: tuple[Any, ...] | None = documented(
319
+ "Allowed values, checked after the cast.", default=None
320
+ )
321
+ drop: bool = documented(
322
+ "Remove the column. Dropping a key property is an error.", default=False
323
+ )
324
+ doc: str | None = documented("Copied to the SCHEMA description.", default=None)
325
+ sql_type: str | None = documented("Overrides the emitted x-sql-datatype hint.", default=None)
326
+ when: str | None = documented(
327
+ "Apply the chain only to rows where this is truthy; sees conformed names.", default=None
328
+ )
329
+ fields: Mapping[str, FieldSpec] | None = documented(
330
+ "Transforms on nested members of struct and json columns, by dotted path.",
331
+ default=None,
332
+ )
333
+ shape: Mapping[str, Any] | None = documented(
334
+ "JSON Schema of the column's object or array value, inline or as a path to a .json "
335
+ "file (relative to the spec file). It alone decides the column's type, or its "
336
+ "flattened columns; members it does not declare are dropped, counted and logged; a "
337
+ "member's default (null, {}, []) is used when it is missing or empty.",
338
+ default=None,
339
+ )
340
+ flatten: bool | None = documented(
341
+ "Flatten this column into parent__child columns (from its shape when it has one). "
342
+ "Unset: follow nested: flatten.",
343
+ default=None,
344
+ )
345
+ engine: Literal["arrow", "polars"] | None = documented(
346
+ "Overrides engine for this column.", default=None
347
+ )
348
+ infer_type: Literal["sdk"] | None = documented(
349
+ "Without type: infer it from expr as the Singer SDK mapper does (int(...) is an "
350
+ "integer, and so on). Set by stream_maps translation; declaring type is clearer.",
351
+ default=None,
352
+ )
353
+
354
+
355
+ @dataclass(frozen=True)
356
+ class StreamSpec:
357
+ """A stream's own keys. Defaults keys set on the stream are merged into its Defaults."""
358
+
359
+ alias: str | ExprRef | None = documented(
360
+ "Final stream name; bypasses stream naming and prefix.", default=None
361
+ )
362
+ source: str | None = documented(
363
+ "Make this key a new output stream projected from this tap stream (split or copy).",
364
+ default=None,
365
+ )
366
+ prefix: str | None = documented("Overrides stream.prefix.", default=None)
367
+ key_properties: tuple[str, ...] | None = documented(
368
+ "Overrides the tap's key properties; source or conformed names.", default=None
369
+ )
370
+ filter: str | None = documented(
371
+ "Rows where this expression is falsy are dropped; sees conformed names.", default=None
372
+ )
373
+ columns: Mapping[str, ColumnSpec] = documented(
374
+ "Columns by source name, or by new name for derived columns.", default_factory=empty_mapping
375
+ )
376
+ order: Literal["source", "declared"] = documented(
377
+ "Output column order: the tap's, or the order of columns here.", default="source"
378
+ )
379
+ drop: bool = documented("Drop the whole stream.", default=False)
380
+
381
+
382
+ STREAM_KEYS = frozenset(spec_key(f) for f in dataclasses.fields(StreamSpec))
383
+ DEFAULTS_KEYS = frozenset(spec_key(f) for f in dataclasses.fields(Defaults))
384
+
385
+
386
+ @dataclass(frozen=True)
387
+ class StreamRules:
388
+ """A ``streams`` entry: its parsed StreamSpec, and its raw mapping for inheritance."""
389
+
390
+ raw: Mapping[str, Any]
391
+ spec: StreamSpec
392
+
393
+ @classmethod
394
+ def spec_parse(cls, data: object, path: str, issues: Issues) -> StreamRules | Any: # noqa: ANN401
395
+ """Validate StreamSpec keys and any Defaults keys the stream overrides."""
396
+ if not isinstance(data, dict):
397
+ issues.add(path, "expected a mapping of stream rules")
398
+ return INVALID
399
+ own = {k: v for k, v in data.items() if k in STREAM_KEYS}
400
+ overrides = {k: v for k, v in data.items() if k in DEFAULTS_KEYS}
401
+ allowed = ", ".join(sorted(STREAM_KEYS | DEFAULTS_KEYS))
402
+ unknown = [k for k in data if k not in STREAM_KEYS | DEFAULTS_KEYS]
403
+ for key in unknown:
404
+ issues.add(child(path, str(key)), f"unknown key; allowed here: {allowed}")
405
+ spec = parse_dataclass(StreamSpec, own, path, issues)
406
+ checked = parse_dataclass(Defaults, overrides, path, issues)
407
+ if unknown or not isinstance(spec, StreamSpec) or checked is INVALID:
408
+ return INVALID
409
+ return cls(freeze_mapping(data), spec)
410
+
411
+ def spec_dump(self) -> object:
412
+ """The mapping as written."""
413
+ return thaw(self.raw)
414
+
415
+ @classmethod
416
+ def spec_schema(cls, defs: dict[str, Any]) -> dict[str, Any]:
417
+ """StreamSpec properties plus every Defaults property, without defaults (inherited)."""
418
+ if "StreamRules" not in defs:
419
+ dataclass_schema(StreamSpec, defs)
420
+ dataclass_schema(Defaults, defs)
421
+ inherited = {
422
+ key: {k: v for k, v in prop.items() if k != "default"}
423
+ for key, prop in defs["Defaults"]["properties"].items()
424
+ }
425
+ defs["StreamRules"] = {
426
+ "description": (
427
+ "Rules for the streams this key matches: StreamSpec keys plus any Defaults "
428
+ "key, which overrides the inherited value (objects merge, lists replace)."
429
+ ),
430
+ "type": "object",
431
+ "additionalProperties": False,
432
+ "properties": {**defs["StreamSpec"]["properties"], **inherited},
433
+ }
434
+ return {"$ref": "#/$defs/StreamRules"}
435
+
436
+
437
+ @dataclass(frozen=True)
438
+ class Spec:
439
+ """A conform spec file, version 1."""
440
+
441
+ version: Literal[1] = documented("The spec version.")
442
+ defaults: Defaults = documented("Inherited by every stream.", default_factory=Defaults)
443
+ macros: Mapping[str, Macro] = documented(
444
+ "Named, parameterised transform chains.", default_factory=empty_mapping
445
+ )
446
+ udfs: Mapping[str, str] = documented(
447
+ "Python functions by name, as 'package.module:function'.",
448
+ default_factory=empty_mapping,
449
+ metadata={"check": lambda m: next(filter(None, map(_udf_problem, m.values())), None)},
450
+ )
451
+ streams: Mapping[str, StreamRules] = documented(
452
+ "Per-stream rules: StreamSpec keys plus any Defaults key. A key is a glob over tap "
453
+ "stream names, or a new stream name when the rules have source.",
454
+ default_factory=empty_mapping,
455
+ )
456
+ else_: Literal["keep", "drop"] = documented(
457
+ "Tap streams that match no key: keep (conform with the defaults) or drop.",
458
+ default="keep",
459
+ metadata={"key": "else"},
460
+ )
461
+
462
+
463
+ def parse_spec(data: object, source: str | None = None) -> Spec:
464
+ """Strictly parse spec data (already substituted and merged with any inline spec).
465
+
466
+ Raises:
467
+ SpecError: listing every problem found, each with its path.
468
+ """
469
+ issues = Issues()
470
+ spec = parse_dataclass(Spec, data, "", issues)
471
+ if issues or not isinstance(spec, Spec):
472
+ raise SpecError(issues.items, source)
473
+ return spec
@@ -0,0 +1,179 @@
1
+ """The spec reference (``docs/spec-reference.md``), generated from the model (WBS 10.1).
2
+
3
+ Every key, type, default and description comes from the same frozen dataclasses the strict
4
+ parser and the JSON Schema use, and the builtin and function tables from the registries, so
5
+ the reference cannot drift from the code. A test fails when the shipped copy is stale.
6
+ Regenerate it with::
7
+
8
+ uv run python -m map_conform.spec.reference
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import dataclasses
14
+ import json
15
+ import typing
16
+ from collections.abc import Mapping
17
+ from pathlib import Path
18
+ from types import NoneType, UnionType
19
+ from typing import Any, Literal, get_args, get_origin
20
+
21
+ from map_conform.expr.functions import FUNCTIONS
22
+ from map_conform.settings import Settings
23
+ from map_conform.spec._struct import dump, fields_of, spec_key
24
+ from map_conform.spec.model import ColumnSpec, Defaults, ExprRef, FieldSpec, Spec, StreamSpec
25
+ from map_conform.spec.steps import Chain, Macro
26
+ from map_conform.transforms.builtins import builtin_registry
27
+ from map_conform.types.canonical import Kind
28
+
29
+ SHIPPED = Path(__file__).resolve().parents[2] / "docs" / "spec-reference.md"
30
+ _GROUPS = ("predicates", "coercion", "temporal", "text", "numeric", "misc", "python", "modules")
31
+
32
+
33
+ def _type(tp: Any) -> str: # noqa: ANN401, PLR0911 -- one branch per annotation form
34
+ """An annotation in words."""
35
+ origin = get_origin(tp)
36
+ if tp is Any:
37
+ return "any"
38
+ if tp is NoneType:
39
+ return "null"
40
+ if origin is Literal:
41
+ return " \\| ".join(f"`{a}`" for a in get_args(tp))
42
+ if origin in (UnionType, typing.Union):
43
+ return " or ".join(_type(a) for a in get_args(tp))
44
+ if origin is tuple:
45
+ return f"list of {_type(get_args(tp)[0])}"
46
+ if origin in (Mapping, dict):
47
+ return f"mapping of {_type(get_args(tp)[1])}"
48
+ names = {bool: "boolean", int: "integer", float: "number", str: "string",
49
+ Chain: "chain", Macro: "macro", ExprRef: "`{expr: ...}`"} # fmt: skip
50
+ if tp in names:
51
+ return names[tp]
52
+ if dataclasses.is_dataclass(tp):
53
+ return "object"
54
+ return str(tp)
55
+
56
+
57
+ def _default(field: dataclasses.Field[Any]) -> str:
58
+ if field.default is not dataclasses.MISSING:
59
+ value: object = field.default
60
+ elif field.default_factory is not dataclasses.MISSING:
61
+ value = field.default_factory()
62
+ else:
63
+ return "required"
64
+ if value is None:
65
+ return "unset"
66
+ if dataclasses.is_dataclass(value):
67
+ return "the section below"
68
+ return f"`{json.dumps(dump(value, full=True), ensure_ascii=False)}`"
69
+
70
+
71
+ def _rows(cls: type[Any], prefix: str = "", *, expand: bool = True) -> list[str]:
72
+ """Table rows for a dataclass's fields; nested objects become dotted keys when expanded."""
73
+ rows: list[str] = []
74
+ for field, tp in fields_of(cls):
75
+ key = f"{prefix}{spec_key(field)}"
76
+ doc = " ".join(str(field.metadata.get("doc", "")).split()).replace("|", "\\|")
77
+ if expand and dataclasses.is_dataclass(tp) and isinstance(tp, type):
78
+ rows.extend(_rows(tp, f"{key}."))
79
+ continue
80
+ rows.append(f"| `{key}` | {_type(tp)} | {_default(field)} | {doc} |")
81
+ return rows
82
+
83
+
84
+ def _table(cls: type[Any], *, expand: bool = True) -> list[str]:
85
+ rows = _rows(cls, expand=expand)
86
+ return ["| Key | Type | Default | Meaning |", "| -- | -- | -- | -- |", *rows]
87
+
88
+
89
+ def _steps() -> list[str]:
90
+ lines = ["| Step | Options | Meaning |", "| -- | -- | -- |"]
91
+ registry = builtin_registry()
92
+ for name, transform in sorted(registry.names().items()):
93
+ options = ", ".join(f"`{f.name}`" for f in dataclasses.fields(transform.kwargs)) or "none"
94
+ lines.append(f"| `{name}` | {options} | {transform.doc} |")
95
+ kinds = ", ".join(f"`{k}`" for k in sorted(registry.casts))
96
+ lines.append(f"| `cast` | per target type | Casts to any of {kinds}. |")
97
+ return lines
98
+
99
+
100
+ def _functions() -> list[str]:
101
+ lines = ["| Function | Group | Meaning |", "| -- | -- | -- |"]
102
+ ordered = sorted(FUNCTIONS.values(), key=lambda f: (_GROUPS.index(f.group), f.name))
103
+ lines.extend(f"| `{f.signature}` | {f.group} | {f.doc} |" for f in ordered)
104
+ return lines
105
+
106
+
107
+ def render() -> str:
108
+ """The reference's text."""
109
+ kinds = ", ".join(f"`{k}`" for k in get_args(Kind))
110
+ parts = [
111
+ "# map-conform spec reference",
112
+ "",
113
+ "Generated from the code by `uv run python -m map_conform.spec.reference`; do not edit.",
114
+ "The [detailed design](detailed-design.md) explains the behaviour behind each key, and",
115
+ "the [cookbook](cookbook.md) shows them at work.",
116
+ "",
117
+ "## Plugin settings",
118
+ "",
119
+ "Set in `meltano.yml` (or `--config`). Nested keys are written with dots in Meltano.",
120
+ "",
121
+ *_table(Settings),
122
+ "",
123
+ "## Spec file: top level",
124
+ "",
125
+ *_table(Spec, expand=False),
126
+ "",
127
+ "## `defaults`",
128
+ "",
129
+ "Inherited by every stream; a stream rule may set any of these keys to override them.",
130
+ "",
131
+ *_table(Defaults),
132
+ "",
133
+ "## `streams.<glob>`",
134
+ "",
135
+ "Plus any `defaults` key. A key is a glob over tap stream names, or a new output stream's",
136
+ "name when the rule has `source`.",
137
+ "",
138
+ *_table(StreamSpec),
139
+ "",
140
+ "## `columns.<name>`",
141
+ "",
142
+ *_table(ColumnSpec),
143
+ "",
144
+ "## `fields.<path>`",
145
+ "",
146
+ "For `struct` and `json` columns; paths are member names joined by `.`, with `[*]` for",
147
+ "list items.",
148
+ "",
149
+ *_table(FieldSpec),
150
+ "",
151
+ "## Types",
152
+ "",
153
+ f"Kinds: {kinds}. Parameterised: `decimal(p,s)`, `string(n)`, `list<T>`,",
154
+ "`struct<name: T, ...>`. SQL aliases are read too (`bigint`, `varchar(n)`, `long`, ...).",
155
+ "",
156
+ "## Builtin steps",
157
+ "",
158
+ *_steps(),
159
+ "",
160
+ "## Expression functions",
161
+ "",
162
+ "Builtin steps, `cast(value, type, ...)`, macros and UDFs are callable in expressions",
163
+ "too. Names in scope: `value`/`self`, columns by conformed name, `record`/`_`,",
164
+ "`source(name)`, `config`, `stream`, `source_stream`, `row_number`, `NULL`, `fake`.",
165
+ "",
166
+ *_functions(),
167
+ "",
168
+ ]
169
+ return "\n".join(parts)
170
+
171
+
172
+ def main() -> int:
173
+ """Write the shipped reference."""
174
+ SHIPPED.write_text(render(), encoding="utf-8")
175
+ return 0
176
+
177
+
178
+ if __name__ == "__main__":
179
+ raise SystemExit(main())