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,63 @@
1
+ """The registry of every builtin transform and cast."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ import functools
7
+ from types import MappingProxyType
8
+
9
+ from map_conform.transforms import casts, fake, nested, numeric, privacy, temporal, text
10
+ from map_conform.transforms.registry import Registry
11
+
12
+ _MODULES = (text, casts, numeric, temporal, nested, privacy, fake)
13
+
14
+ DOCS = MappingProxyType(
15
+ {
16
+ "assume_tz": "Place a naive timestamp in tz, giving an aware one.",
17
+ "clamp": "Limit a number to [min, max], or fail outside it.",
18
+ "date_from_timestamp": "The date of a timestamp, in tz when given.",
19
+ "hash": "Hex digest of the value's text, with salt; skip_first keeps a clear prefix.",
20
+ "left": "The first n characters.",
21
+ "lower": "Lowercase text.",
22
+ "map_values": "Replace listed values; others become default when it is set.",
23
+ "mask": "Replace characters with char, keeping keep_first and keep_last.",
24
+ "mask_hidden": "Replace a string with value ('hidden'); string columns only.",
25
+ "mask_number": "Replace a number with value (0), in the column's own type.",
26
+ "tokenize": "Keyed HMAC-SHA256 hex digest: stable across runs, secret without the key.",
27
+ "fake": "A fake value from a Faker provider, seeded by defaults.faker (faker extra).",
28
+ "normalize_unicode": "Unicode normalisation (NFKC by default).",
29
+ "normalize_whitespace": "Collapse runs of whitespace to one space and trim.",
30
+ "null_tokens": "Null for any of the tokens (e.g. N/A, -).",
31
+ "pad": "Pad text to width with fill, on the left or right.",
32
+ "redact_date": "Keep only the year, or the year and month; the type is kept.",
33
+ "regex_extract": "A group of the first match, or null.",
34
+ "regex_replace": "Replace every match of pattern with repl.",
35
+ "remove_control_chars": "Remove control characters.",
36
+ "right": "The last n characters.",
37
+ "round": "Round half away from zero to ndigits.",
38
+ "scale": "Multiply by factor, exactly for decimals (e.g. cents to units).",
39
+ "set_null": "Always null; the column becomes nullable.",
40
+ "split": "Split text into a list of strings.",
41
+ "strip_chars": "Strip the listed characters from both ends, e.g. currency symbols.",
42
+ "substring": "length characters from start.",
43
+ "title": "Title Case text.",
44
+ "to_local": "The wall-clock time in tz, as a naive timestamp.",
45
+ "to_utc": "An aware timestamp in UTC (explicit; timestamptz output is always UTC).",
46
+ "trim": "Remove surrounding whitespace, or chars.",
47
+ "truncate": "Truncate a date or timestamp to unit.",
48
+ "upper": "Uppercase text.",
49
+ }
50
+ )
51
+ """One line per builtin, shown by ``map-conform functions``."""
52
+
53
+
54
+ @functools.cache
55
+ def builtin_registry() -> Registry:
56
+ """The builtins, registered once."""
57
+ registry = Registry()
58
+ for module in _MODULES:
59
+ module.register(registry)
60
+ for name, transform in registry.transforms.items():
61
+ if not transform.doc and name in DOCS:
62
+ registry.transforms[name] = dataclasses.replace(transform, doc=DOCS[name])
63
+ return registry
@@ -0,0 +1,310 @@
1
+ """Casts to string, boolean, uuid, binary and json (detailed design §6.4).
2
+
3
+ Every cast from a raw value first applies the value cleanup from the stream's ``values``
4
+ defaults (or the column's overrides): trim strings, then turn null tokens into null. For a
5
+ string column, ``""`` follows ``empty_string_for_string`` instead of the null tokens.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import base64
11
+ import binascii
12
+ import datetime as dt
13
+ import json
14
+ import uuid
15
+ from dataclasses import dataclass, field
16
+ from decimal import Decimal
17
+ from typing import TYPE_CHECKING, Any, Literal
18
+
19
+ from map_conform.errors import StepFailed
20
+ from map_conform.transforms.registry import RAW, TEMPORAL, Registry, Transform
21
+
22
+ if TYPE_CHECKING:
23
+ from map_conform.plan.ops import CastArgs
24
+ from map_conform.spec.model import ColumnSpec, Defaults
25
+ from map_conform.transforms.registry import Context
26
+
27
+ _EMPTY = object()
28
+ """Returned by :func:`clean` for a string column's empty string kept as empty."""
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class Cleanup:
33
+ """The value cleanup every cast from a raw value applies."""
34
+
35
+ trim: bool = True
36
+ null_tokens: tuple[str, ...] = ()
37
+ null_tokens_case_sensitive: bool = False
38
+
39
+
40
+ def cleanup_defaults(settings: Defaults, column: ColumnSpec | None) -> dict[str, Any]:
41
+ """Cleanup options from the stream defaults, overridden by the column."""
42
+ values = settings.values
43
+ return {
44
+ "trim": column.trim if column and column.trim is not None else values.trim,
45
+ "null_tokens": list(
46
+ column.null_tokens if column and column.null_tokens is not None else values.null_tokens
47
+ ),
48
+ "null_tokens_case_sensitive": values.null_tokens_case_sensitive,
49
+ }
50
+
51
+
52
+ def clean(value: object, options: Cleanup, *, keep_empty: bool = False) -> object:
53
+ """Trim a string and map null tokens to None; non-strings pass through."""
54
+ if not isinstance(value, str):
55
+ return value
56
+ text = value.strip() if options.trim else value
57
+ if text == "" and keep_empty:
58
+ return _EMPTY
59
+ if options.null_tokens_case_sensitive:
60
+ return None if text in options.null_tokens else text
61
+ folded = text.casefold()
62
+ return None if any(folded == t.casefold() for t in options.null_tokens) else text
63
+
64
+
65
+ # --- string ---------------------------------------------------------------------------------
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class StringCast(Cleanup):
70
+ """Options for casts to string."""
71
+
72
+ empty_string_for_string: Literal["keep", "null"] = "keep"
73
+ max_length: int | None = None
74
+ on_overflow: Literal["truncate", "error"] = "error"
75
+
76
+
77
+ def _string_defaults(settings: Defaults, column: ColumnSpec | None) -> dict[str, Any]:
78
+ out = cleanup_defaults(settings, column)
79
+ out["empty_string_for_string"] = settings.values.empty_string_for_string
80
+ if column is not None:
81
+ out["max_length"] = column.max_length
82
+ out["on_overflow"] = column.on_overflow
83
+ return out
84
+
85
+
86
+ def cast_string(value: object, args: CastArgs, _ctx: Context) -> object:
87
+ """Cast to string: scalars become their text; containers are refused."""
88
+ options: StringCast = args.options
89
+ cleaned = clean(value, options, keep_empty=options.empty_string_for_string == "keep")
90
+ if cleaned is _EMPTY:
91
+ return ""
92
+ if cleaned is None:
93
+ return None
94
+ if isinstance(cleaned, bool):
95
+ text = "true" if cleaned else "false"
96
+ elif isinstance(cleaned, Decimal):
97
+ text = format(cleaned, "f") # 1E+2 is written 100
98
+ elif isinstance(cleaned, (int, float, uuid.UUID)):
99
+ text = str(cleaned)
100
+ elif isinstance(cleaned, (dt.datetime, dt.date, dt.time)):
101
+ text = cleaned.isoformat() # an expression's temporal result
102
+ elif isinstance(cleaned, str):
103
+ text = cleaned
104
+ else:
105
+ raise StepFailed(f"a string column got {type(cleaned).__name__}; declare it json")
106
+ limit = args.target.length if args.target.length is not None else options.max_length
107
+ if limit is not None and len(text) > limit:
108
+ if options.on_overflow == "error":
109
+ raise StepFailed(f"{len(text)} characters is longer than {limit}")
110
+ text = text[:limit]
111
+ return text
112
+
113
+
114
+ # --- boolean --------------------------------------------------------------------------------
115
+
116
+
117
+ @dataclass(frozen=True)
118
+ class BooleanCast(Cleanup):
119
+ """Options for casts to boolean."""
120
+
121
+ true_values: tuple[str, ...] = ("true",)
122
+ false_values: tuple[str, ...] = ("false",)
123
+ case_sensitive: bool = False
124
+
125
+
126
+ def _boolean_defaults(settings: Defaults, column: ColumnSpec | None) -> dict[str, Any]:
127
+ out = cleanup_defaults(settings, column)
128
+ out["true_values"] = list(
129
+ column.true_values if column and column.true_values else settings.boolean.true_values
130
+ )
131
+ out["false_values"] = list(
132
+ column.false_values if column and column.false_values else settings.boolean.false_values
133
+ )
134
+ return out
135
+
136
+
137
+ def cast_boolean(value: object, args: CastArgs, _ctx: Context) -> object:
138
+ """Cast to boolean: listed words, real booleans, and the numbers 0 and 1."""
139
+ options: BooleanCast = args.options
140
+ cleaned = clean(value, options)
141
+ if cleaned is None or isinstance(cleaned, bool):
142
+ return cleaned
143
+ if isinstance(cleaned, (int, float, Decimal)):
144
+ if cleaned in (0, 1):
145
+ return cleaned == 1
146
+ raise StepFailed("only the numbers 0 and 1 are booleans")
147
+ if not isinstance(cleaned, str):
148
+ raise StepFailed(f"{type(cleaned).__name__} is not a boolean")
149
+ if options.case_sensitive:
150
+ if cleaned in options.true_values:
151
+ return True
152
+ if cleaned in options.false_values:
153
+ return False
154
+ else:
155
+ folded = cleaned.casefold()
156
+ if any(folded == t.casefold() for t in options.true_values):
157
+ return True
158
+ if any(folded == f.casefold() for f in options.false_values):
159
+ return False
160
+ raise StepFailed("not one of the true_values or false_values")
161
+
162
+
163
+ # --- uuid -----------------------------------------------------------------------------------
164
+
165
+
166
+ @dataclass(frozen=True)
167
+ class UuidCast(Cleanup):
168
+ """Options for casts to uuid."""
169
+
170
+ version: int | None = None
171
+
172
+
173
+ def cast_uuid(value: object, args: CastArgs, _ctx: Context) -> object:
174
+ """Cast to uuid: braces, missing dashes and capitals are accepted."""
175
+ options: UuidCast = args.options
176
+ cleaned = clean(value, options)
177
+ if cleaned is None or isinstance(cleaned, uuid.UUID):
178
+ return cleaned
179
+ try:
180
+ parsed = uuid.UUID(str(cleaned))
181
+ except ValueError as exc:
182
+ raise StepFailed("not a UUID") from exc
183
+ if options.version is not None and parsed.version != options.version:
184
+ raise StepFailed(f"a version {parsed.version} UUID, not version {options.version}")
185
+ return parsed
186
+
187
+
188
+ # --- binary ---------------------------------------------------------------------------------
189
+
190
+
191
+ @dataclass(frozen=True)
192
+ class BinaryCast(Cleanup):
193
+ """Options for casts to binary."""
194
+
195
+ encoding: Literal["base64", "hex", "utf8"] = "base64"
196
+
197
+
198
+ def cast_binary(value: object, args: CastArgs, _ctx: Context) -> object:
199
+ """Cast to binary from strict base64, hex or UTF-8 text."""
200
+ options: BinaryCast = args.options
201
+ cleaned = clean(value, options)
202
+ if cleaned is None or isinstance(cleaned, bytes):
203
+ return cleaned
204
+ text = str(cleaned)
205
+ try:
206
+ if options.encoding == "base64":
207
+ return base64.b64decode(text, validate=True)
208
+ if options.encoding == "hex":
209
+ return bytes.fromhex(text)
210
+ except (binascii.Error, ValueError) as exc:
211
+ raise StepFailed(f"not valid {options.encoding}") from exc
212
+ return text.encode("utf-8")
213
+
214
+
215
+ # --- json -----------------------------------------------------------------------------------
216
+
217
+
218
+ @dataclass(frozen=True)
219
+ class JsonCast:
220
+ """Options for casts to json (no value cleanup: text is data here)."""
221
+
222
+ parse_strings: bool = True
223
+ sort_keys: bool = False
224
+ null_tokens: tuple[str, ...] = field(default=())
225
+
226
+
227
+ def cast_json(value: object, args: CastArgs, _ctx: Context) -> object:
228
+ """Cast to json: text that is already JSON is decoded, not encoded twice.
229
+
230
+ Decimals stay exact; the value is encoded as JSON text on the wire.
231
+ """
232
+ options: JsonCast = args.options
233
+ if isinstance(value, str):
234
+ if value in options.null_tokens:
235
+ return None
236
+ if options.parse_strings:
237
+ try:
238
+ value = json.loads(value, parse_float=Decimal)
239
+ except json.JSONDecodeError:
240
+ return value
241
+ if options.sort_keys and isinstance(value, dict):
242
+ return dict(sorted(value.items()))
243
+ return value
244
+
245
+
246
+ def register(registry: Registry) -> None:
247
+ """Add these casts."""
248
+ registry.register_cast(
249
+ {"string"},
250
+ Transform(
251
+ "cast",
252
+ cast_string,
253
+ kwargs=StringCast,
254
+ defaults=_string_defaults,
255
+ accepts=frozenset(
256
+ {
257
+ RAW,
258
+ "string",
259
+ "boolean",
260
+ "int16",
261
+ "int32",
262
+ "int64",
263
+ "float32",
264
+ "float64",
265
+ "decimal",
266
+ "uuid",
267
+ *TEMPORAL,
268
+ }
269
+ ),
270
+ ),
271
+ )
272
+ registry.register_cast(
273
+ {"boolean"},
274
+ Transform(
275
+ "cast",
276
+ cast_boolean,
277
+ kwargs=BooleanCast,
278
+ defaults=_boolean_defaults,
279
+ accepts=frozenset({RAW, "string", "boolean"}),
280
+ ),
281
+ )
282
+ registry.register_cast(
283
+ {"uuid"},
284
+ Transform(
285
+ "cast",
286
+ cast_uuid,
287
+ kwargs=UuidCast,
288
+ defaults=cleanup_defaults,
289
+ accepts=frozenset({RAW, "string", "uuid"}),
290
+ ),
291
+ )
292
+ registry.register_cast(
293
+ {"binary"},
294
+ Transform(
295
+ "cast",
296
+ cast_binary,
297
+ kwargs=BinaryCast,
298
+ defaults=cleanup_defaults,
299
+ accepts=frozenset({RAW, "string", "binary"}),
300
+ ),
301
+ )
302
+ registry.register_cast(
303
+ {"json"},
304
+ Transform(
305
+ "cast",
306
+ cast_json,
307
+ kwargs=JsonCast,
308
+ accepts=frozenset({RAW, "string", "json"}),
309
+ ),
310
+ )
@@ -0,0 +1,150 @@
1
+ """Fake data: the ``fake`` step and the ``fake`` object in expressions (WBS 12.4).
2
+
3
+ Both need the ``faker`` extra (``pip install map-conform[faker]``). ``defaults.faker`` sets
4
+ the seed and locale, the same as the SDK's ``faker_config``: with a seed, ``Faker.seed`` is
5
+ called before the generator is created, exactly as the SDK does, so seeded runs give the same
6
+ values in the same order, and the same values the SDK mapper gives.
7
+
8
+ The generator is created on first use, so a stream that never fakes anything never imports
9
+ Faker. In expressions, ``fake`` is a sandbox proxy: provider methods (``fake.email()``) and
10
+ ``fake.seed_instance(value)`` are allowed; private names, ``seed`` (global seeding) and
11
+ ``add_provider`` are not.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import functools
17
+ import importlib.util
18
+ import sys
19
+ from dataclasses import dataclass
20
+ from typing import TYPE_CHECKING, Any
21
+
22
+ from map_conform.errors import StepFailed
23
+ from map_conform.expr.sandbox import Proxy, SandboxError
24
+ from map_conform.spec._struct import documented
25
+ from map_conform.transforms.registry import ANY, Registry, Transform
26
+
27
+ if sys.version_info >= (3, 12):
28
+ from typing import override
29
+ else:
30
+ from typing_extensions import override
31
+
32
+ if TYPE_CHECKING:
33
+ from map_conform.spec.model import FakerDefaults
34
+ from map_conform.transforms.registry import Context
35
+
36
+ NEEDS_EXTRA = "fake needs the faker extra: pip install 'map-conform[faker]'"
37
+ _DENIED = frozenset({"seed", "add_provider", "seed_locale", "factories", "random"})
38
+
39
+
40
+ def available() -> bool:
41
+ """Whether Faker is installed."""
42
+ return importlib.util.find_spec("faker") is not None
43
+
44
+
45
+ class FakeData(Proxy):
46
+ """A lazily created, seeded Faker generator."""
47
+
48
+ __slots__ = ("_faker", "_locale", "_seed")
49
+
50
+ def __init__(
51
+ self, seed: int | None = None, locale: str | tuple[str, ...] | None = None
52
+ ) -> None:
53
+ """Remember the settings; Faker is imported on first use."""
54
+ self._seed = seed
55
+ self._locale = locale
56
+ self._faker: Any = None
57
+
58
+ @classmethod
59
+ def from_settings(cls, settings: FakerDefaults) -> FakeData:
60
+ """From ``defaults.faker``."""
61
+ return cls(settings.seed, settings.locale)
62
+
63
+ def generator(self) -> Any: # noqa: ANN401 -- a faker.Faker
64
+ """The Faker instance, created (and seeded) on first use.
65
+
66
+ Raises:
67
+ SandboxError: when Faker is not installed.
68
+ """
69
+ if self._faker is None:
70
+ if not available():
71
+ raise SandboxError(NEEDS_EXTRA)
72
+ from faker import Faker # noqa: PLC0415 -- optional dependency
73
+
74
+ if self._seed is not None:
75
+ Faker.seed(self._seed) # as the SDK seeds, for the same values
76
+ locale = list(self._locale) if isinstance(self._locale, tuple) else self._locale
77
+ self._faker = Faker(locale) if locale is not None else Faker()
78
+ return self._faker
79
+
80
+ @override
81
+ def attribute(self, name: str) -> object:
82
+ """A provider method or ``seed_instance``.
83
+
84
+ Raises:
85
+ SandboxError: for private and global-state names.
86
+ """
87
+ if name.startswith("_") or name in _DENIED:
88
+ msg = f"fake.{name} is not available in expressions"
89
+ raise SandboxError(msg)
90
+ return getattr(self.generator(), name)
91
+
92
+ @override
93
+ def __repr__(self) -> str:
94
+ """``<fake seed=1 locale=en_US>``."""
95
+ return f"<fake seed={self._seed} locale={self._locale}>"
96
+
97
+
98
+ @functools.cache
99
+ def _providers(locale: str | None) -> frozenset[str]:
100
+ from faker import Faker # noqa: PLC0415 -- optional dependency
101
+
102
+ fake = Faker(locale) if locale else Faker()
103
+ return frozenset(name for name in dir(fake) if not name.startswith("_"))
104
+
105
+
106
+ def _provider_problem(provider: str) -> str | None:
107
+ if not available():
108
+ return NEEDS_EXTRA
109
+ if provider.startswith("_") or provider in _DENIED or provider not in _providers(None):
110
+ return f"{provider!r} is not a Faker provider"
111
+ return None
112
+
113
+
114
+ @dataclass(frozen=True)
115
+ class FakeKwargs:
116
+ """fake options."""
117
+
118
+ provider: str = documented(
119
+ "A Faker provider, e.g. name, email, credit_card_number.",
120
+ metadata={"check": _provider_problem},
121
+ )
122
+ args: tuple[Any, ...] = documented("Positional arguments for the provider.", default=())
123
+ unique: bool = documented("Never repeat a value within the run.", default=False)
124
+
125
+
126
+ def _fake(_value: object, k: FakeKwargs, ctx: Context) -> object:
127
+ if ctx.fake is None:
128
+ raise StepFailed("fake is not available here")
129
+ try:
130
+ generator = ctx.fake.generator()
131
+ source = generator.unique if k.unique else generator
132
+ return getattr(source, k.provider)(*k.args)
133
+ except SandboxError as exc:
134
+ raise StepFailed(str(exc)) from None
135
+ except Exception as exc: # noqa: BLE001 -- e.g. Faker's UniquenessException
136
+ raise StepFailed(f"{type(exc).__name__}: {exc}") from None
137
+
138
+
139
+ def register(registry: Registry) -> None:
140
+ """Add the fake step."""
141
+ registry.register(
142
+ Transform(
143
+ "fake",
144
+ _fake,
145
+ kwargs=FakeKwargs,
146
+ positional="provider",
147
+ accepts=frozenset({ANY}),
148
+ produces=lambda _stage, _k: None,
149
+ )
150
+ )
@@ -0,0 +1,111 @@
1
+ """Casts to struct and list (declared nested types and ``nested: keep``).
2
+
3
+ The value is a mapping (struct) or a list, or JSON text holding one. Members are cast
4
+ recursively by their declared types with neutral options: nested values are data, so they are
5
+ not trimmed and have no null tokens; temporal members are ISO. Members missing from the value
6
+ are null; keys the struct does not declare are dropped, since the declared shape wins. The
7
+ executor renames nested keys to their conformed names before this cast runs.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ from collections.abc import Callable, Mapping
14
+ from dataclasses import dataclass
15
+ from decimal import Decimal
16
+ from typing import TYPE_CHECKING, Any
17
+
18
+ from map_conform.errors import StepFailed
19
+ from map_conform.transforms import casts, numeric, temporal
20
+ from map_conform.transforms.registry import RAW, Registry, Transform
21
+ from map_conform.types.canonical import CType
22
+
23
+ if TYPE_CHECKING:
24
+ from map_conform.plan.ops import CastArgs
25
+ from map_conform.transforms.registry import Context
26
+
27
+ _NUMBER = numeric.NumberCast(trim=False)
28
+ _STRING = casts.StringCast(trim=False)
29
+ _BOOLEAN = casts.BooleanCast(trim=False)
30
+ _UUID = casts.UuidCast(trim=False)
31
+ _BINARY = casts.BinaryCast(trim=False)
32
+ _TEMPORAL = temporal.TemporalCast(trim=False)
33
+ _JSON = casts.JsonCast(parse_strings=False)
34
+
35
+ _MEMBER_CASTS: dict[str, tuple[Callable[..., Any], Any]] = {
36
+ **dict.fromkeys(("int16", "int32", "int64"), (numeric.cast_int, _NUMBER)),
37
+ **dict.fromkeys(("float32", "float64"), (numeric.cast_float, _NUMBER)),
38
+ "decimal": (numeric.cast_decimal, _NUMBER),
39
+ "string": (casts.cast_string, _STRING),
40
+ "boolean": (casts.cast_boolean, _BOOLEAN),
41
+ "uuid": (casts.cast_uuid, _UUID),
42
+ "binary": (casts.cast_binary, _BINARY),
43
+ "json": (casts.cast_json, _JSON),
44
+ **dict.fromkeys(
45
+ ("date", "time", "timestamp", "timestamptz"), (temporal.cast_temporal, _TEMPORAL)
46
+ ),
47
+ }
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class NestedCast:
52
+ """Options for casts to struct and list."""
53
+
54
+ parse_strings: bool = True
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class _MemberArgs:
59
+ target: CType
60
+ options: Any
61
+
62
+
63
+ def cast_member(value: object, target: CType, ctx: Context) -> object:
64
+ """Cast one nested value to its declared type."""
65
+ if value is None:
66
+ return None
67
+ if target.kind in ("struct", "list"):
68
+ return _cast_nested(value, target, ctx, parse_strings=False)
69
+ caster, options = _MEMBER_CASTS[target.kind]
70
+ return caster(value, _MemberArgs(target, options), ctx)
71
+
72
+
73
+ def _cast_nested(value: object, target: CType, ctx: Context, *, parse_strings: bool) -> object:
74
+ if isinstance(value, str) and parse_strings:
75
+ try:
76
+ value = json.loads(value, parse_float=Decimal)
77
+ except json.JSONDecodeError as exc:
78
+ raise StepFailed(f"not JSON for a {target.kind}") from exc
79
+ if target.kind == "struct":
80
+ if not isinstance(value, Mapping):
81
+ raise StepFailed(f"a struct needs an object, got {type(value).__name__}")
82
+ out: dict[str, object] = {}
83
+ for name, member in target.members:
84
+ try:
85
+ out[name] = cast_member(value.get(name), member, ctx)
86
+ except StepFailed as exc:
87
+ raise StepFailed(f"member {name!r}: {exc.reason}") from exc
88
+ return out
89
+ if not isinstance(value, list):
90
+ raise StepFailed(f"a list needs an array, got {type(value).__name__}")
91
+ item = target.list_item
92
+ result: list[object] = []
93
+ for index, element in enumerate(value):
94
+ try:
95
+ result.append(cast_member(element, item, ctx))
96
+ except StepFailed as exc:
97
+ raise StepFailed(f"item {index}: {exc.reason}") from exc
98
+ return result
99
+
100
+
101
+ def cast_nested(value: object, args: CastArgs, ctx: Context) -> object:
102
+ """Cast to a struct or list."""
103
+ options: NestedCast = args.options
104
+ return _cast_nested(value, args.target, ctx, parse_strings=options.parse_strings)
105
+
106
+
107
+ def register(registry: Registry) -> None:
108
+ """Add the struct and list casts."""
109
+ accepts = frozenset({RAW, "string", "json", "struct", "list"})
110
+ transform = Transform("cast", cast_nested, kwargs=NestedCast, accepts=accepts)
111
+ registry.register_cast({"struct", "list"}, transform)