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,267 @@
1
+ """Identifier normalization utilities for S3/Parquet/Glue compatibility.
2
+
3
+ The ``normalize_identifier`` function produces output identical to the Java
4
+ ``S3PythonConnector.applyS3NamingConvention()`` method. Parity is critical --
5
+ if Python and Java produce different names for the same identifier, data lands
6
+ in the wrong S3 paths.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ import unicodedata
12
+
13
+
14
+ # ---------------------------------------------------------------------------
15
+ # Internal helpers
16
+ # ---------------------------------------------------------------------------
17
+
18
+ _CONSECUTIVE_UNDERSCORES = re.compile(r"_{2,}")
19
+
20
+ # Java Character.getType() categories for combining marks:
21
+ # COMBINING_SPACING_MARK (Mc), NON_SPACING_MARK (Mn), ENCLOSING_MARK (Me)
22
+ _COMBINING_MARK_CATEGORIES = frozenset({"Mn", "Mc", "Me"})
23
+
24
+
25
+ def _is_iso_control(ch: str) -> bool:
26
+ """Match Java's ``Character.isISOControl(c)`` exactly.
27
+
28
+ Returns True for U+0000-U+001F and U+007F-U+009F only.
29
+ """
30
+ cp = ord(ch)
31
+ return cp <= 0x1F or (0x7F <= cp <= 0x9F)
32
+
33
+
34
+ def _is_java_whitespace(ch: str) -> bool:
35
+ """Match Java's ``Character.isWhitespace(char)`` for BMP characters.
36
+
37
+ Java considers a char whitespace if it is:
38
+ - U+0009-U+000D (HT, LF, VT, FF, CR)
39
+ - U+001C-U+001F (FS, GS, RS, US)
40
+ - U+0020 (SPACE)
41
+ - A Unicode space separator (Zs) EXCEPT U+00A0, U+2007, U+202F
42
+ - A line separator (Zl: U+2028) or paragraph separator (Zp: U+2029)
43
+ """
44
+ cp = ord(ch)
45
+ # Fast path for common ASCII whitespace
46
+ if 0x09 <= cp <= 0x0D:
47
+ return True
48
+ if 0x1C <= cp <= 0x1F:
49
+ return True
50
+ if cp == 0x20:
51
+ return True
52
+ # Unicode separators
53
+ cat = unicodedata.category(ch)
54
+ if cat == "Zl" or cat == "Zp":
55
+ return True
56
+ if cat == "Zs":
57
+ # Exclude non-breaking spaces
58
+ return cp not in (0x00A0, 0x2007, 0x202F)
59
+ return False
60
+
61
+
62
+ def _is_ascii_alpha(ch: str) -> bool:
63
+ return ("A" <= ch <= "Z") or ("a" <= ch <= "z")
64
+
65
+
66
+ def _is_ascii_digit(ch: str) -> bool:
67
+ return "0" <= ch <= "9"
68
+
69
+
70
+ def _is_ascii_alnum_or_underscore(ch: str) -> bool:
71
+ return _is_ascii_alpha(ch) or _is_ascii_digit(ch) or ch == "_"
72
+
73
+
74
+ # ---------------------------------------------------------------------------
75
+ # Public API
76
+ # ---------------------------------------------------------------------------
77
+
78
+
79
+ def normalize_identifier(
80
+ name: str,
81
+ *,
82
+ max_length: int = 255,
83
+ case: str = "preserve",
84
+ ) -> str:
85
+ """Normalize an identifier for S3/Parquet/Glue compatibility.
86
+
87
+ Mirrors Java ``S3PythonConnector.applyS3NamingConvention()`` exactly:
88
+
89
+ 1. Return *name* unchanged if it is empty or consists only of whitespace.
90
+ 2. NFKD-normalize the string.
91
+ 3. Strip combining marks (Unicode categories Mn, Mc, Me).
92
+ 4. First char: keep ASCII alpha or ``_``; prepend ``_`` before an ASCII
93
+ digit; skip anything else (remain in first-char mode).
94
+ 5. Subsequent chars: keep ASCII alphanumeric or ``_``; replace Java
95
+ whitespace with ``_``; replace non-ISO-control chars with ``_``;
96
+ **drop** ISO control chars that are not Java whitespace.
97
+ 6. Collapse runs of underscores.
98
+ 7. Strip trailing underscores (keep at least one character).
99
+ 8. Return ``_`` if the result is empty after processing.
100
+ 9. Apply *case* transformation (``preserve`` / ``lower`` / ``upper``).
101
+ 10. Truncate to *max_length*.
102
+
103
+ Parameters
104
+ ----------
105
+ name:
106
+ The raw identifier string.
107
+ max_length:
108
+ Maximum length of the returned identifier (default 255).
109
+ case:
110
+ Case transformation: ``"preserve"`` (default), ``"lower"``, or
111
+ ``"upper"``.
112
+ """
113
+ # Step 1 -- blank / empty passthrough (matches Java String.isBlank())
114
+ # Java's String.isBlank() uses Character.isWhitespace() which excludes
115
+ # non-breaking spaces (U+00A0, U+2007, U+202F). Python's str.isspace()
116
+ # includes them. Use _is_java_whitespace for exact parity.
117
+ if not name:
118
+ return name
119
+ if all(_is_java_whitespace(ch) for ch in name):
120
+ return name
121
+
122
+ # Step 2 -- NFKD normalize
123
+ normalized = unicodedata.normalize("NFKD", name)
124
+
125
+ result: list[str] = []
126
+ is_first_char = True
127
+
128
+ for ch in normalized:
129
+ # Step 3 -- skip combining marks
130
+ if unicodedata.category(ch) in _COMBINING_MARK_CATEGORIES:
131
+ continue
132
+
133
+ if is_first_char:
134
+ # Step 4 -- first character rules
135
+ if _is_ascii_alpha(ch) or ch == "_":
136
+ result.append(ch)
137
+ is_first_char = False
138
+ elif _is_ascii_digit(ch):
139
+ result.append("_")
140
+ result.append(ch)
141
+ is_first_char = False
142
+ # else: skip, stay in first-char mode
143
+ else:
144
+ # Step 5 -- subsequent character rules
145
+ if _is_ascii_alnum_or_underscore(ch):
146
+ result.append(ch)
147
+ elif _is_java_whitespace(ch):
148
+ result.append("_")
149
+ elif not _is_iso_control(ch):
150
+ # Not alnum, not whitespace, not ISO control -> underscore
151
+ result.append("_")
152
+ # else: ISO control AND NOT whitespace -> dropped (no output)
153
+
154
+ # Step 8 -- empty result
155
+ if not result:
156
+ return "_"
157
+
158
+ output = "".join(result)
159
+
160
+ # Step 6 -- collapse consecutive underscores
161
+ output = _CONSECUTIVE_UNDERSCORES.sub("_", output)
162
+
163
+ # Step 7 -- strip trailing underscores (keep at least 1 char)
164
+ while output.endswith("_") and len(output) > 1:
165
+ output = output[:-1]
166
+
167
+ # Step 9 -- case transformation
168
+ if case == "lower":
169
+ output = output.lower()
170
+ elif case == "upper":
171
+ output = output.upper()
172
+
173
+ # Step 10 -- truncation
174
+ if len(output) > max_length:
175
+ output = output[:max_length]
176
+
177
+ return output
178
+
179
+
180
+ def resolve_collisions(names: list[str], *, max_length: int | None = 255) -> list[str]:
181
+ """Add numeric suffixes (``_1``, ``_2``, ...) for duplicates.
182
+
183
+ Matches Java ``S3PythonConnector.resolveCollision()`` which starts
184
+ suffixes at ``_1`` (not ``_2``). Collision detection is
185
+ case-insensitive. The first occurrence of each name is kept as-is;
186
+ subsequent duplicates receive ``_1``, ``_2``, etc.
187
+
188
+ Parameters
189
+ ----------
190
+ names:
191
+ List of (already-normalized) identifier strings.
192
+ max_length:
193
+ Maximum identifier length (default 255). Suffix is accounted
194
+ for by truncating the base name. Pass ``None`` to preserve the
195
+ full base name while still resolving collisions.
196
+
197
+ Returns
198
+ -------
199
+ list[str]:
200
+ A new list with collisions resolved.
201
+ """
202
+ seen: set[str] = set()
203
+ seen_lower: set[str] = set()
204
+ out: list[str] = []
205
+
206
+ for name in names:
207
+ # Truncate to max_length first (matches Java line 312-314)
208
+ candidate = (
209
+ name[:max_length]
210
+ if max_length is not None and len(name) > max_length
211
+ else name
212
+ )
213
+ if candidate not in seen and candidate.lower() not in seen_lower:
214
+ seen.add(candidate)
215
+ seen_lower.add(candidate.lower())
216
+ out.append(candidate)
217
+ continue
218
+
219
+ # Find a unique suffix starting at _1 (matches Java line 319)
220
+ for suffix_num in range(1, 10_000):
221
+ suffix_str = f"_{suffix_num}"
222
+ if max_length is None:
223
+ base = name
224
+ else:
225
+ max_base = max_length - len(suffix_str)
226
+ base = name[:max_base] if len(name) > max_base else name
227
+ candidate = base + suffix_str
228
+ if candidate not in seen and candidate.lower() not in seen_lower:
229
+ seen.add(candidate)
230
+ seen_lower.add(candidate.lower())
231
+ out.append(candidate)
232
+ break
233
+ else:
234
+ raise RuntimeError(f"Cannot resolve collision for: {name}")
235
+
236
+ return out
237
+
238
+
239
+ def apply_prefix(schema: str | None, prefix: str | None) -> str | None:
240
+ """Prepend *prefix* to a schema name.
241
+
242
+ Returns *schema* unchanged if it already starts with the prefix, or if
243
+ *prefix* is ``None`` / blank. If *schema* is ``None`` / blank, returns
244
+ the prefix itself.
245
+
246
+ Mirrors Java ``S3PythonConnector.applyGlueDatabasePrefix()`` logic.
247
+
248
+ Parameters
249
+ ----------
250
+ schema:
251
+ The schema (or Glue database) name. May be ``None``.
252
+ prefix:
253
+ The prefix to prepend. May be ``None``.
254
+ """
255
+ # If prefix is None or blank, return schema unchanged
256
+ if prefix is None or not prefix.strip():
257
+ return schema
258
+
259
+ # If schema is None or blank, return prefix
260
+ if schema is None or not schema.strip():
261
+ return prefix
262
+
263
+ # If schema already matches or starts with prefix_, return unchanged
264
+ if schema == prefix or schema.startswith(prefix + "_"):
265
+ return schema
266
+
267
+ return prefix + "_" + schema
@@ -0,0 +1,180 @@
1
+ """Native mapped JSONL emitter for Python BaseConnector reads.
2
+
3
+ The dlt runtime has its own JSONL path because dlt owns row normalization and
4
+ system-field enrichment there. This emitter is the equivalent framework path
5
+ for ordinary Python BaseConnector implementations: connectors keep calling
6
+ ``emit(record)`` with source-shaped rows and the runtime enriches + projects
7
+ them through the Java-provided RecordWritePlan.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import math
12
+ import numbers
13
+ from typing import Any
14
+
15
+ from supaflow_python_sdk.jsonl_record_emitter import JsonlRecordEmitter
16
+ from supaflow_python_sdk.models import MetadataField
17
+ from supaflow_python_sdk.source import RecordEmitResult
18
+ from supaflow_python_sdk.supa_id import HashField, compute_supa_id
19
+ from supaflow_python_sdk.write_plan import RecordWritePlan
20
+
21
+ _DELETED_STRING_TRUE = {"1", "true", "t", "yes", "y"}
22
+
23
+
24
+ def _field_attr(field: Any, snake_name: str, camel_name: str, default: Any = None) -> Any:
25
+ if field is None:
26
+ return default
27
+ if isinstance(field, dict):
28
+ if snake_name in field:
29
+ return field.get(snake_name)
30
+ if camel_name in field:
31
+ return field.get(camel_name)
32
+ return default
33
+ return getattr(field, snake_name, default)
34
+
35
+
36
+ def _coerce_deleted(value: Any) -> bool:
37
+ if isinstance(value, bool):
38
+ return value
39
+ if isinstance(value, numbers.Number):
40
+ try:
41
+ if math.isnan(value):
42
+ return False
43
+ except (TypeError, ValueError):
44
+ pass
45
+ return value != 0
46
+ if isinstance(value, str):
47
+ return value.strip().lower() in _DELETED_STRING_TRUE
48
+ return False
49
+
50
+
51
+ def _hash_fields(fields: list[Any]) -> list[HashField]:
52
+ out: list[HashField] = []
53
+ for field in fields or []:
54
+ name = _field_attr(field, "name", "name")
55
+ if not name:
56
+ continue
57
+ raw_selected = _field_attr(field, "selected", "selected")
58
+ out.append(
59
+ HashField(
60
+ name=str(name),
61
+ canonical_type=(
62
+ _field_attr(field, "canonical_type", "canonicalType")
63
+ or "STRING"
64
+ ),
65
+ primary_key=bool(_field_attr(field, "primary_key", "primaryKey")),
66
+ unique=bool(_field_attr(field, "unique", "unique")),
67
+ selected=False if raw_selected is False else True,
68
+ )
69
+ )
70
+ return out
71
+
72
+
73
+ def _deletion_indicator_name(fields: list[Any]) -> str | None:
74
+ for field in fields or []:
75
+ if bool(_field_attr(field, "deletion_indicator", "deletionIndicator", False)):
76
+ name = _field_attr(field, "name", "name")
77
+ return str(name) if name else None
78
+ return None
79
+
80
+
81
+ class NativeMappedJsonlRecordEmitter:
82
+ """Enrich source-shaped records and delegate destination JSONL writing.
83
+
84
+ System-field policy:
85
+ - _supa_id, _supa_index, and _supa_deleted are source-passthrough when the
86
+ incoming row has a non-null value. This preserves data-lake re-read
87
+ semantics for Supaflow-managed rows while repairing null placeholders.
88
+ - _supa_synced and _supa_job_id are always stamped from the current read
89
+ request because they describe this sync attempt, not the upstream row.
90
+ """
91
+
92
+ def __init__(
93
+ self,
94
+ *,
95
+ output_dir: str,
96
+ plan: RecordWritePlan | None,
97
+ fields: list[MetadataField],
98
+ sync_time: str | None,
99
+ job_details_id: str | None,
100
+ load_mode: str | None = None,
101
+ keyless_object_handling: str | None = None,
102
+ chunk_size: int | None = None,
103
+ ):
104
+ if plan is None:
105
+ raise ValueError("Native JSONL emission requires record_write_plan")
106
+ if not sync_time:
107
+ raise ValueError("Native JSONL emission requires sync_time")
108
+ if not job_details_id:
109
+ raise ValueError("Native JSONL emission requires job_details_id")
110
+
111
+ kwargs: dict[str, Any] = {"output_dir": output_dir, "plan": plan}
112
+ if chunk_size is not None:
113
+ kwargs["chunk_size"] = chunk_size
114
+ self._delegate = JsonlRecordEmitter(**kwargs)
115
+ self._fields = fields or []
116
+ self._hash_fields = _hash_fields(self._fields)
117
+ self._deletion_indicator_name = _deletion_indicator_name(self._fields)
118
+ self._sync_time = str(sync_time)
119
+ self._job_details_id = str(job_details_id)
120
+ self._load_mode = load_mode
121
+ self._keyless_object_handling = keyless_object_handling
122
+ self._next_supa_index = 1
123
+ self._supa_index_passthrough_mode: bool | None = None
124
+
125
+ def emit(self, record: dict[str, Any]) -> None:
126
+ enriched = dict(record)
127
+
128
+ if enriched.get("_supa_id") is None:
129
+ enriched["_supa_id"] = compute_supa_id(record, self._hash_fields, self._load_mode,
130
+ keyless_object_handling=self._keyless_object_handling)
131
+
132
+ has_supa_index = enriched.get("_supa_index") is not None
133
+ self._validate_supa_index_mode(has_supa_index)
134
+ if not has_supa_index:
135
+ enriched["_supa_index"] = self._next_supa_index
136
+
137
+ if enriched.get("_supa_deleted") is None:
138
+ raw_deleted = (
139
+ record.get(self._deletion_indicator_name)
140
+ if self._deletion_indicator_name is not None
141
+ else None
142
+ )
143
+ enriched["_supa_deleted"] = _coerce_deleted(
144
+ raw_deleted
145
+ )
146
+
147
+ enriched["_supa_synced"] = self._sync_time
148
+ # _supa_job_id identifies the source ReadRequest that produced the
149
+ # record. A materialized child writer is invoked by that parent read,
150
+ # so it intentionally inherits the parent request ID rather than the
151
+ # separate child destination-loading job-detail ID.
152
+ enriched["_supa_job_id"] = self._job_details_id
153
+
154
+ self._delegate.emit(enriched)
155
+ self._next_supa_index += 1
156
+
157
+ def _validate_supa_index_mode(self, has_supa_index: bool) -> None:
158
+ if self._supa_index_passthrough_mode is None:
159
+ self._supa_index_passthrough_mode = has_supa_index
160
+ return
161
+ if self._supa_index_passthrough_mode != has_supa_index:
162
+ raise ValueError(
163
+ "Native JSONL emission requires _supa_index to be all-or-nothing "
164
+ "per output object; mixed passthrough and generated rows would "
165
+ "produce ambiguous row ordering."
166
+ )
167
+
168
+ def complete(self) -> RecordEmitResult:
169
+ return self._delegate.complete()
170
+
171
+ def close(self) -> None:
172
+ self._delegate.close()
173
+
174
+ @property
175
+ def closed(self) -> bool:
176
+ return self._delegate.closed
177
+
178
+ @property
179
+ def output_dir(self) -> str:
180
+ return self._delegate.output_dir