supaflow-python-sdk 1.0.74__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 (44) hide show
  1. supaflow_python_sdk/__init__.py +150 -0
  2. supaflow_python_sdk/_definition_validation.py +220 -0
  3. supaflow_python_sdk/_legacy_manifest.py +89 -0
  4. supaflow_python_sdk/_legacy_naming.py +50 -0
  5. supaflow_python_sdk/_precision_json.py +74 -0
  6. supaflow_python_sdk/base_connector.py +146 -0
  7. supaflow_python_sdk/capabilities.py +74 -0
  8. supaflow_python_sdk/catalog_naming.py +189 -0
  9. supaflow_python_sdk/child_settings.py +44 -0
  10. supaflow_python_sdk/compatibility.json +10 -0
  11. supaflow_python_sdk/connector_definition.py +279 -0
  12. supaflow_python_sdk/connector_fixture.py +13 -0
  13. supaflow_python_sdk/connector_identity.py +55 -0
  14. supaflow_python_sdk/connector_property.py +97 -0
  15. supaflow_python_sdk/connector_resource.py +388 -0
  16. supaflow_python_sdk/csv_record_emitter.py +288 -0
  17. supaflow_python_sdk/cursor_candidates.py +167 -0
  18. supaflow_python_sdk/errors.py +130 -0
  19. supaflow_python_sdk/field_capabilities.py +50 -0
  20. supaflow_python_sdk/helpers.py +98 -0
  21. supaflow_python_sdk/host_api.py +102 -0
  22. supaflow_python_sdk/job_context.py +39 -0
  23. supaflow_python_sdk/jsonl_record_emitter.py +727 -0
  24. supaflow_python_sdk/keyless_object_handling.py +19 -0
  25. supaflow_python_sdk/models.py +1052 -0
  26. supaflow_python_sdk/naming.py +267 -0
  27. supaflow_python_sdk/native_mapped_jsonl_record_emitter.py +180 -0
  28. supaflow_python_sdk/oauth.py +399 -0
  29. supaflow_python_sdk/openapi_schema_builder.py +778 -0
  30. supaflow_python_sdk/property_rules.py +27 -0
  31. supaflow_python_sdk/py.typed +0 -0
  32. supaflow_python_sdk/resource_options.py +9 -0
  33. supaflow_python_sdk/schema_compliance.py +481 -0
  34. supaflow_python_sdk/source.py +165 -0
  35. supaflow_python_sdk/source_namespace.py +325 -0
  36. supaflow_python_sdk/supa_id.py +422 -0
  37. supaflow_python_sdk/temporal_stage_value.py +136 -0
  38. supaflow_python_sdk/type_inference.py +583 -0
  39. supaflow_python_sdk/ui.py +45 -0
  40. supaflow_python_sdk/write_plan.py +112 -0
  41. supaflow_python_sdk-1.0.74.dist-info/METADATA +80 -0
  42. supaflow_python_sdk-1.0.74.dist-info/RECORD +44 -0
  43. supaflow_python_sdk-1.0.74.dist-info/WHEEL +5 -0
  44. supaflow_python_sdk-1.0.74.dist-info/top_level.txt +1 -0
