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.
- supaflow_python_sdk/__init__.py +150 -0
- supaflow_python_sdk/_definition_validation.py +220 -0
- supaflow_python_sdk/_legacy_manifest.py +89 -0
- supaflow_python_sdk/_legacy_naming.py +50 -0
- supaflow_python_sdk/_precision_json.py +74 -0
- supaflow_python_sdk/base_connector.py +146 -0
- supaflow_python_sdk/capabilities.py +74 -0
- supaflow_python_sdk/catalog_naming.py +189 -0
- supaflow_python_sdk/child_settings.py +44 -0
- supaflow_python_sdk/compatibility.json +10 -0
- supaflow_python_sdk/connector_definition.py +279 -0
- supaflow_python_sdk/connector_fixture.py +13 -0
- supaflow_python_sdk/connector_identity.py +55 -0
- supaflow_python_sdk/connector_property.py +97 -0
- supaflow_python_sdk/connector_resource.py +388 -0
- supaflow_python_sdk/csv_record_emitter.py +288 -0
- supaflow_python_sdk/cursor_candidates.py +167 -0
- supaflow_python_sdk/errors.py +130 -0
- supaflow_python_sdk/field_capabilities.py +50 -0
- supaflow_python_sdk/helpers.py +98 -0
- supaflow_python_sdk/host_api.py +102 -0
- supaflow_python_sdk/job_context.py +39 -0
- supaflow_python_sdk/jsonl_record_emitter.py +727 -0
- supaflow_python_sdk/keyless_object_handling.py +19 -0
- supaflow_python_sdk/models.py +1052 -0
- supaflow_python_sdk/naming.py +267 -0
- supaflow_python_sdk/native_mapped_jsonl_record_emitter.py +180 -0
- supaflow_python_sdk/oauth.py +399 -0
- supaflow_python_sdk/openapi_schema_builder.py +778 -0
- supaflow_python_sdk/property_rules.py +27 -0
- supaflow_python_sdk/py.typed +0 -0
- supaflow_python_sdk/resource_options.py +9 -0
- supaflow_python_sdk/schema_compliance.py +481 -0
- supaflow_python_sdk/source.py +165 -0
- supaflow_python_sdk/source_namespace.py +325 -0
- supaflow_python_sdk/supa_id.py +422 -0
- supaflow_python_sdk/temporal_stage_value.py +136 -0
- supaflow_python_sdk/type_inference.py +583 -0
- supaflow_python_sdk/ui.py +45 -0
- supaflow_python_sdk/write_plan.py +112 -0
- supaflow_python_sdk-1.0.74.dist-info/METADATA +80 -0
- supaflow_python_sdk-1.0.74.dist-info/RECORD +44 -0
- supaflow_python_sdk-1.0.74.dist-info/WHEEL +5 -0
- supaflow_python_sdk-1.0.74.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Role-specific metadata for shared connections; roles describe an operation."""
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from enum import Enum
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class ConnectionRole(str, Enum):
|
|
7
|
+
SOURCE = "SOURCE"
|
|
8
|
+
DESTINATION = "DESTINATION"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class PropertyValidationRule(str, Enum):
|
|
12
|
+
MUST_BE_TRUE = "MUST_BE_TRUE"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class PropertyValidation:
|
|
17
|
+
rule: PropertyValidationRule
|
|
18
|
+
message: str
|
|
19
|
+
|
|
20
|
+
def __post_init__(self):
|
|
21
|
+
if not isinstance(self.rule, PropertyValidationRule):
|
|
22
|
+
raise ValueError("Unsupported role validation rule")
|
|
23
|
+
if not isinstance(self.message, str) or not self.message.strip():
|
|
24
|
+
raise ValueError("Role validation requires a message")
|
|
25
|
+
|
|
26
|
+
def as_dict(self):
|
|
27
|
+
return {"rule": self.rule.value, "message": self.message}
|
|
File without changes
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Extension point for adapter-specific resource controls."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ResourceAdapterOptions:
|
|
5
|
+
"""Marker implemented by the owning adapter without an SDK dependency on it."""
|
|
6
|
+
|
|
7
|
+
def _apply_legacy_fields(self, resource) -> None:
|
|
8
|
+
"""The owning adapter handles deprecated fields without an SDK import."""
|
|
9
|
+
raise TypeError("The dlt adapter requires DltResourceOptions")
|
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
"""Python port of MetadataComplianceAssert.
|
|
2
|
+
|
|
3
|
+
Full parity with Java's io.supaflow.connector.sdk.test.MetadataComplianceAssert.
|
|
4
|
+
Validates that connector schema() output conforms to the metadata compliance
|
|
5
|
+
contract before it reaches the Java bridge / pipeline runtime.
|
|
6
|
+
|
|
7
|
+
Strict mode is the only mode. Both Python connectors (SFTP, S3) are in dev
|
|
8
|
+
and must pass all checks.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import logging
|
|
13
|
+
import os
|
|
14
|
+
|
|
15
|
+
from supaflow_python_sdk.models import SchemaObjectInfo, SchemaFieldInfo, SchemaResult
|
|
16
|
+
|
|
17
|
+
log = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
FRAMEWORK_IDENTITY_REQUIRED_ATTR = "supaflow_python_requires_framework_identity_fields"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
# ---------------------------------------------------------------------------
|
|
23
|
+
# Core validators -- mirror Java collectStrictViolations / collectStrategyWarnings
|
|
24
|
+
# ---------------------------------------------------------------------------
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def collect_strict_violations(
|
|
28
|
+
obj: SchemaObjectInfo,
|
|
29
|
+
*,
|
|
30
|
+
phase1_required: bool | None = None,
|
|
31
|
+
) -> list[str]:
|
|
32
|
+
"""Collect strict compliance violations for a single schema object.
|
|
33
|
+
|
|
34
|
+
Mirrors MetadataComplianceAssert.collectStrictViolations() in Java.
|
|
35
|
+
|
|
36
|
+
Phase 1 positive-shape invariants (``_supa_id`` present on every
|
|
37
|
+
object; root/child PK flag rules) are gated on ``phase1_required``:
|
|
38
|
+
|
|
39
|
+
- ``phase1_required=True`` -- object MUST include ``_supa_id``; a
|
|
40
|
+
missing ``_supa_id`` is a strict violation. Use this when the
|
|
41
|
+
caller has independently determined the object is part of a
|
|
42
|
+
Phase-1-compliant schema (e.g. ``collect_schema_violations``
|
|
43
|
+
derives it from the whole result).
|
|
44
|
+
- ``phase1_required=False`` -- object is known to be pre-Phase-1
|
|
45
|
+
(Mongo/SFTP today). The Phase-1 rule is skipped entirely.
|
|
46
|
+
- ``phase1_required=None`` (default) -- per-object opt-in: the rule
|
|
47
|
+
fires only when this object itself carries ``_supa_id`` in its
|
|
48
|
+
field list. Preserves backward-compat for direct callers.
|
|
49
|
+
|
|
50
|
+
The result-level helper ``collect_schema_violations`` upgrades the
|
|
51
|
+
per-object default to ``phase1_required=True`` only when framework-owned
|
|
52
|
+
discovery marks the result with ``FRAMEWORK_IDENTITY_REQUIRED_ATTR``.
|
|
53
|
+
Physical ``_supa_id`` columns in arbitrary catalog/file sources do not
|
|
54
|
+
imply the whole result is framework-owned.
|
|
55
|
+
"""
|
|
56
|
+
errors: list[str] = []
|
|
57
|
+
object_name = obj.name if obj.name else "<unknown-object>"
|
|
58
|
+
|
|
59
|
+
# --- Object-level runtime-critical fields ---
|
|
60
|
+
if not obj.name or not obj.name.strip():
|
|
61
|
+
errors.append("object name is null or blank")
|
|
62
|
+
if not obj.fully_qualified_name or not obj.fully_qualified_name.strip():
|
|
63
|
+
errors.append(f"fullyQualifiedName is null or blank on object: {object_name}")
|
|
64
|
+
if not obj.type or not obj.type.strip():
|
|
65
|
+
errors.append(f"type is null or blank on object: {object_name} "
|
|
66
|
+
"(source_metadata_catalog.object_type is NOT NULL)")
|
|
67
|
+
|
|
68
|
+
# --- Strategy flags ---
|
|
69
|
+
if not obj.incremental_strategy:
|
|
70
|
+
errors.append(f"incremental_strategy is null on object: {object_name}")
|
|
71
|
+
elif obj.incremental_strategy == "NONE":
|
|
72
|
+
errors.append(f"incremental_strategy=NONE is legacy and not allowed on object: {object_name}")
|
|
73
|
+
elif obj.incremental_strategy not in {"UNSUPPORTED", "COLUMN_CURSOR", "CONNECTOR_MANAGED"}:
|
|
74
|
+
errors.append(f"unknown incremental_strategy={obj.incremental_strategy!r} on object: {object_name}")
|
|
75
|
+
if not obj.identity_strategy:
|
|
76
|
+
errors.append(f"identity_strategy is null on object: {object_name}")
|
|
77
|
+
|
|
78
|
+
elif obj.identity_strategy not in {"SOURCE_KEY", "ROW_HASH", "NONE"}:
|
|
79
|
+
errors.append(f"unknown identity_strategy={obj.identity_strategy!r} on object: {object_name}")
|
|
80
|
+
|
|
81
|
+
# --- Field-level checks ---
|
|
82
|
+
source_cursor_fields: list[str] = []
|
|
83
|
+
if obj.fields:
|
|
84
|
+
for field in obj.fields:
|
|
85
|
+
field_name = field.name if field.name else "<unnamed>"
|
|
86
|
+
prefix = f"field '{field_name}' on object '{object_name}': "
|
|
87
|
+
|
|
88
|
+
# Runtime-critical
|
|
89
|
+
if not field.name or not field.name.strip():
|
|
90
|
+
errors.append(prefix + "name is null or blank")
|
|
91
|
+
if not field.canonical_type or not field.canonical_type.strip():
|
|
92
|
+
errors.append(prefix + "canonical_type is null or blank")
|
|
93
|
+
if not field.original_data_type or not field.original_data_type.strip():
|
|
94
|
+
errors.append(prefix + "original_data_type is null or blank "
|
|
95
|
+
"(required by CursorTrackingCSVRecordProcessor for CSV header row)")
|
|
96
|
+
|
|
97
|
+
# Numeric envelope: BIGDECIMAL must have valid precision/scale
|
|
98
|
+
if field.canonical_type == "BIGDECIMAL":
|
|
99
|
+
if field.precision is None:
|
|
100
|
+
errors.append(prefix + "BIGDECIMAL missing precision")
|
|
101
|
+
elif field.precision <= 0:
|
|
102
|
+
errors.append(prefix + f"BIGDECIMAL precision must be > 0, got {field.precision}")
|
|
103
|
+
elif field.precision > 38:
|
|
104
|
+
errors.append(prefix + f"BIGDECIMAL precision must be <= 38, got {field.precision}")
|
|
105
|
+
if field.scale is None:
|
|
106
|
+
errors.append(prefix + "BIGDECIMAL missing scale")
|
|
107
|
+
elif field.scale < 0:
|
|
108
|
+
errors.append(prefix + f"BIGDECIMAL scale must be >= 0, got {field.scale}")
|
|
109
|
+
elif field.scale > 37:
|
|
110
|
+
errors.append(prefix + f"BIGDECIMAL scale must be <= 37, got {field.scale}")
|
|
111
|
+
if (field.precision is not None and field.scale is not None
|
|
112
|
+
and field.scale > field.precision):
|
|
113
|
+
errors.append(prefix + f"BIGDECIMAL scale ({field.scale}) > precision ({field.precision})")
|
|
114
|
+
# DOUBLE/FLOAT are imprecise types -- precision/scale must be null.
|
|
115
|
+
# Carrying inference-derived precision/scale on these types generates
|
|
116
|
+
# invalid DDL in destination connectors (e.g., DOUBLE(40,38)).
|
|
117
|
+
if field.canonical_type in ("DOUBLE", "FLOAT"):
|
|
118
|
+
if field.precision is not None:
|
|
119
|
+
errors.append(prefix + f"{field.canonical_type} must not have precision (got {field.precision})")
|
|
120
|
+
if field.scale is not None:
|
|
121
|
+
errors.append(prefix + f"{field.canonical_type} must not have scale (got {field.scale})")
|
|
122
|
+
# Integer envelope: SHORT/INT/LONG must not carry precision/scale.
|
|
123
|
+
# Storing them is dead metadata at DataTypeMapper but leaks into the
|
|
124
|
+
# schema-evolution comparator and produces narrowing ALTERs.
|
|
125
|
+
# See docs/RCA_snowflake_number_precision_narrowing_alter.md.
|
|
126
|
+
if field.canonical_type in ("SHORT", "INT", "LONG"):
|
|
127
|
+
if field.precision is not None:
|
|
128
|
+
errors.append(prefix + f"{field.canonical_type} must not carry precision (got {field.precision})")
|
|
129
|
+
if field.scale is not None:
|
|
130
|
+
errors.append(prefix + f"{field.canonical_type} must not carry scale (got {field.scale})")
|
|
131
|
+
# Generic guard: scale without precision is never valid
|
|
132
|
+
if field.scale is not None and field.precision is None:
|
|
133
|
+
errors.append(prefix + "scale is set but precision is null")
|
|
134
|
+
|
|
135
|
+
# Capability flags: must be non-None
|
|
136
|
+
if field.cursor_capable is None:
|
|
137
|
+
errors.append(prefix + "cursor_capable is None")
|
|
138
|
+
if field.primary_key_capable is None:
|
|
139
|
+
errors.append(prefix + "primary_key_capable is None")
|
|
140
|
+
|
|
141
|
+
# Source flags: sparse booleans (True or None, never False)
|
|
142
|
+
if field.source_primary_key is False:
|
|
143
|
+
errors.append(prefix + "source_primary_key is False (should be None, not False)")
|
|
144
|
+
if field.source_cursor_field is False:
|
|
145
|
+
errors.append(prefix + "source_cursor_field is False (should be None, not False)")
|
|
146
|
+
|
|
147
|
+
if field.source_cursor_field is True:
|
|
148
|
+
source_cursor_fields.append(field_name)
|
|
149
|
+
|
|
150
|
+
# Supaflow system identity is not a source key. Connectors may
|
|
151
|
+
# emit _supa_id as an unflagged system column, and downstream
|
|
152
|
+
# loading may merge on it, but schema discovery must not mark it
|
|
153
|
+
# as either a source PK or a user-selection PK.
|
|
154
|
+
if field_name.lower() == "_supa_id":
|
|
155
|
+
if field.source_primary_key is True:
|
|
156
|
+
errors.append(
|
|
157
|
+
prefix + "_supa_id must NOT be source_primary_key=True "
|
|
158
|
+
"(it is Supaflow's internal row identity, not a source key)"
|
|
159
|
+
)
|
|
160
|
+
if field.primary_key is not None:
|
|
161
|
+
errors.append(
|
|
162
|
+
prefix + "_supa_id must NOT set primary_key in discovery "
|
|
163
|
+
"(destination merge key is handled separately)"
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
# --- Positive shape invariant (Phase 1) ---
|
|
167
|
+
# These checks enforce the root/child identity contract introduced by the
|
|
168
|
+
# _supa_id / business-PK separation. They only apply when the object has
|
|
169
|
+
# fields (TABLES_ONLY discovery has no field-level data).
|
|
170
|
+
#
|
|
171
|
+
# Scope gate (``phase1_required``): see docstring. In the default
|
|
172
|
+
# per-object mode, the rule fires only when this object already
|
|
173
|
+
# contains ``_supa_id``, which is convenient for unit-test fixtures
|
|
174
|
+
# that assert shape rules in isolation. The result-level helper only
|
|
175
|
+
# passes ``phase1_required=True`` when framework-owned discovery marks
|
|
176
|
+
# the result, so external catalog/file sources can expose mixed
|
|
177
|
+
# physical tables without turning one ``_supa_id`` column into a
|
|
178
|
+
# global schema-wide requirement.
|
|
179
|
+
#
|
|
180
|
+
# Root: parent_object_name is None AND object_type != "ASSOCIATION"
|
|
181
|
+
# Child: parent_object_name is not None OR object_type == "ASSOCIATION"
|
|
182
|
+
if obj.fields:
|
|
183
|
+
field_names = [f.name for f in obj.fields]
|
|
184
|
+
pk_flagged = [f.name for f in obj.fields if f.source_primary_key is True]
|
|
185
|
+
supa_id_present = "_supa_id" in field_names
|
|
186
|
+
|
|
187
|
+
if phase1_required is None:
|
|
188
|
+
apply_phase1 = supa_id_present
|
|
189
|
+
else:
|
|
190
|
+
apply_phase1 = phase1_required
|
|
191
|
+
|
|
192
|
+
if apply_phase1:
|
|
193
|
+
if not supa_id_present:
|
|
194
|
+
errors.append(
|
|
195
|
+
f"object '{object_name}': _supa_id missing from fields "
|
|
196
|
+
f"(Phase-1 contract requires the framework row-identity "
|
|
197
|
+
f"column on every object in the schema result)"
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
# Task 18: when _supa_id is present, _supa_index MUST also be
|
|
201
|
+
# present AND MUST be unflagged (neither source_primary_key nor
|
|
202
|
+
# source_cursor_field). Position is an emit-time contract
|
|
203
|
+
# enforced by the runtime constructors; here we only enforce
|
|
204
|
+
# the presence-pairing and flag invariant (schema-local, no
|
|
205
|
+
# DltResourceSpec context required).
|
|
206
|
+
supa_index_field = next(
|
|
207
|
+
(f for f in obj.fields if f.name == "_supa_index"), None
|
|
208
|
+
)
|
|
209
|
+
if supa_index_field is None:
|
|
210
|
+
errors.append(
|
|
211
|
+
f"object '{object_name}': _supa_index missing from fields "
|
|
212
|
+
f"(Task-18 contract requires _supa_index alongside _supa_id "
|
|
213
|
+
f"on every Phase-1 object)"
|
|
214
|
+
)
|
|
215
|
+
else:
|
|
216
|
+
if supa_index_field.source_primary_key is True:
|
|
217
|
+
errors.append(
|
|
218
|
+
f"object '{object_name}': _supa_index must NOT be "
|
|
219
|
+
f"source_primary_key=True (it is an unflagged system column)"
|
|
220
|
+
)
|
|
221
|
+
if supa_index_field.source_cursor_field is True:
|
|
222
|
+
errors.append(
|
|
223
|
+
f"object '{object_name}': _supa_index must NOT be "
|
|
224
|
+
f"source_cursor_field=True (it is an unflagged system column)"
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
is_child = (
|
|
228
|
+
obj.parent_object_name is not None
|
|
229
|
+
or obj.object_type == "ASSOCIATION"
|
|
230
|
+
)
|
|
231
|
+
is_root = not is_child
|
|
232
|
+
|
|
233
|
+
if is_root:
|
|
234
|
+
# Phase 1 root contract:
|
|
235
|
+
# - _supa_id must NOT be source_primary_key=True.
|
|
236
|
+
# - Zero or more business fields may carry source_primary_key=True.
|
|
237
|
+
# Composite PKs (e.g. ["id__entity_id", "id__name"] on Jira
|
|
238
|
+
# workflows) are fully legal -- all parts carry the flag.
|
|
239
|
+
# Zero business PKs is legal (connector declared primary_key=None,
|
|
240
|
+
# schemaless source, or user is expected to pick in the wizard).
|
|
241
|
+
# The check excludes _supa_id from the business-PK set so that
|
|
242
|
+
# the _supa_id-is-flagged violation is not double-reported.
|
|
243
|
+
if "_supa_id" in pk_flagged:
|
|
244
|
+
errors.append(
|
|
245
|
+
f"object '{object_name}' (root): _supa_id must NOT be "
|
|
246
|
+
f"source_primary_key=True on roots (Phase 1)"
|
|
247
|
+
)
|
|
248
|
+
else:
|
|
249
|
+
# Phase-2 child contract: _supa_id must be present (checked above)
|
|
250
|
+
# and must NOT carry source_primary_key=True. Zero or more business
|
|
251
|
+
# fields may carry source_primary_key=True (same symmetry as roots).
|
|
252
|
+
# There is no upper-bound on business PK count -- composite keys are
|
|
253
|
+
# fully legal. There is no lower-bound either -- schemaless children
|
|
254
|
+
# (primary_key=None, Case B identity) are valid with zero flagged
|
|
255
|
+
# business fields.
|
|
256
|
+
#
|
|
257
|
+
# "The N flagged business fields match the spec's child_primary_keys"
|
|
258
|
+
# is a connector-level assertion enforced in live audits (Task 16),
|
|
259
|
+
# not here. Compliance is schema-local and receives no spec context.
|
|
260
|
+
if "_supa_id" in pk_flagged:
|
|
261
|
+
errors.append(
|
|
262
|
+
f"object '{object_name}' (child): _supa_id must NOT be "
|
|
263
|
+
f"source_primary_key=True on children (Phase 2)"
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
# Cross-field: UNSUPPORTED and CONNECTOR_MANAGED both mean column-level
|
|
267
|
+
# cursor tracking does not apply, so source_cursor_field=True is a
|
|
268
|
+
# contradiction for either strategy.
|
|
269
|
+
if obj.incremental_strategy == "UNSUPPORTED" and source_cursor_fields:
|
|
270
|
+
errors.append(
|
|
271
|
+
f"object '{object_name}': incremental_strategy=UNSUPPORTED cannot set "
|
|
272
|
+
f"source_cursor_field=True (fields: {', '.join(source_cursor_fields)})"
|
|
273
|
+
)
|
|
274
|
+
if obj.incremental_strategy == "CONNECTOR_MANAGED" and source_cursor_fields:
|
|
275
|
+
errors.append(
|
|
276
|
+
f"object '{object_name}': incremental_strategy=CONNECTOR_MANAGED cannot set "
|
|
277
|
+
f"source_cursor_field=True (fields: {', '.join(source_cursor_fields)})"
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
return errors
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def collect_strategy_warnings(obj: SchemaObjectInfo) -> list[str]:
|
|
284
|
+
"""Collect non-fatal strategy warnings.
|
|
285
|
+
|
|
286
|
+
Mirrors MetadataComplianceAssert.collectStrategyWarnings() in Java.
|
|
287
|
+
"""
|
|
288
|
+
warnings: list[str] = []
|
|
289
|
+
object_name = obj.name if obj.name else "<unknown-object>"
|
|
290
|
+
|
|
291
|
+
if not obj.incremental_strategy:
|
|
292
|
+
return warnings
|
|
293
|
+
|
|
294
|
+
source_cursor_fields = _get_source_cursor_field_names(obj)
|
|
295
|
+
|
|
296
|
+
# Note: CONNECTOR_MANAGED + source_cursor_field=True is now a strict
|
|
297
|
+
# violation (see collect_strict_violations). Kept the COLUMN_CURSOR
|
|
298
|
+
# warning below for the locked-but-empty case.
|
|
299
|
+
if (obj.incremental_strategy == "COLUMN_CURSOR"
|
|
300
|
+
and not source_cursor_fields
|
|
301
|
+
and obj.cursor_field_locked is True):
|
|
302
|
+
warnings.append(
|
|
303
|
+
f"object '{object_name}': incremental_strategy=COLUMN_CURSOR has no "
|
|
304
|
+
f"source_cursor_field=True while cursor_field_locked=True"
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
return warnings
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def assert_no_selection_flags_in_catalog(obj: SchemaObjectInfo) -> None:
|
|
311
|
+
"""Assert that discovery output never sets user-selection flags.
|
|
312
|
+
|
|
313
|
+
cursor_field and primary_key are owned by the merge/selection layer,
|
|
314
|
+
not by connectors during schema discovery.
|
|
315
|
+
|
|
316
|
+
Mirrors MetadataComplianceAssert.assertNoSelectionFlagsInCatalog() in Java.
|
|
317
|
+
"""
|
|
318
|
+
errors: list[str] = []
|
|
319
|
+
if obj.fields:
|
|
320
|
+
for field in obj.fields:
|
|
321
|
+
if field.cursor_field is not None:
|
|
322
|
+
errors.append(
|
|
323
|
+
f"cursor_field (user-selection) must not be set in discovery: "
|
|
324
|
+
f"{field.name} on {obj.name} (value={field.cursor_field})"
|
|
325
|
+
)
|
|
326
|
+
if field.primary_key is not None:
|
|
327
|
+
errors.append(
|
|
328
|
+
f"primary_key (user-selection) must not be set in discovery: "
|
|
329
|
+
f"{field.name} on {obj.name} (value={field.primary_key})"
|
|
330
|
+
)
|
|
331
|
+
if errors:
|
|
332
|
+
raise AssertionError(
|
|
333
|
+
"Selection flag violations:\n- " + "\n- ".join(errors)
|
|
334
|
+
)
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
# ---------------------------------------------------------------------------
|
|
338
|
+
# SchemaResult-level helpers
|
|
339
|
+
# ---------------------------------------------------------------------------
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def collect_schema_violations(result: SchemaResult) -> list[str]:
|
|
343
|
+
"""Collect strict violations across all objects in a SchemaResult.
|
|
344
|
+
|
|
345
|
+
The result-level Phase-1 signal is explicit: framework-owned schema
|
|
346
|
+
builders mark objects with ``FRAMEWORK_IDENTITY_REQUIRED_ATTR`` when
|
|
347
|
+
every object in the result is expected to include the Supaflow identity
|
|
348
|
+
fields. This keeps the original guardrail for dlt/declarative connectors
|
|
349
|
+
(a root accidentally dropping ``_supa_id`` while its children keep it
|
|
350
|
+
fails loudly), without treating arbitrary external catalogs as
|
|
351
|
+
homogeneous. Catalog/file sources can legitimately expose a mixed set of
|
|
352
|
+
physical tables where some were written by Supaflow and some were not.
|
|
353
|
+
"""
|
|
354
|
+
errors: list[str] = []
|
|
355
|
+
if not result.objects:
|
|
356
|
+
return errors
|
|
357
|
+
|
|
358
|
+
phase1_required = any(
|
|
359
|
+
_framework_identity_required(obj)
|
|
360
|
+
for obj in result.objects
|
|
361
|
+
)
|
|
362
|
+
phase1_signal = True if phase1_required else None
|
|
363
|
+
|
|
364
|
+
for obj in result.objects:
|
|
365
|
+
errors.extend(collect_strict_violations(
|
|
366
|
+
obj, phase1_required=phase1_signal
|
|
367
|
+
))
|
|
368
|
+
return errors
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def assert_strict_schema_result(result: SchemaResult) -> None:
|
|
372
|
+
"""Assert that a SchemaResult passes the full strict metadata contract.
|
|
373
|
+
|
|
374
|
+
Call this in connector unit tests right after connector.schema():
|
|
375
|
+
|
|
376
|
+
result = connector.schema(req)
|
|
377
|
+
assert_strict_schema_result(result)
|
|
378
|
+
|
|
379
|
+
Also checks no selection flags leaked into discovery output.
|
|
380
|
+
|
|
381
|
+
Raises:
|
|
382
|
+
AssertionError: if any violations found
|
|
383
|
+
"""
|
|
384
|
+
errors = collect_schema_violations(result)
|
|
385
|
+
if errors:
|
|
386
|
+
raise AssertionError(
|
|
387
|
+
f"Schema compliance violations ({len(errors)}):\n- "
|
|
388
|
+
+ "\n- ".join(errors)
|
|
389
|
+
)
|
|
390
|
+
# Also check no selection flags in catalog
|
|
391
|
+
if result.objects:
|
|
392
|
+
for obj in result.objects:
|
|
393
|
+
assert_no_selection_flags_in_catalog(obj)
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
# Keep old name as alias for backward compatibility with existing tests
|
|
397
|
+
assert_schema_result_contract = assert_strict_schema_result
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
# ---------------------------------------------------------------------------
|
|
401
|
+
# Host-level validation (called from host.py)
|
|
402
|
+
# ---------------------------------------------------------------------------
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def validate_schema_response(result: SchemaResult) -> None:
|
|
406
|
+
"""Validate schema response in the host process.
|
|
407
|
+
|
|
408
|
+
Called when DEPLOY_ENV=dev or SUPAFLOW_VALIDATE_SCHEMA=1.
|
|
409
|
+
Logs violations and raises to fail fast before Java bridge.
|
|
410
|
+
|
|
411
|
+
Mirrors Java SchemaResponse.validateMetadataCompliance():
|
|
412
|
+
- FULL level (totalFields > 0): run complete strict contract
|
|
413
|
+
- TABLES_ONLY level (totalFields == 0): only validate object identity
|
|
414
|
+
(name, FQN). Strategies and field-level checks are not applicable.
|
|
415
|
+
"""
|
|
416
|
+
total_fields = sum(
|
|
417
|
+
len(obj.fields) for obj in (result.objects or []) if obj.fields
|
|
418
|
+
)
|
|
419
|
+
|
|
420
|
+
errors: list[str] = []
|
|
421
|
+
warnings: list[str] = []
|
|
422
|
+
|
|
423
|
+
if total_fields > 0:
|
|
424
|
+
# FULL level: run the complete strict contract (source discovery)
|
|
425
|
+
errors = collect_schema_violations(result)
|
|
426
|
+
if result.objects:
|
|
427
|
+
for obj in result.objects:
|
|
428
|
+
warnings.extend(collect_strategy_warnings(obj))
|
|
429
|
+
# Check for selection flags leaked into discovery output
|
|
430
|
+
if result.objects:
|
|
431
|
+
for obj in result.objects:
|
|
432
|
+
if obj.fields:
|
|
433
|
+
for field in obj.fields:
|
|
434
|
+
if field.cursor_field is not None:
|
|
435
|
+
errors.append(
|
|
436
|
+
f"cursor_field (user-selection) must not be set in discovery: "
|
|
437
|
+
f"{field.name} on {obj.name} (value={field.cursor_field})"
|
|
438
|
+
)
|
|
439
|
+
if field.primary_key is not None:
|
|
440
|
+
errors.append(
|
|
441
|
+
f"primary_key (user-selection) must not be set in discovery: "
|
|
442
|
+
f"{field.name} on {obj.name} (value={field.primary_key})"
|
|
443
|
+
)
|
|
444
|
+
else:
|
|
445
|
+
# TABLES_ONLY level: only validate object identity
|
|
446
|
+
if result.objects:
|
|
447
|
+
for obj in result.objects:
|
|
448
|
+
object_name = obj.name if obj.name else "<unknown-object>"
|
|
449
|
+
if not obj.name or not obj.name.strip():
|
|
450
|
+
errors.append("object name is null or blank")
|
|
451
|
+
if not obj.fully_qualified_name or not obj.fully_qualified_name.strip():
|
|
452
|
+
errors.append(f"fullyQualifiedName is null or blank on object: {object_name}")
|
|
453
|
+
|
|
454
|
+
if warnings:
|
|
455
|
+
log.warning("[DEV] Schema compliance warnings: %d\n%s",
|
|
456
|
+
len(warnings), "\n".join(warnings))
|
|
457
|
+
|
|
458
|
+
if errors:
|
|
459
|
+
msg = (f"[DEV] Schema compliance violations: {len(errors)}\n"
|
|
460
|
+
+ "\n".join(errors))
|
|
461
|
+
log.error(msg)
|
|
462
|
+
raise ValueError(msg)
|
|
463
|
+
|
|
464
|
+
log.info("[DEV] Schema compliance passed: %d objects, %d fields",
|
|
465
|
+
len(result.objects or []), total_fields)
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
# ---------------------------------------------------------------------------
|
|
469
|
+
# Internal helpers
|
|
470
|
+
# ---------------------------------------------------------------------------
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def _get_source_cursor_field_names(obj: SchemaObjectInfo) -> list[str]:
|
|
474
|
+
if not obj.fields:
|
|
475
|
+
return []
|
|
476
|
+
return [f.name for f in obj.fields if f.source_cursor_field is True]
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def _framework_identity_required(obj: SchemaObjectInfo) -> bool:
|
|
480
|
+
attrs = getattr(obj, "custom_attributes", None)
|
|
481
|
+
return isinstance(attrs, dict) and attrs.get(FRAMEWORK_IDENTITY_REQUIRED_ATTR) is True
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Public abstractions for source read operations.
|
|
2
|
+
|
|
3
|
+
Connector authors program against these interfaces. They know nothing about
|
|
4
|
+
CSV, files, or transport. Runtime implementations are injected by the host.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from abc import ABC, abstractmethod
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import TYPE_CHECKING, Any
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from supaflow_python_sdk.models import SyncStateResponse
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
# ---------------------------------------------------------------------------
|
|
17
|
+
# Record emission
|
|
18
|
+
# ---------------------------------------------------------------------------
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class RecordEmitResult:
|
|
23
|
+
"""Statistics from the record emission phase."""
|
|
24
|
+
|
|
25
|
+
records_emitted: int
|
|
26
|
+
error_count: int = 0
|
|
27
|
+
bytes_written: int | None = None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class RecordEmitter(ABC):
|
|
31
|
+
"""Generic interface for emitting records during a source read.
|
|
32
|
+
|
|
33
|
+
The connector calls emit() for each record fetched from the source,
|
|
34
|
+
then complete() when done. The runtime decides how records are
|
|
35
|
+
transported (CSV, streaming, etc.).
|
|
36
|
+
|
|
37
|
+
emit() returns None, not bool. The Java processRecord() -> bool
|
|
38
|
+
include/skip semantic cannot be faithfully provided across the process
|
|
39
|
+
boundary because the Java processor runs after Python has already
|
|
40
|
+
written the record.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
@abstractmethod
|
|
44
|
+
def emit(self, record: dict[str, Any]) -> None:
|
|
45
|
+
"""Emit a single record to the output."""
|
|
46
|
+
|
|
47
|
+
@abstractmethod
|
|
48
|
+
def complete(self) -> RecordEmitResult:
|
|
49
|
+
"""Finalize emission. Flush buffers, return statistics."""
|
|
50
|
+
|
|
51
|
+
@abstractmethod
|
|
52
|
+
def close(self) -> None:
|
|
53
|
+
"""Release resources."""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# ---------------------------------------------------------------------------
|
|
57
|
+
# Parent context reading
|
|
58
|
+
# ---------------------------------------------------------------------------
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class ParentContextReader(ABC):
|
|
62
|
+
"""Reads parent-object context records for child-object reads.
|
|
63
|
+
|
|
64
|
+
Mirrors Java Iterator<Map<String, Object>> from
|
|
65
|
+
ReadRequest.parentContextIterator.
|
|
66
|
+
|
|
67
|
+
Supports Python iteration: ``for record in reader: ...``
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
@abstractmethod
|
|
71
|
+
def has_next(self) -> bool:
|
|
72
|
+
"""Return True if more parent context records are available."""
|
|
73
|
+
|
|
74
|
+
@abstractmethod
|
|
75
|
+
def next(self) -> dict[str, Any]:
|
|
76
|
+
"""Return the next parent context record."""
|
|
77
|
+
|
|
78
|
+
@abstractmethod
|
|
79
|
+
def close(self) -> None:
|
|
80
|
+
"""Release resources (file handles, connections).
|
|
81
|
+
|
|
82
|
+
Called by the host in a ``finally`` block after the read completes.
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
def __iter__(self):
|
|
86
|
+
return self
|
|
87
|
+
|
|
88
|
+
def __next__(self):
|
|
89
|
+
if not self.has_next():
|
|
90
|
+
raise StopIteration
|
|
91
|
+
return self.next()
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# ---------------------------------------------------------------------------
|
|
95
|
+
# Child context writing
|
|
96
|
+
# ---------------------------------------------------------------------------
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class ChildContextWriter(ABC):
|
|
100
|
+
"""Writes parent-ID records to a child object's context.
|
|
101
|
+
|
|
102
|
+
Mirrors ChildContextInfo.contextProcessor.processRecord().
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
@abstractmethod
|
|
106
|
+
def emit(self, record: dict[str, Any]) -> None:
|
|
107
|
+
"""Write a parent-ID record to this child's context."""
|
|
108
|
+
|
|
109
|
+
@abstractmethod
|
|
110
|
+
def close(self) -> None:
|
|
111
|
+
"""Flush and release resources."""
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
# ---------------------------------------------------------------------------
|
|
115
|
+
# Checkpointing
|
|
116
|
+
# ---------------------------------------------------------------------------
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class CheckpointEmitter(ABC):
|
|
120
|
+
"""Emits intermediate sync state during long reads.
|
|
121
|
+
|
|
122
|
+
Mirrors CheckpointCallback.onCheckpoint().
|
|
123
|
+
"""
|
|
124
|
+
|
|
125
|
+
@abstractmethod
|
|
126
|
+
def checkpoint(self, sync_state: SyncStateResponse) -> None:
|
|
127
|
+
"""Emit intermediate sync state."""
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
# ---------------------------------------------------------------------------
|
|
131
|
+
# Progress reporting
|
|
132
|
+
# ---------------------------------------------------------------------------
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@dataclass
|
|
136
|
+
class ProgressStatus:
|
|
137
|
+
"""Interim progress update. Terminal status is in ReadResult, not here."""
|
|
138
|
+
|
|
139
|
+
output_row_count: int | None = None
|
|
140
|
+
error_row_count: int | None = None
|
|
141
|
+
status_message: str | None = None
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class ProgressReporter(ABC):
|
|
145
|
+
"""Reports interim progress to the pipeline.
|
|
146
|
+
|
|
147
|
+
Mirrors ConnectorCallback.update() for IN_PROGRESS updates only.
|
|
148
|
+
Terminal status (ENDED, FAILED, etc.) is owned by ReadResult.
|
|
149
|
+
"""
|
|
150
|
+
|
|
151
|
+
@abstractmethod
|
|
152
|
+
def report(self, status: ProgressStatus, *, force: bool = False) -> None:
|
|
153
|
+
"""Report interim progress."""
|
|
154
|
+
|
|
155
|
+
def record_row(self, row_count: int, error_count: int = 0) -> None:
|
|
156
|
+
"""Record one row-progress fact.
|
|
157
|
+
|
|
158
|
+
Runtime reporters may throttle this method before forwarding to the
|
|
159
|
+
transport. Connector hot loops should call this instead of applying
|
|
160
|
+
local modulus checks or constructing ProgressStatus directly.
|
|
161
|
+
"""
|
|
162
|
+
self.report(ProgressStatus(
|
|
163
|
+
output_row_count=row_count,
|
|
164
|
+
error_row_count=error_count,
|
|
165
|
+
))
|