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,778 @@
1
+ """Reusable OpenAPI -> object-schema builder.
2
+
3
+ Consumed by connectors that have authoritative OpenAPI specs (Jira,
4
+ ServiceNow, Zendesk, GitHub, etc.) to produce a rich per-stream
5
+ object-schema dict that serves two audiences:
6
+
7
+ 1. ``to_dlt_column_hints(...)`` projection consumed by
8
+ ``apply_hints(columns=...)`` in the connector's ``_create_source``,
9
+ keeping documented fields in the Supaflow schema even when the
10
+ sampled tenant has sparse data.
11
+
12
+ 2. Direct-API schema building for connectors that outgrow dlt's
13
+ normalize-backed inference. The rich dict carries descriptions,
14
+ enums, formats, and inferred PK/FK hints that dlt's column schema
15
+ cannot express.
16
+
17
+ Per-connector generator scripts call ``build_object_schema`` once per
18
+ stream, write the aggregated ``{stream_name: object_schema}`` dict out
19
+ as a committed Python file, and invoke this module only at build time.
20
+ Runtime has no dependency on this module beyond the projection helper.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import logging
25
+ from dataclasses import dataclass, field
26
+ from typing import Any, Dict, Iterable, List, Mapping, Optional, Tuple
27
+
28
+ from supaflow_python_sdk._legacy_naming import (
29
+ _LEGACY_SEGMENT_TRANSLATION as _LEGACY_SEGMENT_TRANSLATION,
30
+ _normalize_column_segment as _normalize_column_segment,
31
+ )
32
+
33
+ _LOGGER = logging.getLogger(__name__)
34
+
35
+
36
+ # OpenAPI (type, format) -> dlt data_type. ``None`` format is the default.
37
+ # Unknown (type, format) pairs fall back to the (type, None) entry; if
38
+ # that's also missing, the caller raises (see _map_type).
39
+ OPENAPI_TYPE_TO_DLT: Dict[Tuple[str, Optional[str]], str] = {
40
+ ("string", None): "text",
41
+ ("string", "date"): "date",
42
+ ("string", "date-time"): "timestamp",
43
+ ("string", "uri"): "text",
44
+ ("string", "uuid"): "text",
45
+ ("string", "email"): "text",
46
+ ("string", "hostname"): "text",
47
+ ("string", "ipv4"): "text",
48
+ ("string", "ipv6"): "text",
49
+ ("string", "byte"): "text",
50
+ ("string", "binary"): "text",
51
+ ("string", "password"): "text",
52
+ ("integer", None): "bigint",
53
+ ("integer", "int32"): "bigint",
54
+ ("integer", "int64"): "bigint",
55
+ ("number", None): "double",
56
+ ("number", "float"): "double",
57
+ ("number", "double"): "double",
58
+ ("boolean", None): "bool",
59
+ }
60
+
61
+
62
+
63
+ def _is_user_ref(
64
+ prop: Mapping[str, Any], user_schema_refs: frozenset[str]
65
+ ) -> bool:
66
+ """Detect whether a property refers to a configured user schema
67
+ (directly or via allOf). ``user_schema_refs`` is the set of
68
+ OpenAPI schema names (last path segment of the $ref) the caller
69
+ considers user-typed; pass an empty set to disable inference.
70
+ """
71
+ if not user_schema_refs:
72
+ return False
73
+ ref = prop.get("$ref")
74
+ if ref and ref.rsplit("/", 1)[-1] in user_schema_refs:
75
+ return True
76
+ for sub in prop.get("allOf") or []:
77
+ if _is_user_ref(sub, user_schema_refs):
78
+ return True
79
+ return False
80
+
81
+
82
+ _MAX_REF_DEPTH = 32
83
+
84
+
85
+ def _resolve_schema(
86
+ spec: Mapping[str, Any],
87
+ prop: Mapping[str, Any],
88
+ _depth: int = 0,
89
+ ) -> Dict[str, Any]:
90
+ """Resolve ``$ref`` and single-``allOf`` into a concrete schema dict.
91
+
92
+ Returns a NEW dict; does not mutate ``prop`` or the spec. Any
93
+ fields present on the referring prop (``description``, ``enum``,
94
+ ``format``, ``example``, ``readOnly``, ``nullable``, etc.) override
95
+ the corresponding fields on the resolved target -- the prop site
96
+ always wins. This lets callers refine a shared schema at the use
97
+ site without mutating the component.
98
+ """
99
+ if _depth > _MAX_REF_DEPTH:
100
+ raise RecursionError(
101
+ f"$ref resolution exceeded depth {_MAX_REF_DEPTH}; possible cycle"
102
+ )
103
+
104
+ def _compositional_assign(target: Dict[str, Any], key: str, value: Any) -> None:
105
+ """Merge one key/value into ``target`` using OpenAPI composition rules.
106
+
107
+ ``properties`` is a dict-union (incoming wins on per-field collision,
108
+ matching both allOf left-to-right and prop-site-overrides-ref
109
+ precedence). ``required`` is a list-union preserving first-seen order.
110
+ All other keys overwrite (prop-site or later branch wins), which is
111
+ how scalar refinements like ``description``/``enum``/``format`` are
112
+ meant to flow.
113
+ """
114
+ if key == "properties" and isinstance(value, dict):
115
+ existing = target.get("properties")
116
+ if isinstance(existing, dict):
117
+ combined = dict(existing)
118
+ combined.update(value)
119
+ target["properties"] = combined
120
+ else:
121
+ target["properties"] = dict(value)
122
+ return
123
+ if key == "required" and isinstance(value, list):
124
+ existing = target.get("required")
125
+ seen: Dict[str, None] = {}
126
+ if isinstance(existing, list):
127
+ for name in existing:
128
+ if isinstance(name, str):
129
+ seen.setdefault(name, None)
130
+ for name in value:
131
+ if isinstance(name, str):
132
+ seen.setdefault(name, None)
133
+ target["required"] = list(seen.keys())
134
+ return
135
+ target[key] = value
136
+
137
+ if "$ref" in prop:
138
+ ref = prop["$ref"]
139
+ if not ref.startswith("#/components/schemas/"):
140
+ raise ValueError(f"Unsupported $ref shape: {ref!r}")
141
+ name = ref.rsplit("/", 1)[-1]
142
+ target = spec.get("components", {}).get("schemas", {}).get(name)
143
+ if target is None:
144
+ raise KeyError(f"Missing OpenAPI schema: {name}")
145
+ resolved = _resolve_schema(spec, target, _depth + 1)
146
+ # Prop-site fields always win (description, enum, format, example,
147
+ # readOnly, nullable, ...), but ``properties`` and ``required`` are
148
+ # compositional: prop-site refinements MUST be unioned with the
149
+ # resolved target's fields, not replace them.
150
+ merged = dict(resolved)
151
+ for k, v in prop.items():
152
+ if k == "$ref":
153
+ continue
154
+ _compositional_assign(merged, k, v)
155
+ return merged
156
+
157
+ if "allOf" in prop and isinstance(prop["allOf"], list):
158
+ # OpenAPI allOf = composition: union every branch's ``properties``
159
+ # and ``required``. Other scalar keys follow the left-to-right
160
+ # "later wins" rule, with prop-site extras winning over every branch.
161
+ merged: Dict[str, Any] = {}
162
+ for sub in prop["allOf"]:
163
+ sub_resolved = _resolve_schema(spec, sub, _depth + 1)
164
+ for k, v in sub_resolved.items():
165
+ _compositional_assign(merged, k, v)
166
+ for k, v in prop.items():
167
+ if k == "allOf":
168
+ continue
169
+ _compositional_assign(merged, k, v)
170
+ return merged
171
+
172
+ # Inline schema - return a shallow copy so callers can mutate safely.
173
+ return dict(prop)
174
+
175
+
176
+ @dataclass(frozen=True)
177
+ class StreamSpec:
178
+ """Describes one stream the generator should extract.
179
+
180
+ ``business_primary_key`` is the API's natural key (e.g. ``("id",)``
181
+ or the composite ``("id__entity_id", "id__name")`` for Jira
182
+ workflows). It is NOT the Supaflow row-identity key -- that is
183
+ always ``_supa_id``, computed from the business-PK values by the
184
+ declarative runtime. We call this "business" PK to prevent
185
+ confusion with ``_supa_id``-owned row identity.
186
+
187
+ ``response_type`` values:
188
+ * ``array`` - endpoint returns a raw JSON array of items.
189
+ * ``page_bean`` - endpoint returns ``{values: [...], ...}``.
190
+ * ``wrapped`` - endpoint returns ``{<data_path>: [...]}`` for a
191
+ custom envelope key like ``issueLinkTypes``.
192
+ """
193
+
194
+ name: str
195
+ endpoint: str
196
+ schema_ref: str
197
+ business_primary_key: Tuple[str, ...]
198
+ response_type: str = "array"
199
+ data_path: Optional[str] = None
200
+ spec_source: str = "platform"
201
+ fk_hints: Mapping[str, Tuple[str, str]] = field(default_factory=dict)
202
+ """Override map: flattened column name -> (target_stream, target_field).
203
+
204
+ Used when the FK target is unambiguous but OpenAPI only embeds a
205
+ full nested object (the common pattern). Inferred FKs from User
206
+ refs are filled automatically; use this dict for non-User FKs.
207
+ """
208
+
209
+ user_schema_refs: Tuple[str, ...] = ()
210
+ """OpenAPI schema names this stream treats as user-typed refs for
211
+ automatic ``accountId`` -> users.account_id FK inference. Empty
212
+ tuple (default) disables user-ref inference entirely. The Jira
213
+ generator passes ``("User", "UserDetails")``; other connectors
214
+ declare their own set per stream.
215
+ """
216
+
217
+ flatten_nested_objects: bool = True
218
+ """Whether to recurse into nested object properties and flatten them
219
+ into ``parent__child`` scalar columns, or collapse them into a
220
+ single ``json`` column at the parent level.
221
+
222
+ Defaults to ``True`` to preserve the original behavior expected by
223
+ normalize-backed connectors (Jira): dlt's normalize stage produces
224
+ flat rows with ``parent__child`` column names, so the static schema
225
+ must match.
226
+
227
+ Set ``False`` for connectors on the ``iterate_resource`` path that
228
+ emit raw records as-is (Stripe, GitHub). In that case the runtime
229
+ emits ``{parent: {...}}`` as a single JSON blob, and the static
230
+ schema needs to declare ``parent`` as ``json`` to match -- any
231
+ pre-flattened ``parent__child`` columns declared on the schema would
232
+ stay NULL forever because the emitter never populates them.
233
+
234
+ Nested array properties (``type: array``) are unaffected by this
235
+ flag: they always emit a child-table entry (normalize-backed) or
236
+ are handled separately by the connector. Only plain object nesting
237
+ is collapsed.
238
+
239
+ ``oneOf``/``anyOf`` polymorphic properties always collapse to a
240
+ single ``json`` column regardless of this flag -- union-flattening
241
+ their branches would misrepresent the shape even under normalize.
242
+ """
243
+
244
+ child_pk_overrides: Mapping[str, Tuple[str, ...]] = field(default_factory=dict)
245
+ """Override map: builder-native FQ child name -> PK column tuple.
246
+
247
+ Keys use the path the builder itself produces (parent chain joined
248
+ with ``__``, e.g. ``"workflows__statuses"``, ``"projects__components"``).
249
+ This is NOT the same as dlt's post-envelope-hoist table name --
250
+ connectors that use ``envelope_prefix`` on their ``DltResourceSpec``
251
+ must translate when consuming ``to_child_primary_keys(...)``, or
252
+ hand-author ``DltResourceSpec.child_primary_keys`` directly.
253
+
254
+ Values:
255
+ * ``tuple[str, ...]`` with one or more entries: use these columns
256
+ as the child's business PK. Every named column must exist in
257
+ the resolved items schema (post snake_case), else ``ValueError``.
258
+ * Empty tuple ``()``: explicitly force Case B -- suppress the
259
+ heuristic even if ``id``/``key``/``accountId`` is present. Use
260
+ when a child has an ``id`` that is not stable across runs.
261
+ """
262
+
263
+
264
+ def empty_field_entry(name: str, data_type: str) -> Dict[str, Any]:
265
+ """Create a field-entry dict with every key populated with defaults.
266
+
267
+ Having all keys present on every entry simplifies downstream
268
+ consumers (they can do ``entry["enum"]`` without a ``.get()``).
269
+
270
+ Notably absent: ``primary_key`` and ``unique``. Those belong to the
271
+ Supaflow schema layer's ``_supa_id`` contract, not to the API-
272
+ surface rich dict. Business-PK info lives in
273
+ ``business_primary_key``; callers that need ``(name, dlt_type)``
274
+ tuples for ``DltResourceSpec.static_fields`` use the projection
275
+ helper ``to_static_fields`` in the generated ``object_schemas.py``.
276
+ """
277
+ return {
278
+ "name": name,
279
+ "data_type": data_type,
280
+ "nullable": True,
281
+ "description": None,
282
+ "format": None,
283
+ "enum": None,
284
+ "foreign_key": None,
285
+ "source_path": None,
286
+ "business_primary_key": False,
287
+ "inferred_pk": False,
288
+ "inferred_fk": False,
289
+ }
290
+
291
+
292
+ def build_object_schema(
293
+ spec: Mapping[str, Any],
294
+ stream: StreamSpec,
295
+ *,
296
+ user_schema_refs: Optional[Iterable[str]] = None,
297
+ preserve_original_names: bool = False,
298
+ ) -> Dict[str, Any]:
299
+ """Build the rich object-schema dict for one stream.
300
+
301
+ Walks the referenced OpenAPI schema, flattens nested objects,
302
+ emits child schemas for arrays, applies the active naming rule
303
+ (snake_case under legacy, identity under
304
+ ``preserve_original_names=True``), infers business-PK/FK flags,
305
+ and returns a dict of the shape:
306
+
307
+ {
308
+ "name": <stream>,
309
+ "endpoint": <endpoint>,
310
+ "schema_ref": <openapi_schema_name>,
311
+ "response_type": <"array"|"page_bean"|"wrapped">,
312
+ "data_path": <None or envelope key>,
313
+ "business_primary_key": [<col>, ...], # API natural key; NOT row identity
314
+ "fields": {<flattened_col>: <field_entry>, ...},
315
+ "children": {<array_prop_name>: <child_schema>, ...},
316
+ }
317
+
318
+ Child schemas follow the same shape recursively (but carry no
319
+ ``endpoint`` of their own, and their ``business_primary_key`` may
320
+ be empty for Case B bare-value children).
321
+ """
322
+ schema_root = spec.get("components", {}).get("schemas", {}).get(stream.schema_ref)
323
+ if schema_root is None:
324
+ raise KeyError(f"OpenAPI schema not found: {stream.schema_ref}")
325
+ resolved_root = _resolve_schema(spec, schema_root)
326
+
327
+ fields: Dict[str, Dict[str, Any]] = {}
328
+ children: Dict[str, Dict[str, Any]] = {}
329
+
330
+ # Explicit user_schema_refs arg (if any) overrides the StreamSpec
331
+ # field; empty -> no user-ref FK inference.
332
+ if user_schema_refs is not None:
333
+ refs_set = frozenset(user_schema_refs)
334
+ else:
335
+ refs_set = frozenset(stream.user_schema_refs)
336
+
337
+ user_ref_prefixes: set = set()
338
+ # Track the set of $ref schema names currently on the walk stack so
339
+ # we can short-circuit cycles (e.g., IssueBean.fields references
340
+ # IssueBean again in Jira's spec). Seed with the root ref so any
341
+ # nested property referencing back to the root is also skipped.
342
+ initial_ref_stack: frozenset[str] = frozenset({stream.schema_ref})
343
+ _walk_properties(
344
+ spec=spec,
345
+ props=resolved_root.get("properties", {}) or {},
346
+ parent_path=(),
347
+ parent_source_path=(),
348
+ fields=fields,
349
+ children=children,
350
+ stream_name=stream.name,
351
+ user_ref_prefixes=user_ref_prefixes,
352
+ user_schema_refs=refs_set,
353
+ ref_stack=initial_ref_stack,
354
+ child_pk_overrides_ref=stream.child_pk_overrides,
355
+ child_path_chain=(),
356
+ flatten_nested_objects=stream.flatten_nested_objects,
357
+ preserve_original_names=preserve_original_names,
358
+ )
359
+ _apply_business_primary_key_flags(fields, stream.business_primary_key)
360
+ _annotate_inferred_fks(
361
+ fields,
362
+ user_ref_prefixes,
363
+ stream.fk_hints,
364
+ preserve_original_names=preserve_original_names,
365
+ )
366
+
367
+ return {
368
+ "name": stream.name,
369
+ "endpoint": stream.endpoint,
370
+ "schema_ref": stream.schema_ref,
371
+ "response_type": stream.response_type,
372
+ "data_path": stream.data_path,
373
+ "business_primary_key": list(stream.business_primary_key),
374
+ "fields": fields,
375
+ "children": children,
376
+ }
377
+
378
+
379
+ def _map_type(prop: Mapping[str, Any]) -> Optional[str]:
380
+ """Map an OpenAPI property to a dlt ``data_type`` literal.
381
+
382
+ Returns ``None`` for schemas that should not become a scalar column
383
+ (objects, arrays, untyped anys).
384
+ """
385
+ t = prop.get("type")
386
+ if t is None:
387
+ return None
388
+ if t == "object" or t == "array":
389
+ return None
390
+ fmt = prop.get("format")
391
+ key = (t, fmt)
392
+ if key in OPENAPI_TYPE_TO_DLT:
393
+ return OPENAPI_TYPE_TO_DLT[key]
394
+ fallback = (t, None)
395
+ if fallback in OPENAPI_TYPE_TO_DLT:
396
+ return OPENAPI_TYPE_TO_DLT[fallback]
397
+ return None
398
+
399
+
400
+ def _flatten_column_name(
401
+ path: Tuple[str, ...], *, preserve_original_names: bool = False
402
+ ) -> str:
403
+ """Apply the active naming rule to each segment, join with ``__``.
404
+
405
+ Under ``preserve_original_names=True`` (v11) the per-segment
406
+ normalization is identity -- source-shape camelCase / PascalCase
407
+ flows through unchanged; under legacy each segment is
408
+ snake-cased via the SDK's legacy column-key compatibility rule.
409
+ Segments are always joined with the external ``__`` separator
410
+ regardless of mode -- the rich-dict column keys are the
411
+ SchemaFieldInfo.name shape consumed by Supaflow, never the
412
+ dlt-internal ``▶``-joined form.
413
+ """
414
+ return "__".join(
415
+ _normalize_column_segment(p, preserve_original_names=preserve_original_names)
416
+ for p in path
417
+ )
418
+
419
+
420
+ def _ref_names(prop: Mapping[str, Any]) -> frozenset[str]:
421
+ """Return the set of ref names reachable from this prop (direct
422
+ ``$ref`` plus every branch of any ``allOf`` composition), or an
423
+ empty frozenset if the prop is purely inline. Used for cycle
424
+ detection: ``allOf: [{$ref: A}, {$ref: B}]`` must contribute BOTH
425
+ A and B to the walk stack, otherwise a cycle through the
426
+ not-first branch leaks past the visited check and only trips the
427
+ depth-limit RecursionError in ``_resolve_schema``.
428
+ """
429
+ names: set[str] = set()
430
+ ref = prop.get("$ref")
431
+ if ref:
432
+ names.add(ref.rsplit("/", 1)[-1])
433
+ for sub in prop.get("allOf") or []:
434
+ names |= _ref_names(sub)
435
+ return frozenset(names)
436
+
437
+
438
+ def _ref_name(prop: Mapping[str, Any]) -> Optional[str]:
439
+ """Back-compat single-name accessor. Returns an arbitrary element
440
+ of ``_ref_names(prop)`` (or None if empty). Prefer ``_ref_names``
441
+ for cycle-stack bookkeeping; this helper is kept for callers that
442
+ only need a display name (e.g., the ``schema_ref`` child-table
443
+ field, which records a single name).
444
+ """
445
+ names = _ref_names(prop)
446
+ return next(iter(names), None)
447
+
448
+
449
+ _CHILD_PK_CANDIDATES: Tuple[str, ...] = ("id", "key", "accountId")
450
+
451
+
452
+ def _infer_child_business_pk(
453
+ resolved_items: Mapping[str, Any],
454
+ ) -> List[str]:
455
+ """Return the inferred business-PK column list (pre-normalization
456
+ names) for a child schema. Priority: id > key > accountId. No match
457
+ -> empty list. Callers normalize the name(s) via
458
+ ``_normalize_column_segment`` before writing to fields.
459
+ """
460
+ props = resolved_items.get("properties") or {}
461
+ for candidate in _CHILD_PK_CANDIDATES:
462
+ if candidate in props:
463
+ return [candidate]
464
+ return []
465
+
466
+
467
+ def _apply_child_pk(
468
+ child_schema: Dict[str, Any],
469
+ pk_columns_raw: List[str],
470
+ *,
471
+ preserve_original_names: bool = False,
472
+ ) -> None:
473
+ """Apply the inferred or override PK columns to the child schema:
474
+ normalize names, set top-level business_primary_key, and flag each
475
+ matching field entry. Raises ``ValueError`` if any normalized column
476
+ is absent from ``child_schema["fields"]`` -- matches the root-PK
477
+ validation behavior.
478
+
479
+ Under ``preserve_original_names=True`` the per-segment normalize
480
+ is identity so the PK names carry the source-shape verbatim.
481
+ """
482
+ if not pk_columns_raw:
483
+ child_schema["business_primary_key"] = []
484
+ return
485
+ normalized = [
486
+ _normalize_column_segment(
487
+ c, preserve_original_names=preserve_original_names
488
+ )
489
+ for c in pk_columns_raw
490
+ ]
491
+ for col in normalized:
492
+ if col not in child_schema["fields"]:
493
+ field_list = sorted(child_schema["fields"])
494
+ suffix = "..." if len(field_list) > 20 else ""
495
+ raise ValueError(
496
+ f"child PK column {col!r} not found in child fields: "
497
+ f"{field_list[:20]}{suffix}"
498
+ )
499
+ child_schema["fields"][col]["business_primary_key"] = True
500
+ child_schema["fields"][col]["inferred_pk"] = True
501
+ child_schema["business_primary_key"] = normalized
502
+
503
+
504
+ def _walk_properties(
505
+ *,
506
+ spec: Mapping[str, Any],
507
+ props: Mapping[str, Any],
508
+ parent_path: Tuple[str, ...],
509
+ parent_source_path: Tuple[str, ...],
510
+ fields: Dict[str, Dict[str, Any]],
511
+ children: Dict[str, Dict[str, Any]],
512
+ stream_name: str,
513
+ user_ref_prefixes: set,
514
+ user_schema_refs: frozenset[str],
515
+ ref_stack: frozenset[str] = frozenset(),
516
+ child_pk_overrides_ref: Mapping[str, Tuple[str, ...]] = None,
517
+ child_path_chain: Tuple[str, ...] = (),
518
+ flatten_nested_objects: bool = True,
519
+ preserve_original_names: bool = False,
520
+ ) -> None:
521
+ if child_pk_overrides_ref is None:
522
+ child_pk_overrides_ref = {}
523
+ for raw_name, raw_prop in props.items():
524
+ # Note User-ref detection BEFORE resolving, because resolution
525
+ # erases the $ref marker.
526
+ is_user = _is_user_ref(raw_prop, user_schema_refs)
527
+
528
+ # Cycle guard: if ANY $ref reachable from this property (direct
529
+ # or via allOf branches) is already on the walk stack, skip its
530
+ # nested expansion. Real example: Jira's IssueBean.fields
531
+ # embeds IssueBean recursively; multi-branch allOf compositions
532
+ # could otherwise cycle through a non-first branch.
533
+ prop_refs = _ref_names(raw_prop)
534
+ cycle_hit = prop_refs & ref_stack
535
+ if cycle_hit:
536
+ _LOGGER.debug(
537
+ "openapi_schema_builder: skipping recursive $ref(s) %r at "
538
+ "stream=%r source_path=%r (already on walk stack)",
539
+ sorted(cycle_hit),
540
+ stream_name,
541
+ ".".join(parent_source_path + (raw_name,)),
542
+ )
543
+ continue
544
+
545
+ prop = _resolve_schema(spec, raw_prop)
546
+ prop_type = prop.get("type")
547
+ # Extend the ref stack for nested descent with EVERY ref name
548
+ # reachable from this prop, not just the first.
549
+ next_ref_stack = ref_stack | prop_refs
550
+
551
+ if prop_type == "array":
552
+ items = prop.get("items") or {}
553
+ items_refs = _ref_names(items)
554
+ # If any array-items schema ref is already on the walk
555
+ # stack (IssueBean.subtasks contains IssueBean items), skip
556
+ # emitting a child table for it.
557
+ items_cycle_hit = items_refs & next_ref_stack
558
+ if items_cycle_hit:
559
+ _LOGGER.debug(
560
+ "openapi_schema_builder: skipping recursive array-items "
561
+ "$ref(s) %r at stream=%r source_path=%r",
562
+ sorted(items_cycle_hit),
563
+ stream_name,
564
+ ".".join(parent_source_path + (raw_name,)),
565
+ )
566
+ continue
567
+ resolved_items = _resolve_schema(spec, items) if items else {}
568
+ items_type = resolved_items.get("type")
569
+ if items_type == "object" or "properties" in resolved_items:
570
+ child_key = _normalize_column_segment(
571
+ raw_name,
572
+ preserve_original_names=preserve_original_names,
573
+ )
574
+ child_fields: Dict[str, Dict[str, Any]] = {}
575
+ child_children: Dict[str, Dict[str, Any]] = {}
576
+ child_user_refs: set = set()
577
+ child_ref_stack = next_ref_stack | items_refs
578
+ # FQ path for this child in the builder's native form.
579
+ # Uses child_path_chain (array-only descent) NOT parent_path
580
+ # (which tracks object-flattening and resets at child
581
+ # boundaries). Grandchildren reach here with
582
+ # child_path_chain = (..., outer_name) so the FQ key for
583
+ # Outer's `inner` array becomes "{stream}__outer__inner".
584
+ chain_for_this_child = child_path_chain + (child_key,)
585
+ fq_for_override = (
586
+ f"{stream_name}__" + "__".join(chain_for_this_child)
587
+ )
588
+ override = child_pk_overrides_ref.get(fq_for_override)
589
+ _walk_properties(
590
+ spec=spec,
591
+ props=resolved_items.get("properties") or {},
592
+ parent_path=(),
593
+ parent_source_path=(),
594
+ fields=child_fields,
595
+ children=child_children,
596
+ stream_name=stream_name,
597
+ user_ref_prefixes=child_user_refs,
598
+ user_schema_refs=user_schema_refs,
599
+ ref_stack=child_ref_stack,
600
+ child_pk_overrides_ref=child_pk_overrides_ref,
601
+ child_path_chain=chain_for_this_child,
602
+ flatten_nested_objects=flatten_nested_objects,
603
+ preserve_original_names=preserve_original_names,
604
+ )
605
+ _annotate_inferred_fks(
606
+ child_fields,
607
+ child_user_refs,
608
+ fk_hints={},
609
+ preserve_original_names=preserve_original_names,
610
+ )
611
+ if override is None:
612
+ inferred_raw: List[str] = _infer_child_business_pk(resolved_items)
613
+ else:
614
+ inferred_raw = list(override)
615
+ children[child_key] = {
616
+ "name": child_key,
617
+ "endpoint": None,
618
+ "schema_ref": items.get("$ref", "").rsplit("/", 1)[-1] or None,
619
+ "response_type": "embedded_array",
620
+ "data_path": None,
621
+ "business_primary_key": [],
622
+ "fields": child_fields,
623
+ "children": child_children,
624
+ }
625
+ _apply_child_pk(
626
+ children[child_key],
627
+ inferred_raw,
628
+ preserve_original_names=preserve_original_names,
629
+ )
630
+ # scalar-item arrays: skip entirely
631
+ continue
632
+
633
+ if prop_type == "object" or prop.get("properties"):
634
+ if not flatten_nested_objects:
635
+ # Connector wants a single json blob at the parent
636
+ # level (iterate_resource emission model). Skip
637
+ # recursive flattening and emit one column.
638
+ col_name = _flatten_column_name(
639
+ parent_path + (raw_name,),
640
+ preserve_original_names=preserve_original_names,
641
+ )
642
+ entry = empty_field_entry(col_name, "json")
643
+ entry["description"] = prop.get("description")
644
+ entry["source_path"] = ".".join(
645
+ parent_source_path + (raw_name,)
646
+ )
647
+ if col_name not in fields:
648
+ fields[col_name] = entry
649
+ continue
650
+ if is_user:
651
+ user_ref_prefixes.add(parent_path + (raw_name,))
652
+ _walk_properties(
653
+ spec=spec,
654
+ props=prop.get("properties") or {},
655
+ parent_path=parent_path + (raw_name,),
656
+ parent_source_path=parent_source_path + (raw_name,),
657
+ fields=fields,
658
+ children=children,
659
+ stream_name=stream_name,
660
+ user_ref_prefixes=user_ref_prefixes,
661
+ user_schema_refs=user_schema_refs,
662
+ ref_stack=next_ref_stack,
663
+ child_pk_overrides_ref=child_pk_overrides_ref,
664
+ child_path_chain=child_path_chain,
665
+ flatten_nested_objects=flatten_nested_objects,
666
+ preserve_original_names=preserve_original_names,
667
+ )
668
+ continue
669
+
670
+ if prop_type is None and ("oneOf" in prop or "anyOf" in prop):
671
+ # Polymorphic property -- the value can match any of several
672
+ # schemas at runtime. Union-flattening branches into sibling
673
+ # columns would misrepresent the shape (a given row populates
674
+ # exactly one branch), so collapse to a single ``json`` column
675
+ # and let the downstream destination handle the variant.
676
+ # Examples: GitHub ``event.payload`` is a ``oneOf`` of 16
677
+ # event subtypes; several Stripe objects use ``anyOf`` for
678
+ # expandable-reference fields.
679
+ col_name = _flatten_column_name(
680
+ parent_path + (raw_name,),
681
+ preserve_original_names=preserve_original_names,
682
+ )
683
+ entry = empty_field_entry(col_name, "json")
684
+ entry["description"] = prop.get("description")
685
+ entry["source_path"] = ".".join(parent_source_path + (raw_name,))
686
+ if col_name not in fields:
687
+ fields[col_name] = entry
688
+ continue
689
+
690
+ dlt_type = _map_type(prop)
691
+ if dlt_type is None:
692
+ # Genuinely unknown primitive -- not an object/array (those
693
+ # are handled above). Log so regressions in spec type
694
+ # coverage are observable without breaking the build.
695
+ if prop_type not in (None, "object", "array"):
696
+ _LOGGER.warning(
697
+ "openapi_schema_builder: unknown primitive type for "
698
+ "stream=%r source_path=%r type=%r format=%r -- skipping",
699
+ stream_name,
700
+ ".".join(parent_source_path + (raw_name,)),
701
+ prop_type,
702
+ prop.get("format"),
703
+ )
704
+ continue
705
+
706
+ col_name = _flatten_column_name(
707
+ parent_path + (raw_name,),
708
+ preserve_original_names=preserve_original_names,
709
+ )
710
+ entry = empty_field_entry(col_name, dlt_type)
711
+ entry["description"] = prop.get("description")
712
+ entry["format"] = prop.get("format")
713
+ entry["enum"] = prop.get("enum")
714
+ entry["source_path"] = ".".join(parent_source_path + (raw_name,))
715
+ if col_name not in fields:
716
+ fields[col_name] = entry
717
+
718
+
719
+ def _apply_business_primary_key_flags(
720
+ fields: Dict[str, Dict[str, Any]],
721
+ business_primary_key: Tuple[str, ...],
722
+ ) -> None:
723
+ """Flag every column in ``business_primary_key`` as the API's
724
+ natural key. Does NOT touch ``primary_key`` / ``unique`` keys --
725
+ those don't exist on the entry shape (they belong to _supa_id at
726
+ the Supaflow schema layer).
727
+
728
+ For composite PKs (workflows: ``("id__entity_id", "id__name")``)
729
+ every named column is flagged. _compute_supa_id_for_row needs all
730
+ of them present to hash correctly.
731
+ """
732
+ for pk in business_primary_key:
733
+ if pk not in fields:
734
+ field_list = sorted(fields)
735
+ suffix = "..." if len(field_list) > 20 else ""
736
+ raise ValueError(
737
+ f"business PK column {pk!r} not found in extracted "
738
+ f"fields: {field_list[:20]}{suffix}"
739
+ )
740
+ fields[pk]["business_primary_key"] = True
741
+ fields[pk]["inferred_pk"] = True
742
+
743
+
744
+ def _annotate_inferred_fks(
745
+ fields: Dict[str, Dict[str, Any]],
746
+ user_ref_prefixes: set,
747
+ fk_hints: Mapping[str, Tuple[str, str]],
748
+ *,
749
+ preserve_original_names: bool = False,
750
+ ) -> None:
751
+ # User-ref FKs: every <prefix>__account_id column where prefix is a
752
+ # User-typed ref gets an FK to users.account_id.
753
+ #
754
+ # Under ``preserve_original_names=True`` the column suffix stays
755
+ # source-shape (``accountId``); the FK target field is the
756
+ # business-PK column name on the ``users`` resource (which is
757
+ # also source-shape under preservation). Connectors that opt in
758
+ # MUST keep ``users.business_primary_key`` aligned with what dlt
759
+ # emits -- ``accountId`` under preserve, ``account_id`` under
760
+ # legacy.
761
+ target_field_name = (
762
+ "accountId" if preserve_original_names else "account_id"
763
+ )
764
+ for prefix_path in user_ref_prefixes:
765
+ col = _flatten_column_name(
766
+ prefix_path + ("accountId",),
767
+ preserve_original_names=preserve_original_names,
768
+ )
769
+ if col in fields:
770
+ fields[col]["foreign_key"] = {
771
+ "object": "users", "field": target_field_name,
772
+ }
773
+ fields[col]["inferred_fk"] = True
774
+ # Explicit overrides from the StreamSpec.
775
+ for col, (target_obj, target_field) in fk_hints.items():
776
+ if col in fields:
777
+ fields[col]["foreign_key"] = {"object": target_obj, "field": target_field}
778
+ fields[col]["inferred_fk"] = True