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,146 @@
1
+ from __future__ import annotations
2
+
3
+ from abc import ABC, abstractmethod
4
+ from typing import Any
5
+
6
+ from supaflow_python_sdk.connector_definition import ConnectorDefinition
7
+ from supaflow_python_sdk.connector_identity import ConnectorPackageMetadata
8
+ from supaflow_python_sdk.models import (
9
+ InitRequest, InitResult,
10
+ StageRequest, StageResult,
11
+ LoadRequest, LoadResult,
12
+ MapTargetObjectRequest, MapTargetObjectResult,
13
+ SchemaRequest, SchemaResult,
14
+ ReadRequest, ReadResult,
15
+ MappedField,
16
+ )
17
+ from supaflow_python_sdk.errors import ConnectorError, ConnectorException, ErrorType
18
+
19
+
20
+ def _build_fqn(schema: str | None, name: str) -> str:
21
+ """Build a fully qualified name from schema and object name."""
22
+ if schema:
23
+ return f"{schema}.{name}"
24
+ return name
25
+
26
+
27
+ class BaseConnector(ABC):
28
+ """Base interface for Supaflow Python connectors.
29
+
30
+ Lifecycle: init() -> [map_target_object() per object] -> [stage() per object]
31
+ -> [load() per object] -> close()
32
+
33
+ init() is always called first. map_target_object() receives config and can
34
+ rely on authenticated state from init().
35
+
36
+ Definition metadata is optional. Authoring projects may declare DEFINITION
37
+ (or the compatible SPEC name); lifecycle-only implementations need neither.
38
+
39
+ Connector authors implement init() and stage() at minimum.
40
+ Override load() for post-stage operations (e.g., catalog registration).
41
+ Override map_target_object() for custom naming conventions.
42
+ """
43
+
44
+ @classmethod
45
+ def get_definition(cls) -> ConnectorDefinition | None:
46
+ """Read nearest optional metadata without changing the source class.
47
+
48
+ Raw inherited SPEC/DEFINITION attributes may differ before binding;
49
+ metadata callers use this accessor. The bound subclass has both aliases.
50
+ """
51
+ for base in cls.__mro__:
52
+ declared = vars(base)
53
+ if "DEFINITION" in declared:
54
+ if "SPEC" in declared and cls.SPEC is not cls.DEFINITION:
55
+ raise TypeError(f"{cls.__qualname__} declares different DEFINITION and SPEC objects")
56
+ return cls.DEFINITION
57
+ if "SPEC" in declared:
58
+ return cls.SPEC
59
+ return None
60
+
61
+ @classmethod
62
+ def _require_definition(cls) -> ConnectorDefinition:
63
+ definition = cls.get_definition()
64
+ if definition is None:
65
+ raise ValueError("Declare a connector definition as DEFINITION or SPEC before generating metadata")
66
+ return definition
67
+
68
+ @classmethod
69
+ def with_package_metadata(cls, metadata: ConnectorPackageMetadata) -> type[BaseConnector]:
70
+ """Return an isolated class with one resolved definition for this load."""
71
+ definition = cls._require_definition().with_package_metadata(metadata)
72
+ return type(cls.__name__, (cls,), {
73
+ "__module__": cls.__module__, "__qualname__": cls.__qualname__,
74
+ "DEFINITION": definition, "SPEC": definition,
75
+ })
76
+
77
+ @classmethod
78
+ def generated_manifest_dict(cls) -> dict[str, Any]:
79
+ return cls._require_definition().manifest_dict()
80
+
81
+ @classmethod
82
+ def generated_manifest(cls) -> dict[str, Any]:
83
+ return cls._require_definition().manifest_dict()
84
+
85
+ @classmethod
86
+ def generated_manifest_yaml(cls) -> str:
87
+ return cls._require_definition().render_manifest_yaml()
88
+
89
+ @abstractmethod
90
+ def init(self, request: InitRequest) -> InitResult:
91
+ """Validate config, authenticate, prepare working state."""
92
+
93
+ @abstractmethod
94
+ def stage(self, request: StageRequest) -> StageResult:
95
+ """Read CSV data and write to destination. Return manifest."""
96
+
97
+ def load(self, request: LoadRequest) -> LoadResult:
98
+ """Finalize data after staging. Default: no-op."""
99
+ return LoadResult(message="No explicit load step required")
100
+
101
+ def map_target_object(
102
+ self, request: MapTargetObjectRequest,
103
+ ) -> MapTargetObjectResult:
104
+ """Apply connector-specific naming. Default: accept proposed names."""
105
+ return MapTargetObjectResult(
106
+ schema_name=request.proposed_schema_name,
107
+ object_name=request.proposed_object_name,
108
+ fully_qualified_name=_build_fqn(
109
+ request.proposed_schema_name,
110
+ request.proposed_object_name,
111
+ ),
112
+ fields=[
113
+ MappedField(f.original_name, f.proposed_name)
114
+ for f in request.proposed_fields
115
+ ],
116
+ )
117
+
118
+ def schema(self, request: SchemaRequest) -> SchemaResult:
119
+ """Discover destination schema (catalogs, tables, fields).
120
+
121
+ Default: returns empty result. Override for connectors that
122
+ support destination schema discovery.
123
+ """
124
+ return SchemaResult(catalogs=[], objects=[])
125
+
126
+ def close(self) -> None:
127
+ """Clean up resources."""
128
+
129
+ def read(self, request: ReadRequest) -> ReadResult:
130
+ """Read records from source, emit via request.record_emitter.
131
+
132
+ Default: raises UNSUPPORTED. Override for source connectors.
133
+ """
134
+ raise ConnectorException(ConnectorError(
135
+ type=ErrorType.UNSUPPORTED,
136
+ message="This connector does not support read operations",
137
+ ))
138
+
139
+ def supports_direct_remote_load(self, request: ReadRequest | None = None) -> bool:
140
+ """Whether this source can return a RemoteLoadArtifact for this read.
141
+
142
+ Mirrors the Java ``SupaflowConnector.supportsDirectRemoteLoad`` default.
143
+ Connectors should return True only when the supplied request can be
144
+ served without streaming rows through ``request.record_emitter``.
145
+ """
146
+ return False
@@ -0,0 +1,74 @@
1
+ """Source capability defaults for connector manifests."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any
5
+
6
+
7
+ def source_capabilities() -> dict[str, Any]:
8
+ """Default manifest capabilities for Python source connectors."""
9
+ return {
10
+ "ingestion_mode": {
11
+ "values": ["HISTORICAL_PLUS_INCREMENTAL", "INCREMENTAL", "HISTORICAL"],
12
+ "default": "HISTORICAL_PLUS_INCREMENTAL",
13
+ "enabled": True,
14
+ },
15
+ "load_mode": {
16
+ "values": ["APPEND", "MERGE"],
17
+ "default": "APPEND",
18
+ "enabled": True,
19
+ },
20
+ "supports_staging": {"supported": False, "default": False},
21
+ "requires_staging": {"supported": False, "default": False},
22
+ "requires_explicit_load_step": {"supported": False, "default": False},
23
+ "supports_cdc": {"supported": False, "default": False},
24
+ "supports_checkpointing": {"supported": False, "default": False},
25
+ "supports_catalogs": {"supported": False, "default": False},
26
+ # Manifest-driven flag for connectors that surface MULTIPLE
27
+ # catalogs from a single source (e.g., a MongoDB cluster with
28
+ # several databases, a multi-warehouse Snowflake source). The
29
+ # Java bridge reads this via
30
+ # ``ConnectorManifestAdapter.supportsMultiCatalog`` to answer
31
+ # ``supportsMultiCatalog()`` -- before that wiring landed the
32
+ # bridge hardcoded ``false``, so leaving this slot at False
33
+ # by default preserves the historical behaviour for every
34
+ # existing Python connector. New multi-catalog connectors opt
35
+ # in by overriding the capability in their ``DltConnectorSpec``.
36
+ "supports_multi_catalog": {"supported": False, "default": False},
37
+ "supports_schemas": {"supported": False, "default": False},
38
+ "supports_target_mapping": {"supported": False, "default": False},
39
+ "supports_rate_limit": {"supported": True, "default": True},
40
+ # Authoritative sources (databases, fixed-resource APIs) treat an
41
+ # object that is no longer discovered as a real deletion, so the
42
+ # schema refresh marks it deleted and pipelines skip it. This matches
43
+ # the Java SDK default (SupaflowConnector.deleteMissingObjects). Only
44
+ # ephemeral/non-authoritative sources (e.g. file connectors where an
45
+ # empty folder between drops is normal) set this to False -- those are
46
+ # not DeclarativeDltConnector subclasses today.
47
+ "delete_missing_objects": True,
48
+ # All DeclarativeDltConnector subclasses build their schema via
49
+ # dlt normalize over a sample of records, which means two runs
50
+ # against the same source can assign different CanonicalTypes to
51
+ # the same column depending on which values the sample happens
52
+ # to contain. Declaring this capability tells the Java schema
53
+ # refresh service to run type stabilization
54
+ # (DatasourceSchemaRefreshService.stabilizeInferredTypes): if an
55
+ # incoming type is a subtype of the stored type or on a
56
+ # different branch of TypeHierarchy, the stored type is
57
+ # preserved rather than being overwritten. Widening transitions
58
+ # (e.g., INT -> BIGINT) still go through. This prevents sample
59
+ # variance from flip-flopping columns between, e.g., BIGINT and
60
+ # STRING on every run.
61
+ "has_inferred_schema_types": True,
62
+ # Whether the connector can fetch metadata for MULTIPLE schemas in one
63
+ # schema() call (a multi-element schema_list), so the refresh
64
+ # orchestrator can batch schemas into a single database-wide query
65
+ # instead of one call per schema. The Java bridge reads this via
66
+ # ``ConnectorManifestAdapter.supportsBatchedSchemaFetch`` to answer
67
+ # ``SupaflowConnector.supportsBatchedSchemaFetch()``. Python connectors
68
+ # build schema through dlt's per-source model and are NOT validated for
69
+ # multi-schema requests, so this stays False -- the orchestrator then
70
+ # keeps the per-schema fetch loop for them. This mirrors the Java SDK
71
+ # default; only the validated Java connectors (Snowflake / Postgres /
72
+ # SQL Server / Redshift) opt in (Java-side, not Python).
73
+ "supports_batched_schema_fetch": False,
74
+ }
@@ -0,0 +1,189 @@
1
+ """Catalog-safe identifier naming helpers.
2
+
3
+ These helpers are for external catalogs whose identifier surface is narrower
4
+ than a physical file format. They intentionally do not replace source-name
5
+ preservation for file formats that can store richer names directly.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import re
11
+ import threading
12
+ from functools import lru_cache
13
+ from typing import Iterable
14
+
15
+
16
+ # ICU4C/PyICU does not expose Java ICU4J's ``Any-Eng`` transliterator ID.
17
+ # ``Any-Latin`` plus accent removal gives the same catalog property we need:
18
+ # non-Latin identifiers become readable ASCII before Glue sanitization.
19
+ ICU_TRANSLITERATOR_ID = "Any-Latin; nfd; [:nonspacing mark:] remove; nfc"
20
+ GLUE_IDENTIFIER_MAX_BYTES = 255
21
+
22
+ _INVALID_GLUE_CHARS = re.compile(r"[^a-z0-9_]")
23
+ _CONSECUTIVE_UNDERSCORES = re.compile(r"_+")
24
+ _TRANSLITERATOR_LOCK = threading.Lock()
25
+
26
+
27
+ class CatalogNamingDependencyError(RuntimeError):
28
+ """Raised when the optional ICU transliteration dependency is missing."""
29
+
30
+
31
+ @lru_cache(maxsize=1)
32
+ def _icu_transliterator():
33
+ try:
34
+ from icu import Transliterator
35
+ except ImportError as exc:
36
+ raise CatalogNamingDependencyError(
37
+ "PyICU is required for catalog identifier transliteration. "
38
+ "Install the connector dependency 'PyICU'."
39
+ ) from exc
40
+
41
+ if hasattr(Transliterator, "createInstance"):
42
+ return Transliterator.createInstance(ICU_TRANSLITERATOR_ID)
43
+ return Transliterator.getInstance(ICU_TRANSLITERATOR_ID)
44
+
45
+
46
+ def transliterate_identifier(value: str) -> str:
47
+ """Transliterate *value* with the PyICU catalog transform."""
48
+ # ICU Transliterator instances are mutable. Serialize access to the cached
49
+ # instance so callers can safely use the helper from threaded connectors.
50
+ with _TRANSLITERATOR_LOCK:
51
+ return str(_icu_transliterator().transliterate(value))
52
+
53
+
54
+ def _fallback_identifier(original: str, kind: str) -> str:
55
+ prefixes = {
56
+ "column": "col",
57
+ "field": "col",
58
+ "table": "table",
59
+ "object": "table",
60
+ "schema": "db",
61
+ "database": "db",
62
+ "partition": "part",
63
+ }
64
+ prefix = prefixes.get(kind, "id")
65
+ digest = hashlib.sha1(original.encode("utf-8", errors="surrogatepass")).hexdigest()
66
+ return f"{prefix}_{digest[:12]}"
67
+
68
+
69
+ def _truncate_to_utf8_bytes(value: str, max_bytes: int) -> str:
70
+ if len(value.encode("utf-8")) <= max_bytes:
71
+ return value
72
+
73
+ out: list[str] = []
74
+ used = 0
75
+ for ch in value:
76
+ size = len(ch.encode("utf-8"))
77
+ if used + size > max_bytes:
78
+ break
79
+ out.append(ch)
80
+ used += size
81
+ return "".join(out)
82
+
83
+
84
+ def _has_identifier_content(value: str) -> bool:
85
+ return any(("a" <= ch <= "z") or ("0" <= ch <= "9") for ch in value)
86
+
87
+
88
+ def normalize_glue_identifier(
89
+ name: str,
90
+ *,
91
+ kind: str = "column",
92
+ max_bytes: int = GLUE_IDENTIFIER_MAX_BYTES,
93
+ ) -> str:
94
+ """Return a deterministic Glue/Athena-safe identifier.
95
+
96
+ The transformation is:
97
+ 1. ICU transliteration to Latin with accents removed.
98
+ 2. Lowercase and keep only ``[a-z0-9_]``.
99
+ 3. Collapse repeated separators without trimming meaningful underscores.
100
+ 4. Prefix leading digits with ``_``.
101
+ 5. Use a deterministic hash fallback when no letter/digit content remains.
102
+ 6. Enforce Glue's 255-byte identifier limit by default.
103
+ """
104
+ if name is None:
105
+ raise ValueError(f"{kind} name cannot be None")
106
+
107
+ original = str(name)
108
+ if not original.strip():
109
+ raise ValueError(f"{kind} name cannot be blank")
110
+
111
+ transliterated = transliterate_identifier(original)
112
+ candidate = _INVALID_GLUE_CHARS.sub("_", transliterated.lower())
113
+ candidate = _CONSECUTIVE_UNDERSCORES.sub("_", candidate)
114
+
115
+ if not candidate or not _has_identifier_content(candidate):
116
+ candidate = _fallback_identifier(original, kind)
117
+ elif candidate[0].isdigit():
118
+ candidate = "_" + candidate
119
+
120
+ candidate = _truncate_to_utf8_bytes(candidate, max_bytes)
121
+ if not candidate or not _has_identifier_content(candidate):
122
+ candidate = _fallback_identifier(original, kind)
123
+ candidate = _truncate_to_utf8_bytes(candidate, max_bytes)
124
+
125
+ return candidate
126
+
127
+
128
+ def resolve_glue_collisions(
129
+ names: Iterable[str],
130
+ *,
131
+ max_bytes: int = GLUE_IDENTIFIER_MAX_BYTES,
132
+ ) -> list[str]:
133
+ """Resolve case-insensitive catalog name collisions with numeric suffixes.
134
+
135
+ Collision ownership is intentionally input-order based: the first source
136
+ field/header column keeps the unsuffixed base name and later colliding
137
+ fields get ``_1``, ``_2``, etc. This mirrors the original Java S3 writer
138
+ and preserves existing source-field -> physical-column ownership. Do not
139
+ sort before resolving collisions; sorting would make the mapping look more
140
+ deterministic in isolation but can silently move the base physical column
141
+ from one source field to another.
142
+ """
143
+ seen: set[str] = set()
144
+ resolved: list[str] = []
145
+
146
+ for name in names:
147
+ candidate = _truncate_to_utf8_bytes(str(name), max_bytes)
148
+ if candidate.lower() not in seen:
149
+ seen.add(candidate.lower())
150
+ resolved.append(candidate)
151
+ continue
152
+
153
+ for suffix_num in range(1, 10_000):
154
+ suffix = f"_{suffix_num}"
155
+ base = _truncate_to_utf8_bytes(str(name), max_bytes - len(suffix))
156
+ candidate = base + suffix
157
+ if candidate.lower() not in seen:
158
+ seen.add(candidate.lower())
159
+ resolved.append(candidate)
160
+ break
161
+ else:
162
+ raise RuntimeError(f"Cannot resolve catalog name collision for: {name}")
163
+
164
+ return resolved
165
+
166
+
167
+ def normalize_glue_identifiers(
168
+ names: Iterable[str],
169
+ *,
170
+ kind: str = "column",
171
+ max_bytes: int = GLUE_IDENTIFIER_MAX_BYTES,
172
+ ) -> list[str]:
173
+ """Normalize identifiers and resolve catalog collisions in input order."""
174
+ normalized = [
175
+ normalize_glue_identifier(name, kind=kind, max_bytes=max_bytes)
176
+ for name in names
177
+ ]
178
+ return resolve_glue_collisions(normalized, max_bytes=max_bytes)
179
+
180
+
181
+ def build_glue_field_map(source_names: list[str]) -> dict[str, str]:
182
+ """Return ``{source_name: glue_name}`` for a field list in source order.
183
+
184
+ Callers must pass names in the same order as the staged CSV header / source
185
+ field list. The ordered collision policy is part of the writer contract,
186
+ and validators rely on the same full-header order to reproduce suffixes.
187
+ """
188
+ resolved = normalize_glue_identifiers(source_names, kind="column")
189
+ return dict(zip(source_names, resolved))
@@ -0,0 +1,44 @@
1
+ """Typed helpers for well-known keys inside SchemaObjectInfo.child_settings.
2
+
3
+ Connector authors use these during schema discovery to declare per-child
4
+ behavior without reaching into the raw dict.
5
+
6
+ Mirrors the Java-side split: supaflow_python_sdk.models.SchemaObjectInfo
7
+ exposes only a generic dict; typed enum handling lives in this module.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ from supaflow_python_sdk.models import SchemaObjectInfo
12
+
13
+ DELIVERY_MODE_KEY = "delivery_mode"
14
+
15
+ _VALID_DELIVERY_MODES = frozenset(("CONTEXT", "MATERIALIZED_CHILD_OUTPUT"))
16
+
17
+
18
+ def set_delivery_mode(obj: SchemaObjectInfo, mode: str) -> None:
19
+ """Declare how a parent connector delivers this child's data.
20
+
21
+ mode must be "CONTEXT" or "MATERIALIZED_CHILD_OUTPUT" -- validated at
22
+ write time so connector authors catch typos immediately.
23
+ """
24
+ if mode not in _VALID_DELIVERY_MODES:
25
+ raise ValueError(
26
+ f"Unknown delivery_mode: {mode!r}. "
27
+ f"Must be one of {sorted(_VALID_DELIVERY_MODES)}."
28
+ )
29
+ if obj.child_settings is None:
30
+ obj.child_settings = {}
31
+ obj.child_settings[DELIVERY_MODE_KEY] = mode
32
+
33
+
34
+ def get_delivery_mode(obj: SchemaObjectInfo) -> str:
35
+ """Read child_settings.delivery_mode. Missing/invalid/unknown -> "CONTEXT".
36
+
37
+ Runtime-safe: a SchemaObjectInfo with no child_settings, or a child_settings
38
+ dict with an unknown value, resolves to CONTEXT rather than raising.
39
+ Strict validation happens at set time, not read time.
40
+ """
41
+ if not obj.child_settings or not isinstance(obj.child_settings, dict):
42
+ return "CONTEXT"
43
+ raw = obj.child_settings.get(DELIVERY_MODE_KEY)
44
+ return raw if raw in _VALID_DELIVERY_MODES else "CONTEXT"
@@ -0,0 +1,10 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "connectorApiVersion": 1,
4
+ "hostApiVersion": 1,
5
+ "stageFormatVersions": {
6
+ "CSV": [1],
7
+ "MAPPED_JSONL": [1],
8
+ "NATIVE_MAPPED_JSONL": [1]
9
+ }
10
+ }