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,255 @@
1
+ """The canonical type system: parse and print CType strings (detailed design §4).
2
+
3
+ A CType string such as ``decimal(18,2)``, ``varchar(40)`` or ``struct<street: string>`` is
4
+ parsed into a frozen :class:`CType`. Aliases are normalised, so ``str()`` always gives the
5
+ canonical spelling. Mappings to JSON Schema and Arrow live beside this module.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ import sys
12
+ from dataclasses import dataclass
13
+ from typing import Literal
14
+
15
+ if sys.version_info >= (3, 12):
16
+ from typing import override
17
+ else:
18
+ from typing_extensions import override
19
+
20
+ Kind = Literal[
21
+ "boolean",
22
+ "int16",
23
+ "int32",
24
+ "int64",
25
+ "float32",
26
+ "float64",
27
+ "decimal",
28
+ "string",
29
+ "date",
30
+ "time",
31
+ "timestamp",
32
+ "timestamptz",
33
+ "uuid",
34
+ "binary",
35
+ "json",
36
+ "struct",
37
+ "list",
38
+ ]
39
+
40
+ MAX_DECIMAL_PRECISION = 76
41
+ """decimal256 holds 76 digits; decimal128 holds 38."""
42
+
43
+ _SCALARS: dict[str, Kind] = {
44
+ "boolean": "boolean",
45
+ "bool": "boolean",
46
+ "int16": "int16",
47
+ "smallint": "int16",
48
+ "int32": "int32",
49
+ "int": "int32",
50
+ "integer": "int32",
51
+ "int64": "int64",
52
+ "bigint": "int64",
53
+ "long": "int64",
54
+ "float32": "float32",
55
+ "real": "float32",
56
+ "float": "float32",
57
+ "float64": "float64",
58
+ "double": "float64",
59
+ "string": "string",
60
+ "text": "string",
61
+ "date": "date",
62
+ "time": "time",
63
+ "timestamp": "timestamp",
64
+ "timestamp_ntz": "timestamp",
65
+ "timestamptz": "timestamptz",
66
+ "timestamp_tz": "timestamptz",
67
+ "uuid": "uuid",
68
+ "binary": "binary",
69
+ "bytes": "binary",
70
+ "blob": "binary",
71
+ "json": "json",
72
+ "variant": "json",
73
+ }
74
+ _DECIMALS = {"decimal", "numeric"}
75
+ _STRINGS = {"string", "varchar"}
76
+ _LISTS = {"list", "array"}
77
+ _MEMBER = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
78
+
79
+
80
+ class CTypeError(ValueError):
81
+ """A string that is not a valid CType."""
82
+
83
+
84
+ @dataclass(frozen=True)
85
+ class CType:
86
+ """A canonical type. Only the fields that apply to ``kind`` are set."""
87
+
88
+ kind: Kind
89
+ precision: int | None = None
90
+ scale: int | None = None
91
+ length: int | None = None
92
+ members: tuple[tuple[str, CType], ...] = ()
93
+ item: CType | None = None
94
+
95
+ def __post_init__(self) -> None:
96
+ """Reject shapes no parse could produce."""
97
+ if self.kind == "decimal" and (self.precision is None or self.scale is None):
98
+ raise CTypeError(f"decimal needs a precision and scale: {self!r}")
99
+ if self.kind == "list" and self.item is None:
100
+ raise CTypeError(f"list needs an item type: {self!r}")
101
+
102
+ @property
103
+ def decimal_params(self) -> tuple[int, int]:
104
+ """``(precision, scale)`` of a decimal."""
105
+ if self.precision is None or self.scale is None:
106
+ raise CTypeError(f"{self} is not a decimal")
107
+ return self.precision, self.scale
108
+
109
+ @property
110
+ def list_item(self) -> CType:
111
+ """The item type of a list."""
112
+ if self.item is None:
113
+ raise CTypeError(f"{self} is not a list")
114
+ return self.item
115
+
116
+ @override
117
+ def __str__(self) -> str:
118
+ """The canonical spelling, e.g. ``decimal(18,2)`` or ``list<string>``."""
119
+ if self.kind == "decimal":
120
+ return f"decimal({self.precision},{self.scale})"
121
+ if self.kind == "string" and self.length is not None:
122
+ return f"string({self.length})"
123
+ if self.kind == "struct":
124
+ return "struct<" + ", ".join(f"{n}: {t}" for n, t in self.members) + ">"
125
+ if self.kind == "list":
126
+ return f"list<{self.item}>"
127
+ return self.kind
128
+
129
+
130
+ _MULTI_WORD = (
131
+ (re.compile(r"\bdouble\s+precision\b", re.IGNORECASE), "double"),
132
+ (re.compile(r"\btimestamp\s+with\s+time\s+zone\b", re.IGNORECASE), "timestamptz"),
133
+ (re.compile(r"\btimestamp\s+without\s+time\s+zone\b", re.IGNORECASE), "timestamp"),
134
+ (re.compile(r"\bcharacter\s+varying\b", re.IGNORECASE), "varchar"),
135
+ )
136
+ """SQL type names of several words, as taps write them in x-sql-datatype hints."""
137
+
138
+
139
+ def parse_ctype(text: str) -> CType:
140
+ """Parse a CType string, accepting the documented aliases and SQL multi-word names.
141
+
142
+ Raises:
143
+ CTypeError: if ``text`` is not a valid CType.
144
+ """
145
+ for pattern, alias in _MULTI_WORD:
146
+ text = pattern.sub(alias, text)
147
+ parser = _Parser(text)
148
+ ctype = parser.ctype()
149
+ parser.skip_space()
150
+ if parser.pos != len(text):
151
+ raise parser.error("unexpected trailing text")
152
+ return ctype
153
+
154
+
155
+ def ctype_problem(text: str) -> str | None:
156
+ """Return why ``text`` is not a valid CType, or None if it is."""
157
+ try:
158
+ parse_ctype(text)
159
+ except CTypeError as exc:
160
+ return str(exc)
161
+ return None
162
+
163
+
164
+ class _Parser:
165
+ def __init__(self, text: str) -> None:
166
+ self.text = text
167
+ self.pos = 0
168
+
169
+ def error(self, message: str) -> CTypeError:
170
+ return CTypeError(f"{message} at position {self.pos} in {self.text!r}")
171
+
172
+ def skip_space(self) -> None:
173
+ while self.pos < len(self.text) and self.text[self.pos].isspace():
174
+ self.pos += 1
175
+
176
+ def word(self) -> str:
177
+ self.skip_space()
178
+ match = re.compile(r"[A-Za-z_][A-Za-z0-9_]*").match(self.text, self.pos)
179
+ if not match:
180
+ raise self.error("expected a type name")
181
+ self.pos = match.end()
182
+ return match.group(0)
183
+
184
+ def expect(self, char: str) -> None:
185
+ self.skip_space()
186
+ if not self.text.startswith(char, self.pos):
187
+ raise self.error(f"expected {char!r}")
188
+ self.pos += 1
189
+
190
+ def peek(self, char: str) -> bool:
191
+ self.skip_space()
192
+ return self.text.startswith(char, self.pos)
193
+
194
+ def integer(self) -> int:
195
+ self.skip_space()
196
+ match = re.compile(r"\d+").match(self.text, self.pos)
197
+ if not match:
198
+ raise self.error("expected an integer")
199
+ self.pos = match.end()
200
+ return int(match.group(0))
201
+
202
+ def ctype(self) -> CType:
203
+ name = self.word().lower()
204
+ if name in _DECIMALS:
205
+ return self._decimal()
206
+ if name in _STRINGS and self.peek("("):
207
+ self.expect("(")
208
+ length = self.integer()
209
+ self.expect(")")
210
+ if length < 1:
211
+ raise self.error("string length must be at least 1")
212
+ return CType("string", length=length)
213
+ if name == "varchar":
214
+ raise self.error("varchar needs a length; use string for unbounded text")
215
+ if name in _LISTS:
216
+ self.expect("<")
217
+ item = self.ctype()
218
+ self.expect(">")
219
+ return CType("list", item=item)
220
+ if name == "struct":
221
+ return self._struct()
222
+ if name in _SCALARS:
223
+ return CType(_SCALARS[name])
224
+ raise self.error(f"unknown type {name!r}")
225
+
226
+ def _decimal(self) -> CType:
227
+ if not self.peek("("):
228
+ raise self.error("decimal needs a precision and scale, e.g. decimal(18,2)")
229
+ self.expect("(")
230
+ precision = self.integer()
231
+ self.expect(",")
232
+ scale = self.integer()
233
+ self.expect(")")
234
+ if not 1 <= precision <= MAX_DECIMAL_PRECISION:
235
+ raise self.error(f"decimal precision must be 1-{MAX_DECIMAL_PRECISION}")
236
+ if scale > precision:
237
+ raise self.error("decimal scale cannot exceed its precision")
238
+ return CType("decimal", precision=precision, scale=scale)
239
+
240
+ def _struct(self) -> CType:
241
+ self.expect("<")
242
+ members: list[tuple[str, CType]] = []
243
+ while True:
244
+ name = self.word()
245
+ if not _MEMBER.match(name):
246
+ raise self.error(f"invalid struct member name {name!r}")
247
+ if any(name == existing for existing, _ in members):
248
+ raise self.error(f"duplicate struct member {name!r}")
249
+ self.expect(":")
250
+ members.append((name, self.ctype()))
251
+ if self.peek(","):
252
+ self.expect(",")
253
+ continue
254
+ self.expect(">")
255
+ return CType("struct", members=tuple(members))
@@ -0,0 +1,177 @@
1
+ """Tap SCHEMA property -> CType, for columns the spec does not declare (detailed design §4).
2
+
3
+ Rules, in order:
4
+
5
+ 1. A recognised ``x-sql-datatype`` hint wins (``smallint``, ``numeric(10,2)``, ...).
6
+ 2. ``anyOf``/``oneOf``: branches of one scalar type give that type; null plus one type gives
7
+ that type; anything else is json, with a warning.
8
+ 3. Several non-null ``type`` values: json, with a warning. No type at all: json.
9
+ 4. ``integer``: int64, or int16/int32 when ``minimum``/``maximum`` fit.
10
+ 5. ``number``: float64, unless ``x-singer.decimal`` or ``precision``/``scale`` make it a
11
+ decimal.
12
+ 6. ``string``: ``format`` date / time / date-time (timestamptz) / uuid / x-singer.decimal,
13
+ ``contentEncoding: base64`` (binary), else string, bounded by ``maxLength``.
14
+ 7. ``object`` / ``array``: struct / list with ``nested: keep`` when the shape is typed;
15
+ otherwise json.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from collections.abc import Callable, Mapping
21
+ from dataclasses import dataclass, field
22
+ from typing import Any, Literal
23
+
24
+ from map_conform.types.canonical import CType, CTypeError, parse_ctype
25
+
26
+ INT16 = (-(2**15), 2**15 - 1)
27
+ INT32 = (-(2**31), 2**31 - 1)
28
+ DEFAULT_DECIMAL = (38, 9)
29
+ """Precision and scale for an x-singer.decimal that gives neither."""
30
+
31
+ _FORMATS: dict[str, CType] = {
32
+ "date": CType("date"),
33
+ "time": CType("time"),
34
+ "date-time": CType("timestamptz"),
35
+ "uuid": CType("uuid"),
36
+ }
37
+ _JSON = CType("json")
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class TapType:
42
+ """The CType inferred for a tap property, its nullability and anything worth a warning."""
43
+
44
+ ctype: CType
45
+ nullable: bool
46
+ warnings: tuple[str, ...] = field(default=())
47
+
48
+
49
+ def from_jsonschema(schema: Mapping[str, Any], nested: Literal["json", "keep"] = "json") -> TapType:
50
+ """Infer the CType of one tap SCHEMA property."""
51
+ warnings: list[str] = []
52
+ ctype, nullable = _infer(schema, nested, warnings)
53
+ return TapType(ctype, nullable, tuple(warnings))
54
+
55
+
56
+ def _types(schema: Mapping[str, Any]) -> list[str]:
57
+ declared = schema.get("type")
58
+ if declared is None:
59
+ return []
60
+ return [declared] if isinstance(declared, str) else list(declared)
61
+
62
+
63
+ def _infer(schema: Mapping[str, Any], nested: str, warnings: list[str]) -> tuple[CType, bool]:
64
+ hint = schema.get("x-sql-datatype")
65
+ if isinstance(hint, str):
66
+ try:
67
+ ctype = parse_ctype(hint)
68
+ except CTypeError:
69
+ warnings.append(f"ignored unrecognised x-sql-datatype {hint!r}")
70
+ else:
71
+ return ctype, "null" in _types(schema) or not _types(schema)
72
+ branches = schema.get("anyOf") or schema.get("oneOf")
73
+ if isinstance(branches, list):
74
+ return _infer_branches(branches, nested, warnings)
75
+ types = _types(schema)
76
+ nullable = "null" in types or not types
77
+ non_null = [t for t in types if t != "null"]
78
+ if not non_null:
79
+ return _JSON, True
80
+ if len(non_null) > 1:
81
+ warnings.append(f"several types {non_null}: kept as json")
82
+ return _JSON, nullable
83
+ return _infer_one(non_null[0], schema, nested, warnings), nullable
84
+
85
+
86
+ def _infer_branches(branches: list[Any], nested: str, warnings: list[str]) -> tuple[CType, bool]:
87
+ nullable = False
88
+ inferred: list[CType] = []
89
+ for branch in branches:
90
+ if not isinstance(branch, Mapping):
91
+ continue
92
+ if _types(branch) == ["null"]:
93
+ nullable = True
94
+ continue
95
+ ctype, branch_nullable = _infer(branch, nested, [])
96
+ nullable = nullable or branch_nullable
97
+ inferred.append(ctype)
98
+ kinds = {c.kind for c in inferred}
99
+ if len(kinds) == 1:
100
+ if len(set(inferred)) == 1:
101
+ return inferred[0], nullable
102
+ if kinds <= {"string"}: # string(5) | string: the unbounded one covers both
103
+ return CType("string"), nullable
104
+ warnings.append("anyOf/oneOf of different types: kept as json")
105
+ return _JSON, nullable
106
+
107
+
108
+ def _infer_one(kind: str, schema: Mapping[str, Any], nested: str, warnings: list[str]) -> CType:
109
+ if kind in _SHAPES:
110
+ return _SHAPES[kind](schema, nested, warnings)
111
+ if kind in _VALUES:
112
+ return _VALUES[kind](schema)
113
+ warnings.append(f"unknown type {kind!r}: kept as json")
114
+ return _JSON
115
+
116
+
117
+ def _number(schema: Mapping[str, Any]) -> CType:
118
+ if schema.get("format") == "x-singer.decimal" or "precision" in schema or "scale" in schema:
119
+ return _decimal(schema)
120
+ return CType("float64")
121
+
122
+
123
+ def _integer(schema: Mapping[str, Any]) -> CType:
124
+ low, high = schema.get("minimum"), schema.get("maximum")
125
+ if isinstance(low, int) and isinstance(high, int):
126
+ if INT16[0] <= low and high <= INT16[1]:
127
+ return CType("int16")
128
+ if INT32[0] <= low and high <= INT32[1]:
129
+ return CType("int32")
130
+ return CType("int64")
131
+
132
+
133
+ def _decimal(schema: Mapping[str, Any]) -> CType:
134
+ precision = schema.get("precision", DEFAULT_DECIMAL[0])
135
+ scale = schema.get("scale", DEFAULT_DECIMAL[1] if "precision" not in schema else 0)
136
+ return CType("decimal", precision=precision, scale=scale)
137
+
138
+
139
+ def _string(schema: Mapping[str, Any]) -> CType:
140
+ fmt = schema.get("format")
141
+ if fmt == "x-singer.decimal":
142
+ return _decimal(schema)
143
+ if isinstance(fmt, str) and fmt in _FORMATS:
144
+ return _FORMATS[fmt]
145
+ if schema.get("contentEncoding") == "base64":
146
+ return CType("binary")
147
+ length = schema.get("maxLength")
148
+ if isinstance(length, int) and length > 0:
149
+ return CType("string", length=length)
150
+ return CType("string")
151
+
152
+
153
+ def _object(schema: Mapping[str, Any], nested: str, warnings: list[str]) -> CType:
154
+ properties = schema.get("properties")
155
+ if nested != "keep" or not isinstance(properties, Mapping) or not properties:
156
+ return _JSON
157
+ members = tuple((name, _infer(prop, nested, warnings)[0]) for name, prop in properties.items())
158
+ return CType("struct", members=members)
159
+
160
+
161
+ def _array(schema: Mapping[str, Any], nested: str, warnings: list[str]) -> CType:
162
+ items = schema.get("items")
163
+ if nested != "keep" or not isinstance(items, Mapping):
164
+ return _JSON
165
+ return CType("list", item=_infer(items, nested, warnings)[0])
166
+
167
+
168
+ _VALUES: dict[str, Callable[[Mapping[str, Any]], CType]] = {
169
+ "boolean": lambda _: CType("boolean"),
170
+ "integer": _integer,
171
+ "number": _number,
172
+ "string": _string,
173
+ }
174
+ _SHAPES: dict[str, Callable[[Mapping[str, Any], str, list[str]], CType]] = {
175
+ "object": _object,
176
+ "array": _array,
177
+ }
@@ -0,0 +1,63 @@
1
+ """JSON text with exact decimals (ADR-0007).
2
+
3
+ The Singer SDK decodes JSON numbers with fractions as ``Decimal``. The standard library can
4
+ only write a ``Decimal`` as a float, losing digits, or as a string, changing its JSON type.
5
+ :func:`dumps` writes it as the JSON number it came from: ``{"price": 3.14}`` stays
6
+ ``{"price": 3.14}``, and ``0.1000000000000000055511`` keeps every digit.
7
+
8
+ NaN and infinities are not JSON numbers; like the SDK's serializer, they become ``null``.
9
+ Temporal values are written in ISO 8601 and UUIDs in canonical form.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import datetime as dt
15
+ import json
16
+ import math
17
+ import uuid
18
+ from decimal import Decimal
19
+ from typing import Any
20
+
21
+ _COMPACT = (",", ":")
22
+
23
+
24
+ def _plain(value: object, numbers: dict[str, str], token: str) -> object: # noqa: PLR0911 -- one per kind
25
+ """A copy with decimals replaced by unique placeholder strings, recorded in ``numbers``."""
26
+ if isinstance(value, Decimal):
27
+ if not value.is_finite():
28
+ return None
29
+ key = f"{token}{len(numbers)}"
30
+ numbers[key] = format(value, "f") # plain notation: 1E+2 is 100
31
+ return key
32
+ if isinstance(value, float) and not math.isfinite(value):
33
+ return None
34
+ if isinstance(value, dict):
35
+ return {k: _plain(v, numbers, token) for k, v in value.items()}
36
+ if isinstance(value, (list, tuple)):
37
+ return [_plain(v, numbers, token) for v in value]
38
+ if isinstance(value, (dt.datetime, dt.date, dt.time)):
39
+ return value.isoformat()
40
+ if isinstance(value, uuid.UUID):
41
+ return str(value)
42
+ return value
43
+
44
+
45
+ def dumps(value: Any, *, compact: bool = False, sort_keys: bool = False) -> str: # noqa: ANN401
46
+ """JSON text for ``value``, with every ``Decimal`` written as an exact JSON number.
47
+
48
+ Raises:
49
+ TypeError: for a value JSON cannot represent.
50
+ """
51
+ numbers: dict[str, str] = {}
52
+ token = f"\x00{uuid.uuid4().hex}:"
53
+ plain = _plain(value, numbers, token)
54
+ text = json.dumps(
55
+ plain,
56
+ ensure_ascii=False,
57
+ sort_keys=sort_keys,
58
+ separators=_COMPACT if compact else None,
59
+ allow_nan=False,
60
+ )
61
+ for key, number in numbers.items():
62
+ text = text.replace(json.dumps(key), number, 1)
63
+ return text
@@ -0,0 +1,52 @@
1
+ """CType -> Arrow data type (detailed design §4, ADR-0011).
2
+
3
+ ``uuid`` is the ``arrow.uuid`` extension type, which parquet stores as
4
+ ``fixed_len_byte_array(16)`` with the UUID logical type; ``uuid_as="string"`` gives plain
5
+ strings for readers without that support. Decimals up to 38 digits are decimal128, wider
6
+ ones decimal256. json is its JSON text.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import TYPE_CHECKING, Literal
12
+
13
+ import pyarrow as pa
14
+
15
+ if TYPE_CHECKING:
16
+ from map_conform.types.canonical import CType
17
+
18
+ DECIMAL128_MAX = 38
19
+
20
+ _SCALARS: dict[str, pa.DataType] = {
21
+ "boolean": pa.bool_(),
22
+ "int16": pa.int16(),
23
+ "int32": pa.int32(),
24
+ "int64": pa.int64(),
25
+ "float32": pa.float32(),
26
+ "float64": pa.float64(),
27
+ "string": pa.string(),
28
+ "date": pa.date32(),
29
+ "time": pa.time64("us"),
30
+ "timestamp": pa.timestamp("us"),
31
+ "timestamptz": pa.timestamp("us", tz="UTC"),
32
+ "binary": pa.binary(),
33
+ "json": pa.string(),
34
+ }
35
+
36
+
37
+ def to_arrow(ctype: CType, *, uuid_as: Literal["uuid", "string"] = "uuid") -> pa.DataType:
38
+ """The Arrow type that holds values of ``ctype``."""
39
+ if ctype.kind in _SCALARS:
40
+ return _SCALARS[ctype.kind]
41
+ if ctype.kind == "uuid":
42
+ return pa.uuid() if uuid_as == "uuid" else pa.string()
43
+ if ctype.kind == "decimal":
44
+ precision, scale = ctype.decimal_params
45
+ if precision <= DECIMAL128_MAX:
46
+ return pa.decimal128(precision, scale)
47
+ return pa.decimal256(precision, scale)
48
+ if ctype.kind == "struct":
49
+ return pa.struct(
50
+ [pa.field(name, to_arrow(member, uuid_as=uuid_as)) for name, member in ctype.members]
51
+ )
52
+ return pa.list_(to_arrow(ctype.list_item, uuid_as=uuid_as))
@@ -0,0 +1,65 @@
1
+ """CType -> canonical JSON Schema property: the Clean-Landing Contract's SCHEMA (§4 table).
2
+
3
+ Decimals are strings with ``format: x-singer.decimal`` and their precision and scale (few
4
+ targets honour ``x-sql-datatype``); json is JSON text; struct and list are typed objects and
5
+ arrays. ``x-sql-datatype`` is emitted as a hint where the table lists one.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import TYPE_CHECKING, Any
11
+
12
+ from map_conform.types.from_jsonschema import INT16, INT32
13
+
14
+ if TYPE_CHECKING:
15
+ from map_conform.types.canonical import CType
16
+
17
+ INT64 = (-(2**63), 2**63 - 1)
18
+
19
+ _SCALARS: dict[str, dict[str, Any]] = {
20
+ "boolean": {"type": "boolean"},
21
+ "int16": {"type": "integer", "minimum": INT16[0], "maximum": INT16[1],
22
+ "x-sql-datatype": "smallint"},
23
+ "int32": {"type": "integer", "minimum": INT32[0], "maximum": INT32[1],
24
+ "x-sql-datatype": "integer"},
25
+ "int64": {"type": "integer", "minimum": INT64[0], "maximum": INT64[1],
26
+ "x-sql-datatype": "bigint"},
27
+ "float32": {"type": "number", "x-sql-datatype": "real"},
28
+ "float64": {"type": "number", "x-sql-datatype": "double precision"},
29
+ "date": {"type": "string", "format": "date"},
30
+ "time": {"type": "string", "format": "time"},
31
+ "timestamp": {"type": "string", "format": "date-time", "x-sql-datatype": "timestamp"},
32
+ "timestamptz": {"type": "string", "format": "date-time", "x-sql-datatype": "timestamptz"},
33
+ "uuid": {"type": "string", "format": "uuid"},
34
+ "binary": {"type": "string", "contentEncoding": "base64"},
35
+ "json": {"type": "string", "x-sql-datatype": "json"},
36
+ } # fmt: skip
37
+
38
+
39
+ def to_jsonschema(ctype: CType, *, nullable: bool = True) -> dict[str, Any]:
40
+ """The contract's JSON Schema property for ``ctype``."""
41
+ schema: dict[str, Any]
42
+ if ctype.kind in _SCALARS:
43
+ schema = dict(_SCALARS[ctype.kind])
44
+ elif ctype.kind == "decimal":
45
+ precision, scale = ctype.decimal_params
46
+ schema = {
47
+ "type": "string",
48
+ "format": "x-singer.decimal",
49
+ "precision": precision,
50
+ "scale": scale,
51
+ }
52
+ elif ctype.kind == "string":
53
+ schema = {"type": "string"}
54
+ if ctype.length is not None:
55
+ schema["maxLength"] = ctype.length
56
+ elif ctype.kind == "struct":
57
+ schema = {
58
+ "type": "object",
59
+ "properties": {name: to_jsonschema(member) for name, member in ctype.members},
60
+ }
61
+ else:
62
+ schema = {"type": "array", "items": to_jsonschema(ctype.list_item)}
63
+ if nullable:
64
+ schema["type"] = [schema["type"], "null"]
65
+ return schema
@@ -0,0 +1,53 @@
1
+ """Python values -> RECORD wire values (Clean-Landing Contract §3).
2
+
3
+ Casts produce Python values (``Decimal``, ``datetime``, ``UUID``, ``bytes``, parsed JSON);
4
+ the row executor encodes them for the RECORD message with :func:`to_wire`:
5
+
6
+ - ``timestamptz``: ``YYYY-MM-DDTHH:MM:SS.ffffffZ`` in UTC; ``timestamp``: the same without
7
+ ``Z``; ``time``: ``HH:MM:SS.ffffff``; ``date``: ISO;
8
+ - ``decimal(p,s)``: a string with exactly ``s`` fraction digits, never an exponent;
9
+ - ``uuid``: lowercase with dashes; ``binary``: strict base64; ``json``: JSON text;
10
+ - ``struct`` / ``list``: their members encoded by the same rules.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import base64
16
+ import datetime as dt
17
+ import uuid
18
+ from decimal import Decimal
19
+ from typing import TYPE_CHECKING, Any
20
+
21
+ from map_conform.types.jsontext import dumps
22
+
23
+ if TYPE_CHECKING:
24
+ from map_conform.types.canonical import CType
25
+
26
+
27
+ def to_wire(value: object, ctype: CType) -> Any: # noqa: ANN401, C901, PLR0911 -- JSON values
28
+ """Encode a conformed value of ``ctype`` for a RECORD message."""
29
+ if value is None:
30
+ return None
31
+ kind = ctype.kind
32
+ if kind == "timestamptz" and isinstance(value, dt.datetime):
33
+ return value.astimezone(dt.UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
34
+ if kind == "timestamp" and isinstance(value, dt.datetime):
35
+ return value.strftime("%Y-%m-%dT%H:%M:%S.%f")
36
+ if kind == "date" and isinstance(value, dt.date):
37
+ return value.isoformat()
38
+ if kind == "time" and isinstance(value, dt.time):
39
+ return value.strftime("%H:%M:%S.%f")
40
+ if kind == "decimal" and isinstance(value, Decimal):
41
+ return format(value, "f")
42
+ if kind == "uuid" and isinstance(value, uuid.UUID):
43
+ return str(value)
44
+ if kind == "binary" and isinstance(value, bytes):
45
+ return base64.b64encode(value).decode("ascii")
46
+ if kind == "json":
47
+ return dumps(value)
48
+ if kind == "struct" and isinstance(value, dict):
49
+ members = dict(ctype.members)
50
+ return {k: to_wire(v, members[k]) if k in members else v for k, v in value.items()}
51
+ if kind == "list" and isinstance(value, list):
52
+ return [to_wire(v, ctype.list_item) for v in value]
53
+ return value