qa-core-recon 0.1.0__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.
- qa_core_recon/__init__.py +3 -0
- qa_core_recon/__main__.py +6 -0
- qa_core_recon/alignment.py +494 -0
- qa_core_recon/checks.py +869 -0
- qa_core_recon/cli.py +318 -0
- qa_core_recon/compare.py +239 -0
- qa_core_recon/decimals.py +153 -0
- qa_core_recon/exit_codes.py +9 -0
- qa_core_recon/hashing.py +187 -0
- qa_core_recon/readers.py +643 -0
- qa_core_recon/refusals.py +28 -0
- qa_core_recon/report.py +594 -0
- qa_core_recon/spark.py +484 -0
- qa_core_recon/spec.py +668 -0
- qa_core_recon/templates/recon.yaml +43 -0
- qa_core_recon-0.1.0.dist-info/METADATA +539 -0
- qa_core_recon-0.1.0.dist-info/RECORD +20 -0
- qa_core_recon-0.1.0.dist-info/WHEEL +4 -0
- qa_core_recon-0.1.0.dist-info/entry_points.txt +2 -0
- qa_core_recon-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,494 @@
|
|
|
1
|
+
"""Align source and target columns before the key diff joins or hashes them.
|
|
2
|
+
|
|
3
|
+
Spark's own join casts a string key ``01`` to the long ``1``. That is a false
|
|
4
|
+
match. This module gives every key a string join key, and every compared
|
|
5
|
+
column a canonical token, using the rules below. Schemas are read on the
|
|
6
|
+
driver. Values stay in Spark.
|
|
7
|
+
|
|
8
|
+
* Integer and decimal columns compare by numeric value. Both tokens use the
|
|
9
|
+
decimal payload, so ``1`` and ``1.00`` match.
|
|
10
|
+
* A string paired with a typed column is parsed with ``try_cast``. A non-null
|
|
11
|
+
string that does not parse becomes an ``invalid:`` token, not null, so the
|
|
12
|
+
row is changed. Decimal strings that would have to be rounded do not parse.
|
|
13
|
+
Date strings must already be ``YYYY-MM-DD``.
|
|
14
|
+
* Key columns use a lossless parse. The raw string, with no trim, must equal
|
|
15
|
+
one canonical rendering of the typed value. An integer renders as its
|
|
16
|
+
digits (``1``, not ``01`` or `` 1``). A decimal renders at the column
|
|
17
|
+
scale with :func:`qa_core_recon.hashing.plain_decimal_text` (``1.00`` for
|
|
18
|
+
``decimal(10,2)``, ``0.0000000000`` for scale 10), never an exponent.
|
|
19
|
+
A boolean key is exactly ``true`` or ``false``. A timestamp key is the
|
|
20
|
+
UTC text used by the row hash. A timestamp without a time zone uses that
|
|
21
|
+
text without the trailing ``Z``. A float or double key is not aligned
|
|
22
|
+
with a string. Anything else stays unmatched.
|
|
23
|
+
* Compared columns keep a tolerant parse: surrounding spaces and equivalent
|
|
24
|
+
spellings may match, and a non-null string that does not parse is changed.
|
|
25
|
+
* Any other pair, including float against double, is not given a new refusal
|
|
26
|
+
code. The column is listed in ``type_mismatches`` and both sides are hashed
|
|
27
|
+
as their string rendering.
|
|
28
|
+
* ``TimestampType`` is formatted with ``date_format`` under the UTC session
|
|
29
|
+
before any Python code sees it. ``TimestampNTZType`` uses the same pattern
|
|
30
|
+
on the stored wall time and is not shifted into the session zone.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
from dataclasses import dataclass
|
|
34
|
+
from decimal import Decimal
|
|
35
|
+
|
|
36
|
+
from pyspark.sql.column import Column
|
|
37
|
+
from pyspark.sql.functions import (
|
|
38
|
+
col,
|
|
39
|
+
concat,
|
|
40
|
+
date_format,
|
|
41
|
+
encode,
|
|
42
|
+
expr,
|
|
43
|
+
length,
|
|
44
|
+
lit,
|
|
45
|
+
trim,
|
|
46
|
+
udf,
|
|
47
|
+
when,
|
|
48
|
+
)
|
|
49
|
+
from pyspark.sql.types import (
|
|
50
|
+
BinaryType,
|
|
51
|
+
BooleanType,
|
|
52
|
+
ByteType,
|
|
53
|
+
DataType,
|
|
54
|
+
DateType,
|
|
55
|
+
DecimalType,
|
|
56
|
+
DoubleType,
|
|
57
|
+
FloatType,
|
|
58
|
+
IntegerType,
|
|
59
|
+
LongType,
|
|
60
|
+
NullType,
|
|
61
|
+
ShortType,
|
|
62
|
+
StringType,
|
|
63
|
+
TimestampNTZType,
|
|
64
|
+
TimestampType,
|
|
65
|
+
)
|
|
66
|
+
from pyspark.sql.types import StringType as _StringType
|
|
67
|
+
|
|
68
|
+
from qa_core_recon.decimals import _AMOUNT_TEXT
|
|
69
|
+
from qa_core_recon.hashing import encode_value, plain_decimal_text, strict_decimal_payload
|
|
70
|
+
|
|
71
|
+
_INTEGER_TYPES = (ByteType, ShortType, IntegerType, LongType)
|
|
72
|
+
_TIMESTAMP_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'"
|
|
73
|
+
# TimestampNTZ has no zone, so the key text omits the trailing Z.
|
|
74
|
+
_TIMESTAMP_NTZ_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
|
|
75
|
+
# Fixed width of the zoned pattern. Every character is ASCII.
|
|
76
|
+
_TIMESTAMP_WIDTH = 27
|
|
77
|
+
|
|
78
|
+
_ENCODE = udf(encode_value, _StringType())
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _strict_decimal_udf(text, precision, scale):
|
|
82
|
+
if text is None or precision is None or scale is None:
|
|
83
|
+
return None
|
|
84
|
+
return strict_decimal_payload(str(text), int(precision), int(scale))
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _amount_text_ok(text) -> bool:
|
|
88
|
+
if text is None:
|
|
89
|
+
return False
|
|
90
|
+
return _AMOUNT_TEXT.fullmatch(str(text)) is not None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _plain_decimal_udf(value, scale):
|
|
94
|
+
if value is None or scale is None:
|
|
95
|
+
return None
|
|
96
|
+
number = value if isinstance(value, Decimal) else Decimal(str(value))
|
|
97
|
+
return plain_decimal_text(number, int(scale))
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
_DECIMAL_PAYLOAD = udf(_strict_decimal_udf, _StringType())
|
|
101
|
+
_PLAIN_DECIMAL = udf(_plain_decimal_udf, _StringType())
|
|
102
|
+
_ASCII_AMOUNT = udf(_amount_text_ok, BooleanType())
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@dataclass(frozen=True)
|
|
106
|
+
class FieldPlan:
|
|
107
|
+
"""How one named field is aligned. Built from schemas only."""
|
|
108
|
+
|
|
109
|
+
name: str
|
|
110
|
+
role: str
|
|
111
|
+
kind: str
|
|
112
|
+
source_type: DataType
|
|
113
|
+
target_type: DataType
|
|
114
|
+
string_side: str | None = None
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def mismatch(self) -> dict | None:
|
|
118
|
+
if self.kind != "render":
|
|
119
|
+
return None
|
|
120
|
+
return {
|
|
121
|
+
"column": self.name,
|
|
122
|
+
"role": self.role,
|
|
123
|
+
"source_type": self.source_type.simpleString(),
|
|
124
|
+
"target_type": self.target_type.simpleString(),
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def plan_fields(
|
|
129
|
+
source_fields: dict[str, DataType], target_fields: dict[str, DataType], names, role: str
|
|
130
|
+
):
|
|
131
|
+
"""Return one plan per name, in the given order."""
|
|
132
|
+
plans = []
|
|
133
|
+
for name in names:
|
|
134
|
+
plans.append(_plan(name, role, source_fields[name], target_fields[name]))
|
|
135
|
+
return tuple(plans)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def type_mismatches(plans: tuple[FieldPlan, ...]) -> list[dict]:
|
|
139
|
+
"""Return the unalignable columns, sorted by role then name."""
|
|
140
|
+
found = [plan.mismatch for plan in plans if plan.mismatch is not None]
|
|
141
|
+
found.sort(key=lambda item: (item["role"], item["column"]))
|
|
142
|
+
return found
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def join_key(plan: FieldPlan, side: str) -> Column:
|
|
146
|
+
"""Return the string used to group and join this key. Null stays null."""
|
|
147
|
+
dtype = _dtype(plan, side)
|
|
148
|
+
column = _column(plan.name)
|
|
149
|
+
if plan.kind == "parse" and plan.string_side == side:
|
|
150
|
+
return _parsed_string(plan.name, _other_type(plan, side), lossless=True, for_join=True)
|
|
151
|
+
if plan.kind == "render":
|
|
152
|
+
return _rendered_token(column)
|
|
153
|
+
if plan.kind == "numeric":
|
|
154
|
+
return _numeric_token(column, dtype)
|
|
155
|
+
return _direct_token(column, dtype)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def value_token(plan: FieldPlan, side: str) -> Column:
|
|
159
|
+
"""Return the canonical token hashed for this compared column."""
|
|
160
|
+
dtype = _dtype(plan, side)
|
|
161
|
+
column = _column(plan.name)
|
|
162
|
+
if plan.kind == "parse" and plan.string_side == side:
|
|
163
|
+
return _parsed_string(plan.name, _other_type(plan, side), lossless=False, for_join=False)
|
|
164
|
+
if plan.kind == "render":
|
|
165
|
+
return _rendered_token(column)
|
|
166
|
+
if plan.kind == "numeric":
|
|
167
|
+
return _numeric_token(column, dtype)
|
|
168
|
+
return _direct_token(column, dtype)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def example_key(plan: FieldPlan, side: str) -> Column:
|
|
172
|
+
"""Return the key text stored in an example.
|
|
173
|
+
|
|
174
|
+
``TimestampType`` is formatted in Spark under the UTC session, so the
|
|
175
|
+
driver never turns it into a naive local datetime. ``TimestampNTZType``
|
|
176
|
+
keeps the stored wall time and the microseconds, with no trailing ``Z``.
|
|
177
|
+
"""
|
|
178
|
+
return format_example_value(_column(plan.name), _dtype(plan, side))
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def group_value(plan: FieldPlan, side: str) -> tuple[Column, Column | None]:
|
|
182
|
+
"""Return the group column for one side, and a parse flag or None.
|
|
183
|
+
|
|
184
|
+
A ``group_by`` column that is a string on this side and a parsable type on
|
|
185
|
+
the other side is parsed into the other side's type, with the same rules
|
|
186
|
+
as a compared column: surrounding spaces are allowed and a decimal must be
|
|
187
|
+
exact at the other side's scale. The flag is true when the parse succeeded.
|
|
188
|
+
When it is false the caller keeps the raw string, so a value that does not
|
|
189
|
+
parse stays its own group and the row count reports it. Every other column
|
|
190
|
+
is returned as it is, with timestamps formatted under the UTC session.
|
|
191
|
+
"""
|
|
192
|
+
if plan.kind == "parse" and plan.string_side == side:
|
|
193
|
+
typed = _other_type(plan, side)
|
|
194
|
+
column = _column(plan.name)
|
|
195
|
+
if isinstance(typed, DecimalType):
|
|
196
|
+
payload = _DECIMAL_PAYLOAD(trim(column), lit(typed.precision), lit(typed.scale))
|
|
197
|
+
parsed = when(payload.isNotNull(), payload).cast(
|
|
198
|
+
DecimalType(typed.precision, typed.scale)
|
|
199
|
+
)
|
|
200
|
+
ok = column.isNotNull() & payload.isNotNull()
|
|
201
|
+
else:
|
|
202
|
+
parsed, ok = _parse(plan.name, typed, lossless=False)
|
|
203
|
+
ok = column.isNotNull() & ok
|
|
204
|
+
return format_example_value(parsed, typed), ok
|
|
205
|
+
return format_example_value(_column(plan.name), _dtype(plan, side)), None
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def format_example_value(column: Column, dtype: DataType) -> Column:
|
|
209
|
+
"""Format a timestamp for an example. Other types stay as they are."""
|
|
210
|
+
if isinstance(dtype, TimestampNTZType):
|
|
211
|
+
return date_format(column, _TIMESTAMP_NTZ_PATTERN)
|
|
212
|
+
if isinstance(dtype, TimestampType):
|
|
213
|
+
return date_format(column, _TIMESTAMP_PATTERN)
|
|
214
|
+
return column
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def value_display(plan: FieldPlan, side: str) -> Column:
|
|
218
|
+
"""Return the value shown in an example.
|
|
219
|
+
|
|
220
|
+
Timestamps are the UTC text, so the driver never converts them in the
|
|
221
|
+
machine time zone. ``TimestampNTZType`` keeps the stored wall time and
|
|
222
|
+
does not gain a trailing ``Z``. Other direct values keep their Spark type
|
|
223
|
+
for :func:`qa_core_recon.compare.render_value`.
|
|
224
|
+
"""
|
|
225
|
+
dtype = _dtype(plan, side)
|
|
226
|
+
column = _column(plan.name)
|
|
227
|
+
if isinstance(dtype, TimestampNTZType):
|
|
228
|
+
return date_format(column, _TIMESTAMP_NTZ_PATTERN)
|
|
229
|
+
if isinstance(dtype, TimestampType):
|
|
230
|
+
return date_format(column, _TIMESTAMP_PATTERN)
|
|
231
|
+
if plan.kind == "render":
|
|
232
|
+
return when(column.isNull(), lit(None).cast("string")).otherwise(column.cast("string"))
|
|
233
|
+
if plan.kind == "parse" and plan.string_side == side:
|
|
234
|
+
return _parsed_display(plan.name, _other_type(plan, side))
|
|
235
|
+
return column
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _plan(name: str, role: str, source: DataType, target: DataType) -> FieldPlan:
|
|
239
|
+
# A float key has no single canonical spelling, so a string is not parsed.
|
|
240
|
+
if role == "key" and _string_vs_float(source, target):
|
|
241
|
+
kind, string_side = "render", None
|
|
242
|
+
else:
|
|
243
|
+
kind, string_side = _kind(source, target)
|
|
244
|
+
return FieldPlan(
|
|
245
|
+
name=name,
|
|
246
|
+
role=role,
|
|
247
|
+
kind=kind,
|
|
248
|
+
source_type=source,
|
|
249
|
+
target_type=target,
|
|
250
|
+
string_side=string_side,
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _kind(source: DataType, target: DataType) -> tuple[str, str | None]:
|
|
255
|
+
if isinstance(source, NullType) or isinstance(target, NullType):
|
|
256
|
+
return "direct", None
|
|
257
|
+
if _same_family(source, target):
|
|
258
|
+
return "direct", None
|
|
259
|
+
if _is_int(source) and isinstance(target, DecimalType):
|
|
260
|
+
return "numeric", None
|
|
261
|
+
if _is_int(target) and isinstance(source, DecimalType):
|
|
262
|
+
return "numeric", None
|
|
263
|
+
if isinstance(source, StringType) and _parsable(target):
|
|
264
|
+
return "parse", "source"
|
|
265
|
+
if isinstance(target, StringType) and _parsable(source):
|
|
266
|
+
return "parse", "target"
|
|
267
|
+
return "render", None
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _string_vs_float(source: DataType, target: DataType) -> bool:
|
|
271
|
+
pair = (source, target)
|
|
272
|
+
return any(isinstance(item, StringType) for item in pair) and any(
|
|
273
|
+
isinstance(item, (FloatType, DoubleType)) for item in pair
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _same_family(source: DataType, target: DataType) -> bool:
|
|
278
|
+
if isinstance(source, DecimalType) and isinstance(target, DecimalType):
|
|
279
|
+
return True
|
|
280
|
+
if _is_int(source) and _is_int(target):
|
|
281
|
+
return True
|
|
282
|
+
return type(source) is type(target)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _parsable(dtype: DataType) -> bool:
|
|
286
|
+
return _is_int(dtype) or isinstance(
|
|
287
|
+
dtype,
|
|
288
|
+
(
|
|
289
|
+
DecimalType,
|
|
290
|
+
DateType,
|
|
291
|
+
TimestampType,
|
|
292
|
+
TimestampNTZType,
|
|
293
|
+
BooleanType,
|
|
294
|
+
FloatType,
|
|
295
|
+
DoubleType,
|
|
296
|
+
),
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _direct_token(column: Column, dtype: DataType) -> Column:
|
|
301
|
+
if isinstance(dtype, TimestampNTZType):
|
|
302
|
+
# Stored wall time. date_format does not apply the session zone.
|
|
303
|
+
return _timestamp_token(column)
|
|
304
|
+
if isinstance(dtype, TimestampType):
|
|
305
|
+
# Session zone is UTC, so this text is the instant.
|
|
306
|
+
return _timestamp_token(column)
|
|
307
|
+
return _cell_token(column)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _timestamp_token(column: Column) -> Column:
|
|
311
|
+
payload = date_format(column, _TIMESTAMP_PATTERN)
|
|
312
|
+
return when(column.isNull(), lit("n")).otherwise(
|
|
313
|
+
concat(lit(f"timestamp:{_TIMESTAMP_WIDTH}:"), payload)
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _numeric_token(column: Column, dtype: DataType) -> Column:
|
|
318
|
+
if _is_int(dtype):
|
|
319
|
+
return _cell_token(column.cast(DecimalType(38, 0)))
|
|
320
|
+
return _cell_token(column)
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _rendered_token(column: Column) -> Column:
|
|
324
|
+
return _cell_token(column.cast("string"))
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _cell_token(column: Column) -> Column:
|
|
328
|
+
"""Encode one non-timestamp value with the Python canonical token."""
|
|
329
|
+
return when(column.isNull(), lit("n")).otherwise(_ENCODE(column))
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _parsed_string(name: str, typed: DataType, *, lossless: bool, for_join: bool) -> Column:
|
|
333
|
+
column = _column(name)
|
|
334
|
+
if isinstance(typed, DecimalType):
|
|
335
|
+
return _decimal_string_token(
|
|
336
|
+
name, typed.precision, typed.scale, lossless=lossless, for_join=for_join
|
|
337
|
+
)
|
|
338
|
+
parsed, ok = _parse(name, typed, lossless=lossless)
|
|
339
|
+
aligned = _direct_token(parsed, typed)
|
|
340
|
+
# A failed key keeps its own token, so two equal bad strings still join
|
|
341
|
+
# and a bad string does not join a typed value. A failed compared value
|
|
342
|
+
# uses an invalid token, which is not null and does not match the typed side.
|
|
343
|
+
fallback = _cell_token(column) if for_join else _invalid_token(column)
|
|
344
|
+
return when(column.isNull(), lit("n")).when(ok, aligned).otherwise(fallback)
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _decimal_string_token(
|
|
348
|
+
name: str, precision: int, scale: int, *, lossless: bool, for_join: bool
|
|
349
|
+
) -> Column:
|
|
350
|
+
column = _column(name)
|
|
351
|
+
fallback = _cell_token(column) if for_join else _invalid_token(column)
|
|
352
|
+
if lossless:
|
|
353
|
+
# Spark's own cast uses an exponent from scale 7. The plain text does not.
|
|
354
|
+
parsed = _try_name(name, f"decimal({precision},{scale})")
|
|
355
|
+
rendered = _PLAIN_DECIMAL(parsed, lit(scale))
|
|
356
|
+
ok = (
|
|
357
|
+
parsed.isNotNull() & _ASCII_AMOUNT(column) & rendered.isNotNull() & (column == rendered)
|
|
358
|
+
)
|
|
359
|
+
aligned = _cell_token(parsed)
|
|
360
|
+
return when(column.isNull(), lit("n")).when(ok, aligned).otherwise(fallback)
|
|
361
|
+
payload = _DECIMAL_PAYLOAD(trim(column), lit(precision), lit(scale))
|
|
362
|
+
size = length(encode(payload, "UTF-8")).cast("string")
|
|
363
|
+
token = concat(lit("decimal:"), size, lit(":"), payload)
|
|
364
|
+
return when(column.isNull(), lit("n")).when(payload.isNull(), fallback).otherwise(token)
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def _parsed_display(name: str, typed: DataType) -> Column:
|
|
368
|
+
column = _column(name)
|
|
369
|
+
if isinstance(typed, DecimalType):
|
|
370
|
+
payload = _DECIMAL_PAYLOAD(trim(column), lit(typed.precision), lit(typed.scale))
|
|
371
|
+
return (
|
|
372
|
+
when(column.isNull(), lit(None).cast("string"))
|
|
373
|
+
.when(payload.isNull(), column.cast("string"))
|
|
374
|
+
.otherwise(payload)
|
|
375
|
+
)
|
|
376
|
+
parsed, ok = _parse(name, typed, lossless=False)
|
|
377
|
+
if isinstance(typed, TimestampNTZType):
|
|
378
|
+
shown = date_format(parsed, _TIMESTAMP_NTZ_PATTERN)
|
|
379
|
+
elif isinstance(typed, TimestampType):
|
|
380
|
+
shown = date_format(parsed, _TIMESTAMP_PATTERN)
|
|
381
|
+
elif isinstance(typed, DateType):
|
|
382
|
+
shown = date_format(parsed, "yyyy-MM-dd")
|
|
383
|
+
else:
|
|
384
|
+
shown = parsed.cast("string")
|
|
385
|
+
return (
|
|
386
|
+
when(column.isNull(), lit(None).cast("string"))
|
|
387
|
+
.when(ok, shown)
|
|
388
|
+
.otherwise(column.cast("string"))
|
|
389
|
+
)
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def _parse(name: str, typed: DataType, *, lossless: bool) -> tuple[Column, Column]:
|
|
393
|
+
column = _column(name)
|
|
394
|
+
if _is_int(typed):
|
|
395
|
+
parsed = _try_name(name, "bigint")
|
|
396
|
+
# ASCII amount text, so 1_000 and non-ASCII digits are not integers.
|
|
397
|
+
text_ok = _ASCII_AMOUNT(column)
|
|
398
|
+
if lossless:
|
|
399
|
+
# Digits only. " 1" and "01" are not "1".
|
|
400
|
+
ok = parsed.isNotNull() & text_ok & (column == parsed.cast("string"))
|
|
401
|
+
else:
|
|
402
|
+
ok = parsed.isNotNull() & text_ok
|
|
403
|
+
return parsed, ok
|
|
404
|
+
if isinstance(typed, DateType):
|
|
405
|
+
parsed = _try_name(name, "date")
|
|
406
|
+
canon = date_format(parsed, "yyyy-MM-dd")
|
|
407
|
+
# Values may have surrounding spaces. Keys must already be canonical.
|
|
408
|
+
compared = column if lossless else trim(column)
|
|
409
|
+
ok = parsed.isNotNull() & _ascii_only(column) & (compared == canon)
|
|
410
|
+
return parsed, ok
|
|
411
|
+
if isinstance(typed, TimestampNTZType):
|
|
412
|
+
parsed = _try_name(name, "timestamp_ntz")
|
|
413
|
+
text_ok = _ascii_only(column)
|
|
414
|
+
if lossless:
|
|
415
|
+
canon = date_format(parsed, _TIMESTAMP_NTZ_PATTERN)
|
|
416
|
+
ok = parsed.isNotNull() & text_ok & (column == canon)
|
|
417
|
+
else:
|
|
418
|
+
ok = parsed.isNotNull() & text_ok
|
|
419
|
+
return parsed, ok
|
|
420
|
+
if isinstance(typed, TimestampType):
|
|
421
|
+
parsed = _try_name(name, "timestamp")
|
|
422
|
+
text_ok = _ascii_only(column)
|
|
423
|
+
if lossless:
|
|
424
|
+
canon = date_format(parsed, _TIMESTAMP_PATTERN)
|
|
425
|
+
ok = parsed.isNotNull() & text_ok & (column == canon)
|
|
426
|
+
else:
|
|
427
|
+
ok = parsed.isNotNull() & text_ok
|
|
428
|
+
return parsed, ok
|
|
429
|
+
if isinstance(typed, BooleanType):
|
|
430
|
+
parsed = _try_name(name, "boolean")
|
|
431
|
+
text_ok = _ascii_only(column)
|
|
432
|
+
if lossless:
|
|
433
|
+
exact = (column == lit("true")) | (column == lit("false"))
|
|
434
|
+
ok = parsed.isNotNull() & text_ok & exact
|
|
435
|
+
else:
|
|
436
|
+
ok = parsed.isNotNull() & text_ok
|
|
437
|
+
return parsed, ok
|
|
438
|
+
if isinstance(typed, FloatType):
|
|
439
|
+
parsed = _try_name(name, "float")
|
|
440
|
+
return parsed, parsed.isNotNull() & _ASCII_AMOUNT(column)
|
|
441
|
+
if isinstance(typed, DoubleType):
|
|
442
|
+
parsed = _try_name(name, "double")
|
|
443
|
+
return parsed, parsed.isNotNull() & _ASCII_AMOUNT(column)
|
|
444
|
+
if isinstance(typed, BinaryType):
|
|
445
|
+
return column, lit(False)
|
|
446
|
+
return column, lit(False)
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def _ascii_only(column: Column) -> Column:
|
|
450
|
+
"""True for printable ASCII, plus the space and tab a value parse may trim.
|
|
451
|
+
|
|
452
|
+
Other ASCII controls (``\\x00``-``\\x1f`` and ``\\x7f``) are rejected.
|
|
453
|
+
``\\z`` is the end of the text. Java's ``$`` also matches before a final
|
|
454
|
+
line break, so ``true\\n`` and a timestamp ending in ``\\r\\n`` would pass
|
|
455
|
+
and Spark's cast would trim them into a match.
|
|
456
|
+
"""
|
|
457
|
+
return column.rlike(r"^[\t\x20-\x7e]*\z")
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def _quote_ident(name: str) -> str:
|
|
461
|
+
"""Return a Spark identifier. Backticks inside the name are doubled."""
|
|
462
|
+
return "`" + name.replace("`", "``") + "`"
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def _try_name(name: str, sql_type: str) -> Column:
|
|
466
|
+
# try_cast returns null for a value that does not fit, including when ANSI
|
|
467
|
+
# mode is on. The name is quoted so a hyphen or a dot stays one identifier.
|
|
468
|
+
return expr(f"try_cast({_quote_ident(name)} as {sql_type})")
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def _invalid_token(column: Column) -> Column:
|
|
472
|
+
payload = column.cast("string")
|
|
473
|
+
size = length(encode(payload, "UTF-8")).cast("string")
|
|
474
|
+
return concat(lit("invalid:string:"), size, lit(":"), payload)
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def _dtype(plan: FieldPlan, side: str) -> DataType:
|
|
478
|
+
return plan.source_type if side == "source" else plan.target_type
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def _other_type(plan: FieldPlan, side: str) -> DataType:
|
|
482
|
+
return plan.target_type if side == "source" else plan.source_type
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def _is_int(dtype: DataType) -> bool:
|
|
486
|
+
return isinstance(dtype, _INTEGER_TYPES)
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def _is_timestamp(dtype: DataType) -> bool:
|
|
490
|
+
return isinstance(dtype, (TimestampType, TimestampNTZType))
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def _column(name: str) -> Column:
|
|
494
|
+
return col("`" + name.replace("`", "``") + "`")
|