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,583 @@
|
|
|
1
|
+
"""Type inference from sampled values.
|
|
2
|
+
|
|
3
|
+
Port of Java SDK TypeInferenceEngine and analyzers.
|
|
4
|
+
Shared module for SFTP, S3, and future file-based connectors.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import logging
|
|
10
|
+
import re
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from decimal import Decimal, InvalidOperation
|
|
13
|
+
from datetime import datetime
|
|
14
|
+
|
|
15
|
+
log = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
# ---------------------------------------------------------------------------
|
|
18
|
+
# Constants (match Java defaults)
|
|
19
|
+
# ---------------------------------------------------------------------------
|
|
20
|
+
|
|
21
|
+
SUCCESS_THRESHOLD = 0.95
|
|
22
|
+
SAMPLE_SIZE = 1000
|
|
23
|
+
MAX_CONSECUTIVE_FAILURES = 250
|
|
24
|
+
MIN_DISTINCT_VALUES_FOR_CONFIDENCE = 2
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
# ---------------------------------------------------------------------------
|
|
28
|
+
# FieldSample -- mirrors Java FieldSample
|
|
29
|
+
# ---------------------------------------------------------------------------
|
|
30
|
+
|
|
31
|
+
class FieldSample:
|
|
32
|
+
"""Collected sample values for a single field.
|
|
33
|
+
|
|
34
|
+
Empty/whitespace strings are normalized to null at add_value() time.
|
|
35
|
+
This matches the Java pipeline behavior where SchemaSampler.normalizeValue()
|
|
36
|
+
trims and converts empty strings to null before calling FieldSample.addValue().
|
|
37
|
+
In Java the normalization lives in SchemaSampler; in Python we fold it into
|
|
38
|
+
FieldSample directly since we have no separate SchemaSampler class.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __init__(self, field_name: str):
|
|
42
|
+
self.field_name = field_name
|
|
43
|
+
self._values: list[str] = []
|
|
44
|
+
self._distinct: set[str] = set()
|
|
45
|
+
self._null_count = 0
|
|
46
|
+
self._total_count = 0
|
|
47
|
+
|
|
48
|
+
def add_value(self, value) -> None:
|
|
49
|
+
self._total_count += 1
|
|
50
|
+
if value is None:
|
|
51
|
+
self._null_count += 1
|
|
52
|
+
return
|
|
53
|
+
s = str(value).strip()
|
|
54
|
+
if not s:
|
|
55
|
+
self._null_count += 1
|
|
56
|
+
return
|
|
57
|
+
self._values.append(s)
|
|
58
|
+
self._distinct.add(s)
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def values(self) -> list[str]:
|
|
62
|
+
return self._values
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def non_null_count(self) -> int:
|
|
66
|
+
return len(self._values)
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def null_count(self) -> int:
|
|
70
|
+
return self._null_count
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def total_count(self) -> int:
|
|
74
|
+
return self._total_count
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def distinct_count(self) -> int:
|
|
78
|
+
return len(self._distinct)
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def is_nullable(self) -> bool:
|
|
82
|
+
return self._null_count > 0
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def has_non_null_samples(self) -> bool:
|
|
86
|
+
return len(self._values) > 0
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def is_all_unique(self) -> bool:
|
|
90
|
+
"""Whether all non-null values are unique (potential primary key indicator).
|
|
91
|
+
Part of Java FieldSample contract; used by future PK detection logic."""
|
|
92
|
+
return self.has_non_null_samples and len(self._distinct) == len(self._values)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
# ---------------------------------------------------------------------------
|
|
96
|
+
# FieldInference -- result of inferring a single field
|
|
97
|
+
# ---------------------------------------------------------------------------
|
|
98
|
+
|
|
99
|
+
@dataclass
|
|
100
|
+
class FieldInference:
|
|
101
|
+
"""Result of type inference for a single field.
|
|
102
|
+
|
|
103
|
+
Keeps the raw inferred_type_label separate from the final canonical_type,
|
|
104
|
+
mirroring the Java SDK separation between TypeInferenceEngine (produces
|
|
105
|
+
labels like DECIMAL, INTEGER, TIMESTAMP) and CanonicalTypeMapper (maps
|
|
106
|
+
to LONG, BIGDECIMAL, INSTANT). Connectors can override the mapping via
|
|
107
|
+
map_to_canonical() without changing the inference engine.
|
|
108
|
+
"""
|
|
109
|
+
field_name: str
|
|
110
|
+
inferred_type_label: str # raw analyzer output: DECIMAL, INTEGER, TIMESTAMP, DATE, BOOLEAN, JSON, TEXT
|
|
111
|
+
canonical_type: str # final mapped type: LONG, BIGDECIMAL, INSTANT, LOCALDATE, etc.
|
|
112
|
+
original_data_type: str # formatted label e.g. "DECIMAL(12,2)", "INTEGER(19)"
|
|
113
|
+
precision: int | None = None
|
|
114
|
+
scale: int | None = None
|
|
115
|
+
nullable: bool = True
|
|
116
|
+
hints: dict = field(default_factory=dict)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def map_to_canonical(label: str, precision: int | None = None,
|
|
120
|
+
scale: int | None = None) -> str:
|
|
121
|
+
"""Map an inferred type label to a Supaflow canonical type.
|
|
122
|
+
|
|
123
|
+
Mirrors Java CanonicalTypeMapper.defaultMapper(). Connectors can
|
|
124
|
+
override this function to apply source-specific type semantics.
|
|
125
|
+
|
|
126
|
+
Mapping rules:
|
|
127
|
+
- INTEGER -> LONG
|
|
128
|
+
- DECIMAL with scale=0 (integer-like) -> LONG
|
|
129
|
+
- DECIMAL with precision<=38 and scale<=37 -> BIGDECIMAL
|
|
130
|
+
- DECIMAL otherwise -> DOUBLE
|
|
131
|
+
- TIMESTAMP -> INSTANT
|
|
132
|
+
- DATE -> LOCALDATE
|
|
133
|
+
- BOOLEAN -> BOOLEAN
|
|
134
|
+
- JSON -> JSON
|
|
135
|
+
- TEXT / anything else -> STRING
|
|
136
|
+
"""
|
|
137
|
+
upper = label.upper() if label else "TEXT"
|
|
138
|
+
if upper == "INTEGER":
|
|
139
|
+
return "LONG"
|
|
140
|
+
if upper == "DECIMAL":
|
|
141
|
+
if scale is not None and scale == 0:
|
|
142
|
+
return "LONG"
|
|
143
|
+
if (precision is not None and scale is not None
|
|
144
|
+
and precision <= 38 and scale <= 37):
|
|
145
|
+
return "BIGDECIMAL"
|
|
146
|
+
return "DOUBLE"
|
|
147
|
+
if upper == "TIMESTAMP":
|
|
148
|
+
return "INSTANT"
|
|
149
|
+
if upper == "DATE":
|
|
150
|
+
return "LOCALDATE"
|
|
151
|
+
if upper == "BOOLEAN":
|
|
152
|
+
return "BOOLEAN"
|
|
153
|
+
if upper == "JSON":
|
|
154
|
+
return "JSON"
|
|
155
|
+
return "STRING"
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
# ---------------------------------------------------------------------------
|
|
159
|
+
# Boolean constants
|
|
160
|
+
# ---------------------------------------------------------------------------
|
|
161
|
+
|
|
162
|
+
_TRUE_VALUES = frozenset({"true", "yes", "1", "t", "y", "on"})
|
|
163
|
+
_FALSE_VALUES = frozenset({"false", "no", "0", "f", "n", "off"})
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
# ---------------------------------------------------------------------------
|
|
167
|
+
# Date pattern detection
|
|
168
|
+
# ---------------------------------------------------------------------------
|
|
169
|
+
|
|
170
|
+
# Default date patterns matching Java DateTimeFieldAnalyzer.DEFAULT_DATE_PATTERNS.
|
|
171
|
+
# Each tuple: (regex_str, strptime_format_or_None, has_time).
|
|
172
|
+
# None format means use datetime.fromisoformat().
|
|
173
|
+
# Slash/dash variants with 1- and 2-digit day/month mirror the Java pattern set.
|
|
174
|
+
_DEFAULT_DATE_PATTERN_SPECS: list[tuple[str, str | None, bool]] = [
|
|
175
|
+
# ISO 8601 with timezone offset (+05:30, -08:00, Z)
|
|
176
|
+
(r'\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(\.\d+)?([+-]\d{2}:\d{2}|Z)',
|
|
177
|
+
None, True),
|
|
178
|
+
# ISO 8601 datetime without timezone
|
|
179
|
+
(r'\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(\.\d+)?$',
|
|
180
|
+
None, True),
|
|
181
|
+
# ISO 8601 date only
|
|
182
|
+
(r'\d{4}-\d{2}-\d{2}$', '%Y-%m-%d', False),
|
|
183
|
+
|
|
184
|
+
# US slash formats (MM/dd)
|
|
185
|
+
(r'\d{1,2}/\d{1,2}/\d{4} \d{2}:\d{2}:\d{2}$', '%m/%d/%Y %H:%M:%S', True),
|
|
186
|
+
(r'\d{1,2}/\d{1,2}/\d{2} \d{2}:\d{2}:\d{2}$', '%m/%d/%y %H:%M:%S', True),
|
|
187
|
+
(r'\d{1,2}/\d{1,2}/\d{4}$', '%m/%d/%Y', False),
|
|
188
|
+
(r'\d{1,2}/\d{1,2}/\d{2}$', '%m/%d/%y', False),
|
|
189
|
+
|
|
190
|
+
# US dash formats (MM-dd)
|
|
191
|
+
(r'\d{1,2}-\d{1,2}-\d{4} \d{2}:\d{2}:\d{2}$', '%m-%d-%Y %H:%M:%S', True),
|
|
192
|
+
(r'\d{1,2}-\d{1,2}-\d{2} \d{2}:\d{2}:\d{2}$', '%m-%d-%y %H:%M:%S', True),
|
|
193
|
+
(r'\d{1,2}-\d{1,2}-\d{4}$', '%m-%d-%Y', False),
|
|
194
|
+
(r'\d{1,2}-\d{1,2}-\d{2}$', '%m-%d-%y', False),
|
|
195
|
+
|
|
196
|
+
# EU slash formats (dd/MM) -- same regex as US, tried as fallback
|
|
197
|
+
(r'\d{1,2}/\d{1,2}/\d{4} \d{2}:\d{2}:\d{2}$', '%d/%m/%Y %H:%M:%S', True),
|
|
198
|
+
(r'\d{1,2}/\d{1,2}/\d{2} \d{2}:\d{2}:\d{2}$', '%d/%m/%y %H:%M:%S', True),
|
|
199
|
+
(r'\d{1,2}/\d{1,2}/\d{4}$', '%d/%m/%Y', False),
|
|
200
|
+
(r'\d{1,2}/\d{1,2}/\d{2}$', '%d/%m/%y', False),
|
|
201
|
+
|
|
202
|
+
# EU dash formats (dd-MM)
|
|
203
|
+
(r'\d{1,2}-\d{1,2}-\d{4} \d{2}:\d{2}:\d{2}$', '%d-%m-%Y %H:%M:%S', True),
|
|
204
|
+
(r'\d{1,2}-\d{1,2}-\d{2} \d{2}:\d{2}:\d{2}$', '%d-%m-%y %H:%M:%S', True),
|
|
205
|
+
(r'\d{1,2}-\d{1,2}-\d{4}$', '%d-%m-%Y', False),
|
|
206
|
+
(r'\d{1,2}-\d{1,2}-\d{2}$', '%d-%m-%y', False),
|
|
207
|
+
|
|
208
|
+
# yyyy/MM/dd
|
|
209
|
+
(r'\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}$', '%Y/%m/%d %H:%M:%S', True),
|
|
210
|
+
(r'\d{4}/\d{2}/\d{2}$', '%Y/%m/%d', False),
|
|
211
|
+
]
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _compile_date_patterns(
|
|
215
|
+
specs: list[tuple[str, str | None, bool]],
|
|
216
|
+
) -> list[tuple[re.Pattern, str | None, bool]]:
|
|
217
|
+
"""Compile pattern specs into (regex, fmt, has_time) tuples."""
|
|
218
|
+
compiled = []
|
|
219
|
+
for regex_str, fmt, has_time in specs:
|
|
220
|
+
compiled.append((re.compile(regex_str), fmt, has_time))
|
|
221
|
+
return compiled
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
# Module-level default patterns, compiled once.
|
|
225
|
+
_DEFAULT_DATE_PATTERNS = _compile_date_patterns(_DEFAULT_DATE_PATTERN_SPECS)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _compile_format_strings(
|
|
229
|
+
formats: list[str],
|
|
230
|
+
) -> list[tuple[re.Pattern, str | None, bool]]:
|
|
231
|
+
"""Convert plain strptime format strings into compiled pattern tuples.
|
|
232
|
+
|
|
233
|
+
Provides the same connector-extensible date format capability as the Java
|
|
234
|
+
SDK's SchemaSampleCapabilities.additionalDatePatterns, but using Python-native
|
|
235
|
+
strptime format strings (e.g., "%d.%m.%Y") instead of Java SimpleDateFormat
|
|
236
|
+
patterns (e.g., "dd/MM/yyyy"). Same feature, host-language-appropriate syntax.
|
|
237
|
+
|
|
238
|
+
The regex is derived from the format; has_time is derived from whether
|
|
239
|
+
the format contains H/h/m/s directives.
|
|
240
|
+
"""
|
|
241
|
+
# strptime directive -> regex fragment
|
|
242
|
+
_DIRECTIVE_RE = {
|
|
243
|
+
"%Y": r"\d{4}", "%y": r"\d{2}",
|
|
244
|
+
"%m": r"\d{1,2}", "%d": r"\d{1,2}",
|
|
245
|
+
"%H": r"\d{1,2}", "%I": r"\d{1,2}",
|
|
246
|
+
"%M": r"\d{1,2}", "%S": r"\d{1,2}",
|
|
247
|
+
"%f": r"\d+",
|
|
248
|
+
"%p": r"[APap][Mm]",
|
|
249
|
+
"%z": r"[+-]\d{2}:?\d{2}",
|
|
250
|
+
"%Z": r"[A-Z]+",
|
|
251
|
+
}
|
|
252
|
+
result = []
|
|
253
|
+
for fmt in formats:
|
|
254
|
+
has_time = any(d in fmt for d in ("%H", "%I", "%M", "%S", "%h"))
|
|
255
|
+
# Build regex by replacing directives with digit patterns
|
|
256
|
+
regex_str = fmt
|
|
257
|
+
for directive, pattern in _DIRECTIVE_RE.items():
|
|
258
|
+
regex_str = regex_str.replace(directive, pattern)
|
|
259
|
+
# Escape remaining literal characters that are regex-special
|
|
260
|
+
# (already handled by the replacement, but dots need escaping)
|
|
261
|
+
regex_str = regex_str.replace(".", r"\.")
|
|
262
|
+
regex_str = regex_str + "$"
|
|
263
|
+
try:
|
|
264
|
+
compiled = re.compile(regex_str)
|
|
265
|
+
result.append((compiled, fmt, has_time))
|
|
266
|
+
except re.error:
|
|
267
|
+
log.warning("Invalid date format pattern, skipping: %s", fmt)
|
|
268
|
+
return result
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _try_parse_datetime(
|
|
272
|
+
value: str,
|
|
273
|
+
patterns: list[tuple[re.Pattern, str | None, bool]] | None = None,
|
|
274
|
+
) -> bool | None:
|
|
275
|
+
"""Try to parse a value as a date/datetime.
|
|
276
|
+
|
|
277
|
+
Returns True if the value contains a time component, False if date-only,
|
|
278
|
+
or None if the value does not match any known date/datetime pattern.
|
|
279
|
+
"""
|
|
280
|
+
if len(value) < 6 or len(value) > 35:
|
|
281
|
+
return None
|
|
282
|
+
for regex, fmt, has_time in (patterns or _DEFAULT_DATE_PATTERNS):
|
|
283
|
+
if regex.fullmatch(value):
|
|
284
|
+
try:
|
|
285
|
+
if fmt is None:
|
|
286
|
+
datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
287
|
+
else:
|
|
288
|
+
datetime.strptime(value, fmt)
|
|
289
|
+
return has_time
|
|
290
|
+
except ValueError:
|
|
291
|
+
continue
|
|
292
|
+
return None
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
# ---------------------------------------------------------------------------
|
|
296
|
+
# Numeric parsing helpers
|
|
297
|
+
# ---------------------------------------------------------------------------
|
|
298
|
+
|
|
299
|
+
# Regex for values with grouping separators: 1,234 or 1,234.56 or -1,234,567.89
|
|
300
|
+
_GROUPED_NUMBER_RE = re.compile(
|
|
301
|
+
r'^[+-]?\d{1,3}(?:,\d{3})+(?:\.\d+)?$'
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _parse_numeric_value(v: str) -> Decimal:
|
|
306
|
+
"""Parse a string as a Decimal, handling grouping separators.
|
|
307
|
+
|
|
308
|
+
Tries plain Decimal() first. Falls back to stripping commas for values
|
|
309
|
+
like '1,234.56'. Mirrors the first two strategies of Java's
|
|
310
|
+
NumericFieldAnalyzer (plain number, then locale-aware parsing).
|
|
311
|
+
Currency symbols and percent syntax are not handled -- those require
|
|
312
|
+
locale context that Python connectors don't have yet.
|
|
313
|
+
"""
|
|
314
|
+
try:
|
|
315
|
+
return Decimal(v)
|
|
316
|
+
except (InvalidOperation, ValueError):
|
|
317
|
+
pass
|
|
318
|
+
# Try stripping grouping separators (e.g., '1,234.56' -> '1234.56')
|
|
319
|
+
if _GROUPED_NUMBER_RE.match(v):
|
|
320
|
+
return Decimal(v.replace(",", ""))
|
|
321
|
+
raise InvalidOperation(f"Not a number: {v}")
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
# ---------------------------------------------------------------------------
|
|
325
|
+
# TypeInferenceEngine
|
|
326
|
+
# ---------------------------------------------------------------------------
|
|
327
|
+
|
|
328
|
+
@dataclass
|
|
329
|
+
class _NumericEnvelope:
|
|
330
|
+
"""Shared numeric sample envelope; independent of parsing and type policy."""
|
|
331
|
+
|
|
332
|
+
integer_digits: int = 0
|
|
333
|
+
scale: int = 0
|
|
334
|
+
|
|
335
|
+
def observe(self, value: Decimal) -> None:
|
|
336
|
+
if not value.is_finite():
|
|
337
|
+
raise ValueError("Numeric envelope requires a finite value")
|
|
338
|
+
_, digits, exponent = value.as_tuple()
|
|
339
|
+
self.integer_digits = max(self.integer_digits, len(digits) + exponent)
|
|
340
|
+
self.scale = max(self.scale, -exponent)
|
|
341
|
+
|
|
342
|
+
@property
|
|
343
|
+
def precision(self) -> int:
|
|
344
|
+
# Reserve enough room for both extremes, even on different rows.
|
|
345
|
+
# Retain the shared inference policy of widening decimals to at least 38.
|
|
346
|
+
return max(38, self.integer_digits + self.scale)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
class TypeInferenceEngine:
|
|
350
|
+
"""Runs analyzers in priority order to infer field types.
|
|
351
|
+
|
|
352
|
+
Analyzer order (matching Java): JSON -> Boolean -> Numeric -> DateTime.
|
|
353
|
+
Falls back to STRING when no analyzer matches or diversity is too low.
|
|
354
|
+
"""
|
|
355
|
+
|
|
356
|
+
def __init__(
|
|
357
|
+
self,
|
|
358
|
+
success_threshold: float = SUCCESS_THRESHOLD,
|
|
359
|
+
sample_size: int = SAMPLE_SIZE,
|
|
360
|
+
additional_date_formats: list[str] | None = None,
|
|
361
|
+
):
|
|
362
|
+
if success_threshold <= 0.0 or success_threshold > 1.0:
|
|
363
|
+
raise ValueError("success_threshold must be in (0.0, 1.0]")
|
|
364
|
+
if sample_size <= 0:
|
|
365
|
+
raise ValueError("sample_size must be positive")
|
|
366
|
+
self._threshold = success_threshold
|
|
367
|
+
self._sample_size = sample_size
|
|
368
|
+
# Connector-specific formats are plain strptime strings (e.g., "%d.%m.%Y").
|
|
369
|
+
# Same capability as Java SDK's SchemaSampleCapabilities.additionalDatePatterns,
|
|
370
|
+
# but using Python-native strptime syntax instead of SimpleDateFormat.
|
|
371
|
+
# Prepended to defaults so connector patterns take priority.
|
|
372
|
+
if additional_date_formats:
|
|
373
|
+
extra = _compile_format_strings(additional_date_formats)
|
|
374
|
+
self._date_patterns = extra + _DEFAULT_DATE_PATTERNS
|
|
375
|
+
else:
|
|
376
|
+
self._date_patterns = _DEFAULT_DATE_PATTERNS
|
|
377
|
+
|
|
378
|
+
def infer_field_type(self, sample: FieldSample) -> FieldInference:
|
|
379
|
+
"""Infer type for a single field from its samples."""
|
|
380
|
+
values = self._sample_values(sample)
|
|
381
|
+
if not values:
|
|
382
|
+
return FieldInference(
|
|
383
|
+
field_name=sample.field_name,
|
|
384
|
+
inferred_type_label="TEXT",
|
|
385
|
+
canonical_type=map_to_canonical("TEXT"),
|
|
386
|
+
original_data_type="TEXT",
|
|
387
|
+
nullable=True,
|
|
388
|
+
)
|
|
389
|
+
|
|
390
|
+
if len(set(values)) < MIN_DISTINCT_VALUES_FOR_CONFIDENCE:
|
|
391
|
+
return self._text_fallback(sample, reason="low_diversity")
|
|
392
|
+
|
|
393
|
+
# Priority order: JSON -> Boolean -> Numeric -> DateTime -> Text
|
|
394
|
+
for analyzer in [
|
|
395
|
+
self._analyze_json,
|
|
396
|
+
self._analyze_boolean,
|
|
397
|
+
self._analyze_numeric,
|
|
398
|
+
self._analyze_datetime,
|
|
399
|
+
]:
|
|
400
|
+
result = analyzer(sample)
|
|
401
|
+
if result is not None:
|
|
402
|
+
return result
|
|
403
|
+
|
|
404
|
+
return self._text_fallback(sample)
|
|
405
|
+
|
|
406
|
+
def infer_types(
|
|
407
|
+
self, samples: dict[str, FieldSample]
|
|
408
|
+
) -> dict[str, FieldInference]:
|
|
409
|
+
"""Infer types for all field samples."""
|
|
410
|
+
return {
|
|
411
|
+
name: self.infer_field_type(sample)
|
|
412
|
+
for name, sample in samples.items()
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
def _sample_values(self, sample: FieldSample) -> list[str]:
|
|
416
|
+
return sample.values[:self._sample_size]
|
|
417
|
+
|
|
418
|
+
# -- Analyzers (filled in by subsequent tasks) --
|
|
419
|
+
|
|
420
|
+
def _analyze_json(self, sample: FieldSample) -> FieldInference | None:
|
|
421
|
+
values = self._sample_values(sample)
|
|
422
|
+
matches = 0
|
|
423
|
+
for v in values:
|
|
424
|
+
if (v.startswith("{") and v.endswith("}")) or \
|
|
425
|
+
(v.startswith("[") and v.endswith("]")):
|
|
426
|
+
try:
|
|
427
|
+
json.loads(v)
|
|
428
|
+
matches += 1
|
|
429
|
+
except (json.JSONDecodeError, ValueError):
|
|
430
|
+
pass
|
|
431
|
+
if not values or matches / len(values) < self._threshold:
|
|
432
|
+
return None
|
|
433
|
+
return FieldInference(
|
|
434
|
+
field_name=sample.field_name,
|
|
435
|
+
inferred_type_label="JSON",
|
|
436
|
+
canonical_type=map_to_canonical("JSON"),
|
|
437
|
+
original_data_type="JSON",
|
|
438
|
+
nullable=sample.is_nullable,
|
|
439
|
+
)
|
|
440
|
+
|
|
441
|
+
def _analyze_boolean(self, sample: FieldSample) -> FieldInference | None:
|
|
442
|
+
values = self._sample_values(sample)
|
|
443
|
+
if not values:
|
|
444
|
+
return None
|
|
445
|
+
|
|
446
|
+
# Check distinct count on lowercased values (case-insensitive).
|
|
447
|
+
# FieldSample._distinct is case-sensitive, but boolean detection
|
|
448
|
+
# must treat "Yes"/"yes"/"YES" as the same truthy value.
|
|
449
|
+
lower_distinct = {v.lower() for v in values}
|
|
450
|
+
if len(lower_distinct) > 2:
|
|
451
|
+
return None
|
|
452
|
+
if len(lower_distinct) < 2:
|
|
453
|
+
return None # Defensive: engine already gates on distinct >= 2
|
|
454
|
+
|
|
455
|
+
seen_true = False
|
|
456
|
+
seen_false = False
|
|
457
|
+
matches = 0
|
|
458
|
+
for v in values:
|
|
459
|
+
lower = v.lower()
|
|
460
|
+
if lower in _TRUE_VALUES:
|
|
461
|
+
seen_true = True
|
|
462
|
+
matches += 1
|
|
463
|
+
elif lower in _FALSE_VALUES:
|
|
464
|
+
seen_false = True
|
|
465
|
+
matches += 1
|
|
466
|
+
|
|
467
|
+
if not (seen_true and seen_false):
|
|
468
|
+
return None
|
|
469
|
+
if matches / len(values) < self._threshold:
|
|
470
|
+
return None
|
|
471
|
+
|
|
472
|
+
return FieldInference(
|
|
473
|
+
field_name=sample.field_name,
|
|
474
|
+
inferred_type_label="BOOLEAN",
|
|
475
|
+
canonical_type=map_to_canonical("BOOLEAN"),
|
|
476
|
+
original_data_type="BOOLEAN",
|
|
477
|
+
nullable=sample.is_nullable,
|
|
478
|
+
)
|
|
479
|
+
|
|
480
|
+
def _analyze_numeric(self, sample: FieldSample) -> FieldInference | None:
|
|
481
|
+
values = self._sample_values(sample)
|
|
482
|
+
if not values:
|
|
483
|
+
return None
|
|
484
|
+
|
|
485
|
+
envelope = _NumericEnvelope()
|
|
486
|
+
success_count = 0
|
|
487
|
+
consecutive_failures = 0
|
|
488
|
+
|
|
489
|
+
for v in values:
|
|
490
|
+
try:
|
|
491
|
+
d = _parse_numeric_value(v)
|
|
492
|
+
if d.is_nan() or d.is_infinite():
|
|
493
|
+
consecutive_failures += 1
|
|
494
|
+
if consecutive_failures >= MAX_CONSECUTIVE_FAILURES:
|
|
495
|
+
return None
|
|
496
|
+
continue
|
|
497
|
+
|
|
498
|
+
envelope.observe(d)
|
|
499
|
+
|
|
500
|
+
success_count += 1
|
|
501
|
+
consecutive_failures = 0
|
|
502
|
+
except (InvalidOperation, ValueError, OverflowError):
|
|
503
|
+
consecutive_failures += 1
|
|
504
|
+
if consecutive_failures >= MAX_CONSECUTIVE_FAILURES:
|
|
505
|
+
return None
|
|
506
|
+
|
|
507
|
+
if not values or success_count / len(values) < self._threshold:
|
|
508
|
+
return None
|
|
509
|
+
|
|
510
|
+
if envelope.scale == 0:
|
|
511
|
+
label = "INTEGER"
|
|
512
|
+
# Integer canonical types (SHORT/INT/LONG) must not carry precision/scale.
|
|
513
|
+
# Only BIGDECIMAL (mapped from DECIMAL label) carries a numeric envelope.
|
|
514
|
+
# See docs/RCA_snowflake_number_precision_narrowing_alter.md.
|
|
515
|
+
odt = "INTEGER"
|
|
516
|
+
p, s = None, None
|
|
517
|
+
else:
|
|
518
|
+
label = "DECIMAL"
|
|
519
|
+
# For inferred decimals within BIGDECIMAL range (precision <= 38),
|
|
520
|
+
# widen precision to max (38) to avoid overflow. Sample-derived
|
|
521
|
+
# precision is too tight -- real data often has values outside the
|
|
522
|
+
# sample range. Keep inferred scale (decimal places are structurally
|
|
523
|
+
# stable). For huge precision (> 38), preserve it so the mapper
|
|
524
|
+
# correctly routes to DOUBLE.
|
|
525
|
+
p = envelope.precision
|
|
526
|
+
s = envelope.scale
|
|
527
|
+
odt = f"DECIMAL({p},{s})"
|
|
528
|
+
|
|
529
|
+
return FieldInference(
|
|
530
|
+
field_name=sample.field_name,
|
|
531
|
+
inferred_type_label=label,
|
|
532
|
+
canonical_type=map_to_canonical(label, p, s),
|
|
533
|
+
original_data_type=odt,
|
|
534
|
+
precision=p,
|
|
535
|
+
scale=s,
|
|
536
|
+
nullable=sample.is_nullable,
|
|
537
|
+
)
|
|
538
|
+
|
|
539
|
+
def _analyze_datetime(self, sample: FieldSample) -> FieldInference | None:
|
|
540
|
+
values = self._sample_values(sample)
|
|
541
|
+
if not values:
|
|
542
|
+
return None
|
|
543
|
+
|
|
544
|
+
timestamps = 0
|
|
545
|
+
dates = 0
|
|
546
|
+
total_checked = 0
|
|
547
|
+
|
|
548
|
+
for v in values:
|
|
549
|
+
has_time = _try_parse_datetime(v, self._date_patterns)
|
|
550
|
+
if has_time is not None:
|
|
551
|
+
if has_time:
|
|
552
|
+
timestamps += 1
|
|
553
|
+
else:
|
|
554
|
+
dates += 1
|
|
555
|
+
total_checked += 1
|
|
556
|
+
|
|
557
|
+
total_matches = timestamps + dates
|
|
558
|
+
if total_checked == 0 or total_matches / total_checked < self._threshold:
|
|
559
|
+
return None
|
|
560
|
+
|
|
561
|
+
label = "TIMESTAMP" if timestamps > 0 else "DATE"
|
|
562
|
+
return FieldInference(
|
|
563
|
+
field_name=sample.field_name,
|
|
564
|
+
inferred_type_label=label,
|
|
565
|
+
canonical_type=map_to_canonical(label),
|
|
566
|
+
original_data_type=label,
|
|
567
|
+
nullable=sample.is_nullable,
|
|
568
|
+
)
|
|
569
|
+
|
|
570
|
+
def _text_fallback(
|
|
571
|
+
self, sample: FieldSample, reason: str | None = None
|
|
572
|
+
) -> FieldInference:
|
|
573
|
+
max_len = max((len(v) for v in self._sample_values(sample)), default=0)
|
|
574
|
+
precision = max_len if max_len > 0 else 255
|
|
575
|
+
return FieldInference(
|
|
576
|
+
field_name=sample.field_name,
|
|
577
|
+
inferred_type_label="TEXT",
|
|
578
|
+
canonical_type=map_to_canonical("TEXT"),
|
|
579
|
+
original_data_type=f"TEXT({precision})",
|
|
580
|
+
precision=precision,
|
|
581
|
+
nullable=sample.is_nullable,
|
|
582
|
+
hints={"fallback_reason": reason} if reason else {},
|
|
583
|
+
)
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Immutable display metadata mirroring Java metadata.UiNotice and UiMedia.
|
|
2
|
+
|
|
3
|
+
These values contain no provider behavior, executable content, or asset bytes.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class UiMedia:
|
|
13
|
+
"""Image/animation URL and accessible description.
|
|
14
|
+
|
|
15
|
+
Use credential-free HTTPS or a same-origin absolute path with one leading
|
|
16
|
+
slash. Consumers validate URLs; written guidance must survive media failure.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
url: str
|
|
20
|
+
alt: str
|
|
21
|
+
|
|
22
|
+
def as_dict(self) -> dict[str, str]:
|
|
23
|
+
return {"url": self.url, "alt": self.alt}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class UiNotice:
|
|
28
|
+
"""Plain-text guidance; the consumer owns presentation and actions.
|
|
29
|
+
|
|
30
|
+
Title and body must be nonblank. Optional fields are omitted from the wire
|
|
31
|
+
representation. Continue labels change wording, not the action performed.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
title: str
|
|
35
|
+
body: str
|
|
36
|
+
continue_label: str | None = None
|
|
37
|
+
media: UiMedia | None = None
|
|
38
|
+
|
|
39
|
+
def as_dict(self) -> dict[str, Any]:
|
|
40
|
+
result: dict[str, Any] = {"title": self.title, "body": self.body}
|
|
41
|
+
if self.continue_label is not None:
|
|
42
|
+
result["continueLabel"] = self.continue_label
|
|
43
|
+
if self.media is not None:
|
|
44
|
+
result["media"] = self.media.as_dict()
|
|
45
|
+
return result
|