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,551 @@
1
+ """Compile a stream's plan at SCHEMA time (detailed design §9).
2
+
3
+ A :class:`StreamPlan` holds everything the executors need, already validated: the output
4
+ stream name, ordered :class:`ColumnPlan` objects (output name, CType, sources, compiled
5
+ chain, nullability, on_error, default, enum), the order in which columns are computed (a
6
+ column whose expressions read other columns comes after them), the compiled ``filter``, the
7
+ renamed key and bookmark properties, and the output JSON Schema and Arrow schema. Problems are
8
+ collected, each with its spec path, and raised together as a
9
+ :class:`~map_conform.spec.errors.SpecError`.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import dataclasses
15
+ from collections.abc import Mapping
16
+ from dataclasses import dataclass, field
17
+ from types import MappingProxyType
18
+ from typing import TYPE_CHECKING, Any, Literal
19
+
20
+ import pyarrow as pa
21
+
22
+ from map_conform.errors import OnError
23
+ from map_conform.expr.compiler import ExprError, Expression, Names, compile_expr
24
+ from map_conform.naming.conform import NameConformer, NamingError
25
+ from map_conform.naming.flatten import Flattener, FlattenError
26
+ from map_conform.naming.nested import MemberNames, conform_ctype
27
+ from map_conform.naming.shape import Shape
28
+ from map_conform.naming.streams import stream_name
29
+ from map_conform.plan.chain import ChainCompiler
30
+ from map_conform.plan.ops import CompiledChain, StepError
31
+ from map_conform.plan.vector import VectorChain, vector_chain
32
+ from map_conform.spec._struct import Issues, child, freeze, freeze_mapping, thaw, thaw_mapping
33
+ from map_conform.spec.check import Finding, OutputColumn, output_columns
34
+ from map_conform.spec.errors import SpecError
35
+ from map_conform.spec.load import ResolvedStream
36
+ from map_conform.spec.model import ColumnSpec
37
+ from map_conform.spec.stream_maps import sdk_type
38
+ from map_conform.transforms.fake import FakeData
39
+ from map_conform.transforms.polars_vector import available as polars_available
40
+ from map_conform.transforms.registry import Context
41
+ from map_conform.types.canonical import CType, CTypeError, parse_ctype
42
+ from map_conform.types.from_jsonschema import from_jsonschema
43
+ from map_conform.types.to_arrow import to_arrow
44
+ from map_conform.types.to_jsonschema import to_jsonschema
45
+ from map_conform.types.wire import to_wire
46
+
47
+ if TYPE_CHECKING:
48
+ from map_conform.spec.model import Spec
49
+ from map_conform.transforms.registry import Registry
50
+
51
+ _KEEP_KINDS = frozenset({"string", "json"})
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class ColumnPlan:
56
+ """How one output column is produced."""
57
+
58
+ name: str
59
+ ctype: CType
60
+ sources: tuple[str, ...]
61
+ """Source properties; the first non-null one is used."""
62
+ chain: CompiledChain
63
+ nullable: bool
64
+ on_error: OnError
65
+ default: Any = None
66
+ """The typed default for a missing or null result."""
67
+ enum: frozenset[Any] | None = None
68
+ """Allowed wire values, when the column restricts them."""
69
+ member_names: MemberNames | None = None
70
+ """Renames nested struct members in values."""
71
+ declared: bool = True
72
+ key: str = ""
73
+ """The spec's ``columns`` key, or the source name of an undeclared column."""
74
+ doc: str | None = None
75
+ sql_type: str | None = None
76
+ vector: VectorChain | None = None
77
+ """The chain as Arrow ops, for the columnar executor; None runs it row by row."""
78
+ engine: str = "arrow"
79
+ """The vectorised engine: arrow, or polars."""
80
+
81
+ @property
82
+ def steps(self) -> tuple[str, ...]:
83
+ """The chain's step rules, for explain output."""
84
+ return tuple(step.rule for step in self.chain.steps)
85
+
86
+ @property
87
+ def reads(self) -> frozenset[str]:
88
+ """Columns the chain's expressions read, by output name."""
89
+ return self.chain.reads
90
+
91
+
92
+ @dataclass(frozen=True)
93
+ class StreamPlan:
94
+ """A compiled stream: output name, columns and schemas."""
95
+
96
+ tap_stream: str
97
+ name: str
98
+ columns: tuple[ColumnPlan, ...]
99
+ key_properties: tuple[str, ...]
100
+ bookmark_properties: tuple[str, ...]
101
+ schema: dict[str, Any]
102
+ arrow_schema: pa.Schema
103
+ notes: tuple[str, ...] = field(default=())
104
+ """Lossy renames and type warnings, logged once per stream."""
105
+ order: tuple[int, ...] = field(default=())
106
+ """Indexes into ``columns`` in the order they are computed: dependencies first."""
107
+ filter: Expression | None = None
108
+ """Rows where this is falsy are dropped; it sees every column by output name."""
109
+ fake: FakeData | None = None
110
+ """The stream's fake-data generator (created on first use)."""
111
+ flattener: Flattener | None = None
112
+ """For ``nested: flatten``: flattens each record as the SCHEMA was."""
113
+ flat_properties: Mapping[str, Any] = field(default_factory=dict)
114
+ """The flattened tap SCHEMA properties the records are flattened against."""
115
+ shaped: tuple[ShapedFlattening, ...] = ()
116
+ """Columns flattened from their declared shapes."""
117
+
118
+
119
+ def compile_stream( # noqa: PLR0913 -- the SCHEMA message's parts, plus the spec context
120
+ spec: Spec,
121
+ resolved: ResolvedStream,
122
+ tap_schema: Mapping[str, Any],
123
+ registry: Registry,
124
+ *,
125
+ key_properties: tuple[str, ...] = (),
126
+ bookmark_properties: tuple[str, ...] = (),
127
+ strict: bool = False,
128
+ config: Mapping[str, Any] | None = None,
129
+ ) -> StreamPlan:
130
+ """Compile the plan for one output stream from its tap SCHEMA.
131
+
132
+ Raises:
133
+ SpecError: listing every problem, each with its spec path.
134
+ """
135
+ if strict and resolved.settings.undeclared != "error":
136
+ settings = dataclasses.replace(resolved.settings, undeclared="error")
137
+ resolved = dataclasses.replace(resolved, settings=settings)
138
+ path = child("streams", resolved.key or resolved.tap_stream)
139
+ issues = Issues()
140
+ notes: list[str] = []
141
+ try:
142
+ named = stream_name(resolved)
143
+ except NamingError as exc:
144
+ issues.add(path, exc.reason)
145
+ named = None
146
+ notes.extend(f"stream name: {n}" for n in (named.notes if named else ()))
147
+ properties: Mapping[str, Any] = tap_schema.get("properties") or {}
148
+ resolved, properties, shaped = _flatten_shapes(resolved, properties, issues, path)
149
+ flattener = _flattener(resolved) if resolved.settings.nested == "flatten" else None
150
+ if flattener is not None:
151
+ try:
152
+ properties = flattener.properties(properties)
153
+ except FlattenError as exc:
154
+ issues.add(child(path, "nested"), str(exc))
155
+ findings: list[Finding] = []
156
+ columns = output_columns(resolved, properties, findings, path, key_properties)
157
+ for finding in findings:
158
+ if finding.severity == "error":
159
+ issues.add(finding.path, finding.message)
160
+ fake = FakeData.from_settings(resolved.settings.faker)
161
+ scope = Names(
162
+ columns=frozenset(c.name for c in columns),
163
+ constants={
164
+ "config": freeze_mapping(dict(config or {})),
165
+ "stream": named.name if named else resolved.tap_stream,
166
+ "source_stream": resolved.tap_stream,
167
+ "fake": fake,
168
+ },
169
+ )
170
+ compiler = ChainCompiler(
171
+ registry, resolved.settings, spec.macros, issues, scope, resolved.tap_stream
172
+ )
173
+ builder = _ColumnBuilder(resolved, properties, compiler, issues, notes, path)
174
+ plans = [plan for column in columns if (plan := builder.build(column)) is not None]
175
+ order = _order(plans, issues, path)
176
+ row_filter = _filter(resolved.spec.filter, scope, issues, path)
177
+ read = frozenset().union(*(p.reads for p in plans), row_filter.reads if row_filter else ())
178
+ plans = [dataclasses.replace(p, vector=vector_chain(p, read)) for p in plans]
179
+ renamed = _renamer(columns)
180
+ keys = _keys(resolved, key_properties, renamed, issues, path)
181
+ bookmarks = tuple(renamed.get(b, b) for b in bookmark_properties)
182
+ if issues or named is None:
183
+ raise SpecError(issues.items, f"the plan for stream {resolved.tap_stream!r}")
184
+ return StreamPlan(
185
+ tap_stream=resolved.tap_stream,
186
+ name=named.name,
187
+ columns=tuple(plans),
188
+ key_properties=keys,
189
+ bookmark_properties=bookmarks,
190
+ schema=_output_schema(plans),
191
+ arrow_schema=pa.schema(
192
+ [pa.field(p.name, to_arrow(p.ctype), nullable=p.nullable) for p in plans]
193
+ ),
194
+ notes=tuple(notes),
195
+ order=order,
196
+ filter=row_filter,
197
+ fake=fake,
198
+ flattener=flattener,
199
+ flat_properties=dict(properties) if flattener is not None else {},
200
+ shaped=tuple(shaped),
201
+ )
202
+
203
+
204
+ @dataclass(frozen=True)
205
+ class ShapedFlattening:
206
+ """A column flattened from its declared shape: the executor conforms and flattens it."""
207
+
208
+ key: str
209
+ """The spec's column key, for counts and logs."""
210
+ source: str
211
+ shape: Shape
212
+ flattener: Flattener
213
+ leaves: Mapping[str, Any]
214
+
215
+
216
+ def _flatten_shapes(
217
+ resolved: ResolvedStream, properties: Mapping[str, Any], issues: Issues, path: str
218
+ ) -> tuple[ResolvedStream, Mapping[str, Any], list[ShapedFlattening]]:
219
+ """Replace each flattened shaped column by its leaf columns, typed from the shape."""
220
+ settings = resolved.settings
221
+ columns: dict[str, ColumnSpec] = {}
222
+ props = dict(properties)
223
+ shaped: list[ShapedFlattening] = []
224
+ declared = resolved.spec.columns
225
+ for key, spec in declared.items():
226
+ flatten = spec.flatten if spec.flatten is not None else settings.nested == "flatten"
227
+ if spec.shape is None or not flatten or spec.drop:
228
+ columns.setdefault(key, spec)
229
+ continue
230
+ col_path = child(child(path, "columns"), key)
231
+ if spec.source is not None and not isinstance(spec.source, str):
232
+ issues.add(child(col_path, "source"), "a flattened shape reads one source")
233
+ continue
234
+ source = spec.source or key
235
+ options = settings.flatten
236
+ flattener = Flattener(options.separator, options.max_depth, options.max_key_length,
237
+ frozenset(), typed_leaves=True) # fmt: skip
238
+ schema = thaw_mapping(spec.shape)
239
+ try:
240
+ leaves = flattener.properties({source: schema})
241
+ except FlattenError as exc:
242
+ issues.add(child(col_path, "shape"), str(exc))
243
+ continue
244
+ for leaf, leaf_schema in leaves.items():
245
+ columns[leaf] = _leaf_spec(declared.get(leaf), leaf_schema)
246
+ props = _replace(props, source, leaves)
247
+ shaped.append(ShapedFlattening(key, source, Shape.of(schema), flattener, leaves))
248
+ if not shaped:
249
+ return resolved, properties, []
250
+ stream = dataclasses.replace(resolved.spec, columns=MappingProxyType(columns))
251
+ return dataclasses.replace(resolved, spec=stream), props, shaped
252
+
253
+
254
+ def _leaf_spec(own: ColumnSpec | None, schema: Mapping[str, Any]) -> ColumnSpec:
255
+ """A leaf column: the type and default from the shape, the rest from a spec of its own."""
256
+ inferred = from_jsonschema(schema, "keep")
257
+ base = own or ColumnSpec()
258
+ changes: dict[str, Any] = {}
259
+ if base.type is None: # nullable stays: a member may be missing from any record
260
+ changes["type"] = str(inferred.ctype)
261
+ if base.default is None and "default" in schema:
262
+ changes["default"] = freeze(schema["default"])
263
+ return dataclasses.replace(base, **changes)
264
+
265
+
266
+ def _replace(properties: dict[str, Any], name: str, leaves: Mapping[str, Any]) -> dict[str, Any]:
267
+ """Properties with ``name`` replaced, in place, by the leaf properties."""
268
+ out: dict[str, Any] = {}
269
+ for key, value in properties.items():
270
+ if key == name:
271
+ out.update(leaves)
272
+ elif key not in leaves:
273
+ out[key] = value
274
+ for key, value in leaves.items():
275
+ out.setdefault(key, value)
276
+ return out
277
+
278
+
279
+ def _flattener(resolved: ResolvedStream) -> Flattener:
280
+ """SDK flattening for the properties the spec does not name itself."""
281
+ named = set(resolved.spec.columns)
282
+ for spec in resolved.spec.columns.values():
283
+ if isinstance(spec.source, str):
284
+ named.add(spec.source)
285
+ elif spec.source is not None:
286
+ named.update(spec.source)
287
+ options = resolved.settings.flatten
288
+ return Flattener(options.separator, options.max_depth, options.max_key_length, frozenset(named))
289
+
290
+
291
+ def _filter(text: str | None, scope: Names, issues: Issues, path: str) -> Expression | None:
292
+ if text is None:
293
+ return None
294
+ try:
295
+ return compile_expr(text, dataclasses.replace(scope, value=False))
296
+ except ExprError as exc:
297
+ issues.add(child(path, "filter"), str(exc))
298
+ return None
299
+
300
+
301
+ def _order(plans: list[ColumnPlan], issues: Issues, path: str) -> tuple[int, ...]:
302
+ """Column indexes with every column after the columns it reads; cycles are errors."""
303
+ index = {plan.name: i for i, plan in enumerate(plans)}
304
+ done: list[int] = []
305
+ state: dict[int, str] = {}
306
+
307
+ def visit(i: int, trail: tuple[int, ...]) -> bool:
308
+ if state.get(i) == "done":
309
+ return True
310
+ if state.get(i) == "visiting":
311
+ cycle = [plans[j].name for j in trail[trail.index(i) :]] + [plans[i].name]
312
+ issues.add(
313
+ child(child(path, "columns"), plans[i].key),
314
+ f"dependency cycle: {' -> '.join(cycle)}",
315
+ )
316
+ return False
317
+ state[i] = "visiting"
318
+ deps = sorted(index[name] for name in plans[i].reads if name in index)
319
+ ok = all(visit(j, (*trail, i)) for j in deps)
320
+ state[i] = "done"
321
+ if ok:
322
+ done.append(i)
323
+ return ok
324
+
325
+ for i in range(len(plans)):
326
+ if not visit(i, ()):
327
+ return tuple(range(len(plans)))
328
+ return tuple(done)
329
+
330
+
331
+ @dataclass
332
+ class _ColumnBuilder:
333
+ resolved: ResolvedStream
334
+ properties: Mapping[str, Any]
335
+ compiler: ChainCompiler
336
+ issues: Issues
337
+ notes: list[str]
338
+ path: str
339
+
340
+ def build(self, column: OutputColumn) -> ColumnPlan | None:
341
+ spec = column.spec
342
+ col_path = child(child(self.path, "columns"), column.key)
343
+ before = len(self.issues.items)
344
+ notes = [f"column {column.key!r} -> {column.name!r}: {n}" for n in column.notes]
345
+ ctype, tap_nullable = self._ctype(column, col_path, notes)
346
+ if ctype is None or len(self.issues.items) != before:
347
+ return None
348
+ naming = NameConformer(self.resolved.settings.naming)
349
+ try:
350
+ ctype, member_names = conform_ctype(ctype, naming)
351
+ except NamingError as exc:
352
+ self.issues.add(col_path, f"nested member: {exc}")
353
+ return None
354
+ chain = self.compiler.compile_column(spec, ctype, col_path, own=column.name)
355
+ if chain is None:
356
+ return None
357
+ nullable = self._nullable(spec, chain, tap_nullable=tap_nullable, col_path=col_path)
358
+ on_error = self._on_error(spec, ctype, col_path)
359
+ default = self._typed(spec.default, chain, col_path, "default") if spec else None
360
+ enum = self._enum(spec, chain, col_path)
361
+ if len(self.issues.items) != before:
362
+ return None
363
+ self.notes.extend(notes)
364
+ return ColumnPlan(
365
+ name=column.name,
366
+ ctype=ctype,
367
+ sources=column.sources,
368
+ chain=chain,
369
+ nullable=nullable,
370
+ on_error=on_error,
371
+ default=default,
372
+ enum=enum,
373
+ member_names=member_names,
374
+ declared=spec is not None,
375
+ key=column.key,
376
+ doc=spec.doc if spec else None,
377
+ sql_type=spec.sql_type if spec else None,
378
+ engine=self._engine(spec, col_path),
379
+ )
380
+
381
+ def _ctype(
382
+ self, column: OutputColumn, col_path: str, notes: list[str]
383
+ ) -> tuple[CType | None, bool]:
384
+ spec = column.spec
385
+ if spec is not None and spec.type is not None:
386
+ try:
387
+ return parse_ctype(spec.type), True
388
+ except CTypeError as exc: # already reported by the spec parser; be safe
389
+ self.issues.add(child(col_path, "type"), str(exc))
390
+ return None, True
391
+ if spec is not None and spec.infer_type == "sdk" and spec.expr is not None:
392
+ return self._sdk_type(column, spec.expr, notes)
393
+ if spec is not None and spec.shape is not None: # the declared shape, never the tap's
394
+ return from_jsonschema(thaw_mapping(spec.shape), "keep").ctype, True
395
+ if column.tap_schema is None:
396
+ self.issues.add(
397
+ col_path, "declare its type: the tap SCHEMA has no single source property for it"
398
+ )
399
+ return None, True
400
+ nested = self.resolved.settings.nested
401
+ inferred = from_jsonschema(column.tap_schema, _shape(nested))
402
+ notes.extend(f"column {column.key!r}: {w}" for w in inferred.warnings)
403
+ return inferred.ctype, inferred.nullable
404
+
405
+ def _sdk_type(
406
+ self, column: OutputColumn, expr: str, notes: list[str]
407
+ ) -> tuple[CType | None, bool]:
408
+ """The SDK mapper's prefix inference (WBS 12.2), with a note suggesting a type."""
409
+ dropped = self.resolved.settings.undeclared == "drop"
410
+ ctype, schema = sdk_type(expr, column.key, self.properties, undeclared_dropped=dropped)
411
+ nullable = True
412
+ if ctype is None and schema is not None:
413
+ nested = self.resolved.settings.nested
414
+ inferred = from_jsonschema(schema, _shape(nested))
415
+ ctype, nullable = inferred.ctype, inferred.nullable
416
+ notes.append(
417
+ f"column {column.key!r}: type {ctype} inferred from its expression as the SDK "
418
+ "does; declare type to make it explicit"
419
+ )
420
+ return ctype, nullable
421
+
422
+ def _nullable(
423
+ self, spec: ColumnSpec | None, chain: CompiledChain, *, tap_nullable: bool, col_path: str
424
+ ) -> bool:
425
+ forced = chain.forces_nullable
426
+ if spec is None:
427
+ return tap_nullable or forced
428
+ if forced and not spec.nullable:
429
+ self.issues.add(child(col_path, "nullable"), "set_null makes the column nullable")
430
+ return spec.nullable or forced
431
+
432
+ def _engine(self, spec: ColumnSpec | None, col_path: str) -> str:
433
+ engine = spec.engine if spec and spec.engine else self.resolved.settings.engine
434
+ if engine == "polars" and not polars_available():
435
+ where = (
436
+ child(col_path, "engine") if spec and spec.engine else child(self.path, "engine")
437
+ )
438
+ self.issues.add(
439
+ where, "engine: polars needs the polars extra: pip install 'map-conform[polars]'"
440
+ )
441
+ return "arrow"
442
+ return engine
443
+
444
+ def _on_error(self, spec: ColumnSpec | None, ctype: CType, col_path: str) -> OnError:
445
+ policy = spec.on_error if spec and spec.on_error else self.resolved.settings.on_error
446
+ if policy == "keep" and ctype.kind not in _KEEP_KINDS:
447
+ self.issues.add(
448
+ child(col_path, "on_error"),
449
+ f"keep would put raw text in a {ctype} column; use it only for string or json",
450
+ )
451
+ return policy
452
+
453
+ def _typed(self, value: object, chain: CompiledChain, col_path: str, what: str) -> object:
454
+ if value is None:
455
+ return None
456
+ ctx = Context(self.resolved.tap_stream, col_path, self.resolved.settings, chain.target)
457
+ try:
458
+ return chain.run(thaw(value), ctx)
459
+ except StepError as exc:
460
+ self.issues.add(
461
+ child(col_path, what),
462
+ f"{value!r} does not pass the column's chain: {exc.cell.rule}: {exc.cell.reason}",
463
+ )
464
+ return None
465
+
466
+ def _enum(
467
+ self, spec: ColumnSpec | None, chain: CompiledChain, col_path: str
468
+ ) -> frozenset[Any] | None:
469
+ if spec is None or spec.enum is None:
470
+ return None
471
+ allowed = {
472
+ to_wire(self._typed(v, chain, col_path, "enum"), chain.target) for v in spec.enum
473
+ }
474
+ return frozenset(_hashable(v) for v in allowed)
475
+
476
+
477
+ def _shape(nested: str) -> Literal["keep", "json"]:
478
+ """How an object property is typed.
479
+
480
+ Flattening has already turned objects below its depth into JSON text, so the objects left
481
+ (at depth 0) keep their shape, as in the SDK.
482
+ """
483
+ return "json" if nested == "json" else "keep"
484
+
485
+
486
+ def _hashable(value: object) -> object:
487
+ return value if isinstance(value, (str, int, float, bool, type(None))) else repr(value)
488
+
489
+
490
+ def _renamer(columns: list[OutputColumn]) -> dict[str, str]:
491
+ """Source property (and output name) -> output name."""
492
+ out: dict[str, str] = {}
493
+ for column in columns:
494
+ out[column.name] = column.name
495
+ for source in column.sources:
496
+ out.setdefault(source, column.name)
497
+ return out
498
+
499
+
500
+ def _keys(
501
+ resolved: ResolvedStream,
502
+ tap_keys: tuple[str, ...],
503
+ renamed: Mapping[str, str],
504
+ issues: Issues,
505
+ path: str,
506
+ ) -> tuple[str, ...]:
507
+ keys = resolved.spec.key_properties if resolved.spec.key_properties is not None else tap_keys
508
+ out: list[str] = []
509
+ for key in keys:
510
+ if key in renamed:
511
+ out.append(renamed[key])
512
+ else:
513
+ issues.add(child(path, "key_properties"), f"key property {key!r} is not in the output")
514
+ return tuple(out)
515
+
516
+
517
+ def _output_schema(plans: list[ColumnPlan]) -> dict[str, Any]:
518
+ properties: dict[str, Any] = {}
519
+ for plan in plans:
520
+ prop = to_jsonschema(plan.ctype, nullable=plan.nullable)
521
+ if plan.doc:
522
+ prop["description"] = plan.doc
523
+ if plan.sql_type:
524
+ prop["x-sql-datatype"] = plan.sql_type
525
+ properties[plan.name] = prop
526
+ return {"type": "object", "properties": properties}
527
+
528
+
529
+ def plan_report(plan: StreamPlan) -> dict[str, Any]:
530
+ """A plain-data account of a compiled plan, for ``spec explain``."""
531
+ return {
532
+ "name": plan.name,
533
+ "key_properties": list(plan.key_properties),
534
+ "bookmark_properties": list(plan.bookmark_properties),
535
+ "columns": [
536
+ {
537
+ "name": c.name,
538
+ "sources": list(c.sources),
539
+ "type": str(c.ctype),
540
+ "nullable": c.nullable,
541
+ "on_error": c.on_error,
542
+ "steps": list(c.steps),
543
+ **({"default": to_wire(c.default, c.ctype)} if c.default is not None else {}),
544
+ **({"enum": sorted(map(str, c.enum))} if c.enum is not None else {}),
545
+ **({"reads": sorted(c.reads)} if c.reads else {}),
546
+ }
547
+ for c in plan.columns
548
+ ],
549
+ **({"filter": plan.filter.text} if plan.filter is not None else {}),
550
+ "notes": list(plan.notes),
551
+ }