@@ -0,0 +1,150 @@
1
+ """Supaflow Python SDK -- public types and utilities for connector authors."""
2
+
3
+ from supaflow_python_sdk.base_connector import BaseConnector
4
+ from supaflow_python_sdk.capabilities import source_capabilities
5
+ from supaflow_python_sdk.connector_definition import ConnectorDefinition
6
+ from supaflow_python_sdk.connector_fixture import ConnectorFixture
7
+ from supaflow_python_sdk.connector_identity import (
8
+ ConnectorPackageMetadata,
9
+ customer_connector_type,
10
+ first_party_connector_type,
11
+ parse_customer_connector_type,
12
+ )
13
+ from supaflow_python_sdk.connector_property import ConnectorProperty
14
+ from supaflow_python_sdk.connector_resource import ConnectorResource
15
+ from supaflow_python_sdk.errors import (
16
+ ConnectorError,
17
+ ConnectorException,
18
+ ErrorType,
19
+ Warning,
20
+ fail,
21
+ )
22
+ from supaflow_python_sdk.helpers import (
23
+ check_cancelled,
24
+ discover_csv_files,
25
+ log_error,
26
+ log_info,
27
+ log_warn,
28
+ )
29
+ from supaflow_python_sdk.job_context import JobContext
30
+ from supaflow_python_sdk.models import (
31
+ AppliedReadWindow,
32
+ ChildContextInfo,
33
+ FilterCondition,
34
+ FilterItem,
35
+ IncrementalField,
36
+ InitRequest,
37
+ InitResult,
38
+ LoadRequest,
39
+ LoadResult,
40
+ MapTargetObjectRequest,
41
+ MapTargetObjectResult,
42
+ MappedField,
43
+ MetadataField,
44
+ OrderByClause,
45
+ ProgressUpdatePolicy,
46
+ RateLimitConfig,
47
+ ReadMetadata,
48
+ ReadObjectMetadata,
49
+ ReadRequest,
50
+ ReadResult,
51
+ ReadStatistics,
52
+ RetryPolicy,
53
+ SchemaRequest,
54
+ SchemaResult,
55
+ StageManifest,
56
+ StageRequest,
57
+ StageResult,
58
+ StageStats,
59
+ SyncStateRequest,
60
+ SyncStateResponse,
61
+ )
62
+ from supaflow_python_sdk.naming import (
63
+ apply_prefix,
64
+ normalize_identifier,
65
+ resolve_collisions,
66
+ )
67
+ from supaflow_python_sdk.oauth import ManagedOAuthCredentials, OAuthDefinition
68
+ from supaflow_python_sdk.source import (
69
+ CheckpointEmitter,
70
+ ChildContextWriter,
71
+ ParentContextReader,
72
+ ProgressReporter,
73
+ ProgressStatus,
74
+ RecordEmitResult,
75
+ RecordEmitter,
76
+ )
77
+
78
+ from supaflow_python_sdk.property_rules import ConnectionRole, PropertyValidation, PropertyValidationRule
79
+ from supaflow_python_sdk.ui import UiMedia, UiNotice
80
+
81
+ __version__ = "1.0.74"
82
+
83
+ __all__ = [
84
+ "ConnectionRole", "PropertyValidation", "PropertyValidationRule",
85
+ "UiMedia",
86
+ "UiNotice",
87
+ "BaseConnector",
88
+ "ConnectorDefinition",
89
+ "ConnectorFixture",
90
+ "ConnectorProperty",
91
+ "ConnectorResource",
92
+ "source_capabilities",
93
+ "OAuthDefinition",
94
+ "ManagedOAuthCredentials",
95
+ "JobContext",
96
+ "ConnectorError",
97
+ "ConnectorException",
98
+ "ErrorType",
99
+ "Warning",
100
+ "fail",
101
+ "check_cancelled",
102
+ "discover_csv_files",
103
+ "log_error",
104
+ "log_info",
105
+ "log_warn",
106
+ "ChildContextInfo",
107
+ "FilterCondition",
108
+ "FilterItem",
109
+ "IncrementalField",
110
+ "InitRequest",
111
+ "InitResult",
112
+ "LoadRequest",
113
+ "LoadResult",
114
+ "MapTargetObjectRequest",
115
+ "MapTargetObjectResult",
116
+ "MappedField",
117
+ "MetadataField",
118
+ "OrderByClause",
119
+ "ProgressUpdatePolicy",
120
+ "RateLimitConfig",
121
+ "ReadMetadata",
122
+ "ReadObjectMetadata",
123
+ "ReadRequest",
124
+ "ReadResult",
125
+ "ReadStatistics",
126
+ "RetryPolicy",
127
+ "SchemaRequest",
128
+ "SchemaResult",
129
+ "StageManifest",
130
+ "StageRequest",
131
+ "StageResult",
132
+ "StageStats",
133
+ "AppliedReadWindow",
134
+ "SyncStateRequest",
135
+ "SyncStateResponse",
136
+ "apply_prefix",
137
+ "normalize_identifier",
138
+ "resolve_collisions",
139
+ "CheckpointEmitter",
140
+ "ChildContextWriter",
141
+ "ParentContextReader",
142
+ "ProgressReporter",
143
+ "ProgressStatus",
144
+ "RecordEmitResult",
145
+ "RecordEmitter",
146
+ "ConnectorPackageMetadata",
147
+ "customer_connector_type",
148
+ "first_party_connector_type",
149
+ "parse_customer_connector_type",
150
+ ]
@@ -0,0 +1,220 @@
1
+ """Metadata-only legacy/v11 validation for the SDK definition ownership move.
2
+
3
+ Runtime extraction and naming still belong to the adapter. These checks reuse
4
+ SDK compatibility metadata grammar without importing the execution engine.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from typing import TYPE_CHECKING, Sequence
9
+
10
+ from supaflow_python_sdk._legacy_naming import _normalize_column_segment
11
+ if TYPE_CHECKING:
12
+ from supaflow_python_sdk.connector_resource import ConnectorResource
13
+
14
+
15
+ def _legacy_table_name(name: str) -> str:
16
+ if not name:
17
+ return name
18
+ return "__".join(_normalize_column_segment(part, preserve_original_names=False)
19
+ for part in name.split("__"))
20
+
21
+
22
+ def _external_joined_path(path_segments: Sequence[str] | str) -> str:
23
+ segments = (path_segments,) if isinstance(path_segments, str) else tuple(path_segments)
24
+ return "__".join(segments)
25
+
26
+
27
+ def _check_resource_legacy_collisions(resource: "ConnectorResource") -> None:
28
+ """Reject ``child_primary_keys`` / ``child_primary_keys_locked`` keys
29
+ that collide under dlt's snake_case normalization.
30
+
31
+ This is the construction-time guard for the legacy
32
+ (``preserve_original_names=False``) path: under snake_case, two
33
+ distinct spec-author keys like ``Customer`` and ``customer_event``
34
+ would both normalize to ``customer_event`` and alias at every
35
+ comparison site routed through ``lookup_by_dlt_name``. Loud
36
+ failure at spec construction prevents silent runtime divergence.
37
+ Keep the SDK grammar equal to supported dlt versions; the definition
38
+ metadata parity test is a required gate for dlt upgrades.
39
+
40
+ NOT called when ``DltConnectorSpec.preserve_original_names=True``:
41
+ under identity, the runtime lookup is direct dict access (no
42
+ normalization), so two raw-distinct keys cannot alias. Schema
43
+ discovery additionally runs a B2 joined-FQN guard via
44
+ ``assert_no_path_collisions`` -- but per PR #107 review that
45
+ guard is defensive only: it catches reconstruction bugs and
46
+ multi-source merge collisions, NOT the pre-merge source-shape
47
+ conflict the spec advertises (dlt 1.24.0 silently merges both
48
+ paths into one table during normalize, so the guard never sees
49
+ the original conflict). Real pre-normalize B2 detection or
50
+ escape-in-segment encoding is a documented prerequisite before
51
+ PR C flips the flag on Jira+Mongo. See
52
+ ``naming.py::assert_no_path_collisions`` and
53
+ ``_schema_normalize_backed`` for the limitation in detail.
54
+
55
+ Phase 3 consolidation deletes this guard entirely along with the
56
+ flag.
57
+ """
58
+ for attr in ("child_primary_keys", "child_primary_keys_locked"):
59
+ mapping = getattr(resource, attr, None)
60
+ if not mapping:
61
+ continue
62
+ seen: dict[str, str] = {}
63
+ for key in mapping.keys():
64
+ normalized = _legacy_table_name(key)
65
+ if normalized in seen and seen[normalized] != key:
66
+ raise ValueError(
67
+ f"DltResourceSpec(name={resource.name!r}).{attr}: "
68
+ f"keys {seen[normalized]!r} and {key!r} both "
69
+ f"normalize to {normalized!r} -- runtime lookup "
70
+ f"would be ambiguous. Pick a single canonical "
71
+ f"casing for the spec key."
72
+ )
73
+ seen[normalized] = key
74
+
75
+
76
+ def _validate_v11_resource(
77
+ connector_name: str, resource: "ConnectorResource"
78
+ ) -> None:
79
+ """v11 (closure design) structural-identity invariants for one
80
+ resource declared under ``preserve_original_names=True``.
81
+
82
+ Enforces three contracts at spec construction:
83
+
84
+ 1. **``path_segments`` non-empty.** Every resource on a
85
+ preservation-mode connector must carry routing identity. None
86
+ or empty raises ``ValueError`` pointing the author at §4.1 of
87
+ the closure-design spec.
88
+
89
+ 2. **``cursor_field_path_segments`` non-empty + consistent
90
+ (§4.3 / §7.2).** When ``cursor_field`` is set:
91
+
92
+ - ``cursor_field_path_segments`` must be non-empty.
93
+ - The empty-inner-tuple case raises (a single empty segment
94
+ is not a valid identifier).
95
+ - ``to_external_joined_path(cursor_field_path_segments,
96
+ preserve=True)`` MUST equal ``cursor_field``. Catches
97
+ author typos like declaring ``cursor_field="updated_at"``
98
+ while writing ``cursor_field_path_segments=("updated",)``.
99
+
100
+ 3. **``primary_key_path_segments`` non-empty + consistent
101
+ (v11 §4.4 / §7.2).** When ``primary_key`` is truthy:
102
+
103
+ - ``primary_key_path_segments`` must be non-empty.
104
+ - Same length as ``primary_key``.
105
+ - Every inner tuple is non-empty.
106
+ - For each column ``i``,
107
+ ``to_external_joined_path(primary_key_path_segments[i],
108
+ preserve=True) == primary_key[i]``. Catches the Jira-
109
+ workflows-style author typo where the structural form
110
+ drifts from the external display form.
111
+
112
+ Truthy semantics on ``primary_key`` match
113
+ ``_compute_supa_id_for_row``: an empty list / empty tuple is
114
+ treated as "no PK declared" and no structural form is required.
115
+ """
116
+ # 1. path_segments is required.
117
+ if not resource.path_segments:
118
+ raise ValueError(
119
+ f"DltConnectorSpec(name={connector_name!r}, "
120
+ f"preserve_original_names=True) "
121
+ f"resource {resource.name!r}: path_segments is required "
122
+ f"(non-empty). See B2 closure-design spec §4.1. For "
123
+ f"single-source-identifier resources use a 1-tuple, "
124
+ f"e.g., path_segments=({resource.name!r},)."
125
+ )
126
+
127
+ # 2. cursor_field_path_segments validation.
128
+ if resource.cursor_field:
129
+ segs = resource.cursor_field_path_segments
130
+ if not segs:
131
+ raise ValueError(
132
+ f"DltConnectorSpec(name={connector_name!r}, "
133
+ f"preserve_original_names=True) "
134
+ f"resource {resource.name!r}: cursor_field is "
135
+ f"{resource.cursor_field!r} but "
136
+ f"cursor_field_path_segments is empty. See B2 "
137
+ f"closure-design spec §4.3. For atomic cursors use a "
138
+ f"1-tuple, e.g., cursor_field_path_segments="
139
+ f"({resource.cursor_field!r},)."
140
+ )
141
+ if any(not s for s in segs):
142
+ raise ValueError(
143
+ f"DltConnectorSpec(name={connector_name!r}, "
144
+ f"preserve_original_names=True) "
145
+ f"resource {resource.name!r}: cursor_field_path_segments "
146
+ f"contains an empty inner segment ({segs!r}). Each "
147
+ f"segment must be a non-empty source identifier."
148
+ )
149
+ external = _external_joined_path(
150
+ segs
151
+ )
152
+ if external != resource.cursor_field:
153
+ raise ValueError(
154
+ f"DltConnectorSpec(name={connector_name!r}, "
155
+ f"preserve_original_names=True) "
156
+ f"resource {resource.name!r}: cursor_field_path_segments "
157
+ f"external form {external!r} does not equal cursor_field "
158
+ f"{resource.cursor_field!r}. Either the structural form "
159
+ f"or the display form has a typo; both must agree."
160
+ )
161
+
162
+ # 3. primary_key_path_segments validation.
163
+ pk = resource.primary_key
164
+ if pk:
165
+ # Coerce single-string PK to a one-element list so the
166
+ # length / per-column checks below work uniformly.
167
+ pk_list: list[str]
168
+ if isinstance(pk, str):
169
+ pk_list = [pk]
170
+ else:
171
+ pk_list = list(pk)
172
+ pk_segs = resource.primary_key_path_segments
173
+ if not pk_segs:
174
+ raise ValueError(
175
+ f"DltConnectorSpec(name={connector_name!r}, "
176
+ f"preserve_original_names=True) "
177
+ f"resource {resource.name!r}: primary_key is "
178
+ f"{pk!r} but primary_key_path_segments is empty. See "
179
+ f"B2 closure-design spec §4.4.1. For atomic PKs use "
180
+ f"a one-element list of 1-tuples, e.g., "
181
+ f"primary_key_path_segments=[({pk_list[0]!r},)]."
182
+ )
183
+ if len(pk_segs) != len(pk_list):
184
+ raise ValueError(
185
+ f"DltConnectorSpec(name={connector_name!r}, "
186
+ f"preserve_original_names=True) "
187
+ f"resource {resource.name!r}: primary_key_path_segments "
188
+ f"length {len(pk_segs)} does not match primary_key "
189
+ f"length {len(pk_list)} ({pk!r})."
190
+ )
191
+ for i, (col, segs) in enumerate(zip(pk_list, pk_segs)):
192
+ if not segs:
193
+ raise ValueError(
194
+ f"DltConnectorSpec(name={connector_name!r}, "
195
+ f"preserve_original_names=True) "
196
+ f"resource {resource.name!r}: "
197
+ f"primary_key_path_segments[{i}] is empty -- each "
198
+ f"PK column must have a non-empty structural form."
199
+ )
200
+ if any(not s for s in segs):
201
+ raise ValueError(
202
+ f"DltConnectorSpec(name={connector_name!r}, "
203
+ f"preserve_original_names=True) "
204
+ f"resource {resource.name!r}: "
205
+ f"primary_key_path_segments[{i}] {segs!r} contains "
206
+ f"an empty inner segment."
207
+ )
208
+ external = _external_joined_path(
209
+ segs
210
+ )
211
+ if external != col:
212
+ raise ValueError(
213
+ f"DltConnectorSpec(name={connector_name!r}, "
214
+ f"preserve_original_names=True) "
215
+ f"resource {resource.name!r}: "
216
+ f"primary_key_path_segments[{i}] external form "
217
+ f"{external!r} does not equal primary_key[{i}] "
218
+ f"{col!r}. Either the structural form or the "
219
+ f"display form has a typo; both must agree."
220
+ )
@@ -0,0 +1,89 @@
1
+ """Private v1 compatibility codec; metadata construction needs only the SDK.
2
+
3
+ YAML rendering is a legacy convenience supplied by the runtime/toolchain's
4
+ existing PyYAML dependency, never a default SDK installation requirement.
5
+ This compatibility interface remains stable for supported runtimes through M9.
6
+ Consumers include the SDK definition, toolchain renderer and runtime v1 wrapper,
7
+ including the quoted-string class, registration helper and serializer functions.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ from types import ModuleType
12
+ from typing import Any
13
+
14
+
15
+ class _QuotedYamlStr(str):
16
+ """String subclass whose PyYAML representation is always double-quoted.
17
+
18
+ Used for the connector.version field so the generator output matches the
19
+ quoted form produced by the Maven stamp and the `supaflow-connector
20
+ stamp-version` CLI. Without this, an unquoted `version: 1.0.47-SNAPSHOT`
21
+ on disk after stamping would disagree with a fresh `generate-manifest`
22
+ (which emits unquoted via safe_dump), and the manifest sync check fails.
23
+ """
24
+
25
+
26
+ def _register_yaml(yaml_module: ModuleType) -> None:
27
+ """Keep the runtime's existing quoted-string registration on its dumper."""
28
+ yaml_module.SafeDumper.add_representer(
29
+ _QuotedYamlStr,
30
+ lambda dumper, data: dumper.represent_scalar(
31
+ "tag:yaml.org,2002:str", str(data), style='"'
32
+ ),
33
+ )
34
+
35
+
36
+ def manifest_dict(definition: Any) -> dict[str, Any]:
37
+ return {
38
+ "manifest_version": 1,
39
+ "connector": {
40
+ "name": definition.name,
41
+ "type": definition.type,
42
+ "runtime": definition.runtime,
43
+ "sdk_version": definition.sdk_version,
44
+ "min_platform_version": definition.min_platform_version,
45
+ "kind": definition.kind,
46
+ "vendor": definition.vendor,
47
+ "version": definition.version,
48
+ "group_id": definition.group_id,
49
+ "artifact_id": definition.artifact(),
50
+ "release_stage": definition.release_stage,
51
+ "entrypoint": definition.entrypoint,
52
+ "icon": definition.icon,
53
+ "description": definition.description,
54
+ },
55
+ "capabilities": dict(definition.capabilities),
56
+ "properties": [prop.as_manifest() for prop in definition.properties],
57
+ }
58
+
59
+
60
+ def render_manifest_yaml(manifest: dict[str, Any]) -> str:
61
+ """Render v1 with the quoted version expected by the Maven and CLI stampers."""
62
+ try:
63
+ import yaml
64
+ except ModuleNotFoundError as exc:
65
+ if exc.name != "yaml":
66
+ raise
67
+ raise ModuleNotFoundError(
68
+ "Legacy YAML rendering requires PyYAML from the connector runtime or toolchain",
69
+ name="yaml",
70
+ ) from None
71
+ if _QuotedYamlStr not in yaml.SafeDumper.yaml_representers:
72
+ _register_yaml(yaml)
73
+ connector = manifest["connector"]
74
+ manifest = {
75
+ **manifest,
76
+ "connector": {
77
+ **connector,
78
+ "version": (
79
+ _QuotedYamlStr(connector["version"])
80
+ if connector["version"] is not None else None
81
+ ),
82
+ },
83
+ }
84
+ return yaml.safe_dump(
85
+ manifest,
86
+ sort_keys=False,
87
+ default_flow_style=False,
88
+ allow_unicode=False,
89
+ )
@@ -0,0 +1,50 @@
1
+ """Existing SDK metadata-name compatibility grammar; not an execution normalizer."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+
6
+
7
+ _LEGACY_SEGMENT_TRANSLATION = str.maketrans({"+": "x", "-": "_", "*": "x", "@": "a", "|": "l"})
8
+
9
+
10
+ def _normalize_column_segment(
11
+ segment: str, *, preserve_original_names: bool
12
+ ) -> str:
13
+ """Normalize one identifier segment for legacy metadata keys.
14
+
15
+ - **``preserve_original_names=False`` (legacy):** retains the SDK's
16
+ historical snake-case column keys (Stripe ``Customer`` -> ``customer``,
17
+ GitHub ``createdAt`` -> ``created_at``). Keep this compatibility grammar
18
+ independent of adapter imports. This grammar must remain equal to
19
+ supported dlt snake_case: the definition metadata parity test is a
20
+ required gate for dlt upgrades, since these keys guard runtime lookup.
21
+ A grammar change requires a compatibility decision; do not change this
22
+ shared body to clear a parity failure and silently rename existing keys.
23
+
24
+ - **``preserve_original_names=True`` (v11):** identity. Source
25
+ identifiers flow through dlt's ``SupaflowNamingConvention``
26
+ unchanged, so the rich-dict column key matches the
27
+ dlt-emitted column name verbatim.
28
+
29
+ Single chokepoint so every site that builds a metadata key
30
+ (flattened column names, child PK normalization, child key
31
+ derivation) shares one rule.
32
+ """
33
+ if preserve_original_names:
34
+ return segment
35
+ if segment is None:
36
+ raise ValueError("`name` is None")
37
+ name = segment.strip()
38
+ if not name:
39
+ raise ValueError(name)
40
+
41
+ # Legacy keys use a reduced alphabet, split acronym/camel-case boundaries,
42
+ # prefix decimal digits and encode trailing underscores as x characters.
43
+ name = re.sub(r"[^a-zA-Z\d_]+", "_", name.translate(_LEGACY_SEGMENT_TRANSLATION))
44
+ name = re.sub(r"([^_])([A-Z][a-z]+)", r"\1_\2", name)
45
+ name = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", name).lower()
46
+ if name[0].isdecimal():
47
+ name = "_" + name
48
+ trailing = len(name) - len(name.rstrip("_"))
49
+ name = name.rstrip("_") + "x" * trailing
50
+ return re.sub(r"__+", "_", name)
@@ -0,0 +1,74 @@
1
+ """Internal JSON codec preserving numeric tokens without changing native Decimal semantics.
2
+
3
+ Parsed JSON fractions are marked separately: existing connector-native Decimal
4
+ values may intentionally serialize as strings, whereas JSON numbers must remain
5
+ numbers. No dependency on dlt or an optional JSON backend.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import math
11
+ from decimal import Decimal
12
+
13
+
14
+ class JsonNumber(Decimal):
15
+ """An exact fractional numeric token read from JSON, not a quoted string."""
16
+
17
+
18
+ def _parse_number(token):
19
+ exact = JsonNumber(token)
20
+ approximate = float(token)
21
+ # Preserve existing float/hash behavior when its JSON round-trip is exact.
22
+ # Only tokens that would lose digits (or overflow) need an exact wrapper.
23
+ if math.isfinite(approximate) and Decimal(str(approximate)) == exact:
24
+ return approximate
25
+ return exact
26
+
27
+
28
+ def loads(value):
29
+ return json.loads(value, parse_float=_parse_number)
30
+
31
+
32
+ def dumps(value, *, ensure_ascii=True, sort_keys=False, default=None, separators=None):
33
+ """Use stdlib scalar escaping, retaining exact parsed JSON numeric tokens."""
34
+ scalar_encoder = json.JSONEncoder(ensure_ascii=ensure_ascii)
35
+ item_sep, key_sep = separators or (", ", ": ")
36
+ active = set()
37
+
38
+ def encode(item):
39
+ if isinstance(item, JsonNumber):
40
+ if not item.is_finite():
41
+ raise ValueError("Non-finite exact JSON number")
42
+ return str(item)
43
+ if isinstance(item, (dict, list, tuple)):
44
+ identity = id(item)
45
+ if identity in active:
46
+ raise ValueError("Circular reference detected")
47
+ active.add(identity)
48
+ try:
49
+ if isinstance(item, dict):
50
+ entries = sorted(item.items()) if sort_keys else item.items()
51
+ parts = []
52
+ for key, child in entries:
53
+ # Let stdlib enforce/escape its normal JSON key contract.
54
+ encoded_key = scalar_encoder.encode({key: None})
55
+ encoded_key = encoded_key[1:encoded_key.rfind(":")]
56
+ parts.append(encoded_key + key_sep + encode(child))
57
+ return "{" + item_sep.join(parts) + "}"
58
+ return "[" + item_sep.join(encode(child) for child in item) + "]"
59
+ finally:
60
+ active.remove(identity)
61
+ if item is None or isinstance(item, (str, bool, int, float)):
62
+ return scalar_encoder.encode(item)
63
+ if default is not None:
64
+ identity = id(item)
65
+ if identity in active:
66
+ raise ValueError("Circular reference detected")
67
+ active.add(identity)
68
+ try:
69
+ return encode(default(item))
70
+ finally:
71
+ active.remove(identity)
72
+ return scalar_encoder.encode(item)
73
+
74
+ return encode(value)