Repository navigation
Check the type of each CSV value instead of failing the read #1724
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
markhm
wants to merge
3
commits into
datacontract:main
Choose a base branch
from
markhm:fix/csv-type-checks
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| """The values of a CSV file, read as text, converted to the types the contract declares. | ||
|
|
||
| One definition serves both the table the checks read and the type check on the text, so a value the type check | ||
| reports is the same value the table holds as NULL: the other checks on its column treat it as missing. | ||
| """ | ||
|
|
||
| import datetime | ||
| from typing import Optional | ||
|
|
||
| from open_data_contract_standard.model import SchemaProperty | ||
|
|
||
| from datacontract.export.duckdb_type_converter import convert_to_duckdb_csv_type | ||
|
|
||
| # The DuckDB type of each converted column and its ibis spelling; any other column stays text | ||
| CSV_TYPES = { | ||
| "BIGINT": "int64", | ||
| "DOUBLE": "float64", | ||
| "BOOLEAN": "boolean", | ||
| "DATE": "date", | ||
| "TIMESTAMP": "timestamp", | ||
| "TIME": "time", | ||
| } | ||
| _DATE_TIME_TYPES = {"DATE", "TIMESTAMP", "TIME"} | ||
|
|
||
| # Java DateTimeFormatter letters (ODCS logicalTypeOptions.format) and their strptime directives, longest first | ||
| _PATTERN_LETTERS = [ | ||
| ("yyyy", "%Y"), | ||
| ("uuuu", "%Y"), | ||
| ("yy", "%y"), | ||
| ("MMMM", "%B"), | ||
| ("MMM", "%b"), | ||
| ("MM", "%m"), | ||
| ("M", "%-m"), | ||
| ("dd", "%d"), | ||
| ("d", "%-d"), | ||
| ("HH", "%H"), | ||
| ("H", "%-H"), | ||
| ("hh", "%I"), | ||
| ("h", "%-I"), | ||
| ("mm", "%M"), | ||
| ("m", "%-M"), | ||
| ("ss", "%S"), | ||
| ("s", "%-S"), | ||
| ("SSSSSS", "%f"), | ||
| ("SSS", "%g"), | ||
| ("a", "%p"), | ||
| ("EEEE", "%A"), | ||
| ("EEE", "%a"), | ||
| # XXX is left out: it writes a zero offset as Z, which %z does not read | ||
| ("xxx", "%z"), | ||
| ("Z", "%z"), | ||
| ] | ||
|
|
||
|
|
||
| def strptime_format(pattern: str) -> Optional[str]: | ||
| """The strptime format of a Java DateTimeFormatter pattern, or None for a pattern it cannot express.""" | ||
| out = [] | ||
| i = 0 | ||
| while i < len(pattern): | ||
| c = pattern[i] | ||
| if c == "'": | ||
| end = pattern.find("'", i + 1) | ||
| if end == -1: | ||
| return None | ||
| out.append("'" if end == i + 1 else pattern[i + 1 : end].replace("%", "%%")) | ||
| i = end + 1 | ||
| elif c.isalpha(): | ||
| letters = next((pair for pair in _PATTERN_LETTERS if pattern.startswith(pair[0], i)), None) | ||
| if letters is None: | ||
| return None | ||
| out.append(letters[1]) | ||
| i += len(letters[0]) | ||
| else: | ||
| out.append("%%" if c == "%" else c) | ||
| i += 1 | ||
| return "".join(out) | ||
|
|
||
|
|
||
| def csv_type(prop: SchemaProperty) -> Optional[str]: | ||
| """The DuckDB type a CSV column is converted to, or None for a column that stays text.""" | ||
| duckdb_type = convert_to_duckdb_csv_type(prop) | ||
| return duckdb_type if duckdb_type in CSV_TYPES else None | ||
|
|
||
|
|
||
| def csv_format(prop: SchemaProperty, duckdb_type: Optional[str]) -> Optional[str]: | ||
| """The declared format of a date, timestamp or time column (Java DateTimeFormatter), or None. | ||
|
|
||
| A format strptime cannot express is None too, so the column is read as ISO 8601; the type check says so. | ||
| """ | ||
| if duckdb_type not in _DATE_TIME_TYPES or not prop.logicalTypeOptions: | ||
| return None | ||
| pattern = prop.logicalTypeOptions.get("format") | ||
| return pattern if pattern and strptime_format(pattern) is not None else None | ||
|
|
||
|
|
||
| def csv_value(text, duckdb_type: str, pattern: Optional[str] = None): | ||
| """The ibis expression converting `text` to `duckdb_type`: NULL for a value that does not convert. | ||
|
|
||
| An integer is a whole number, not 2.50 or 2.00, which a cast would round. A date, timestamp or time in a | ||
| declared format must be in that format and exist; without one, it is ISO 8601. | ||
| """ | ||
| import ibis | ||
|
|
||
| target = CSV_TYPES[duckdb_type] | ||
| if duckdb_type == "BIGINT": | ||
| return text.strip().re_search(r"^[+-]?[0-9]+$").ifelse(text.strip().try_cast(target), ibis.null(target)) | ||
| if pattern is not None and duckdb_type in _DATE_TIME_TYPES: | ||
|
|
||
| @ibis.udf.scalar.builtin | ||
| def try_strptime(value: str, format: str) -> datetime.datetime: # -> TRY_STRPTIME(value, format) | ||
| ... | ||
|
|
||
| return try_strptime(text, strptime_format(pattern)).cast(target) | ||
| return text.try_cast(target) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -29,6 +29,7 @@ | |
| schema_property_mismatch_reasons, | ||
| ) | ||
| from datacontract.engines.ibis.connections.connect import connect_ibis | ||
| from datacontract.engines.ibis.csv_values import csv_value | ||
| from datacontract.engines.ibis.dtype_category import ibis_dtype_to_schema_property | ||
| from datacontract.engines.ibis.native_type import ( | ||
| fetch_native_types, | ||
|
|
@@ -175,12 +176,13 @@ def execute_ibis_checks( | |
| # Unsupported server type/format already logged a warning check. | ||
| return | ||
|
|
||
| by_model: dict[str, List[CheckSpec]] = defaultdict(list) | ||
| # The checks on the values of a file as text (a CSV value of the wrong type) read the {model}__raw__ view | ||
| by_model: dict[tuple[str, bool], List[CheckSpec]] = defaultdict(list) | ||
| for spec in executable: | ||
| by_model[spec.model].append(spec) | ||
| by_model[(spec.model, spec.uses_raw_view and spec.metric == MetricType.INVALID_COUNT)].append(spec) | ||
|
|
||
| try: | ||
| for model, model_specs in by_model.items(): | ||
| for (model, raw), model_specs in by_model.items(): | ||
| _run_model( | ||
| run, | ||
| con, | ||
|
|
@@ -189,8 +191,10 @@ def execute_ibis_checks( | |
| data_contract, | ||
| server, | ||
| include_failed_samples, | ||
| row_filter=(model_filters or {}).get(model), | ||
| # The filter is written against the typed columns, not their text | ||
| row_filter=None if raw else (model_filters or {}).get(model), | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This type check ignores |
||
| schema_name=schema_name, | ||
| table=f"{model}__raw__" if raw else None, | ||
| ) | ||
| finally: | ||
| _maybe_disconnect(con, spark, duckdb_connection) | ||
|
|
@@ -226,9 +230,10 @@ def _run_model( | |
| include_failed_samples: bool = False, | ||
| row_filter: Optional[str] = None, | ||
| schema_name: str = "all", | ||
| table: Optional[str] = None, | ||
| ): | ||
| try: | ||
| t = _resolve_table(con, model, _table_database(con, server)) | ||
| t = _resolve_table(con, table or model, _table_database(con, server)) | ||
| except Exception as e: | ||
| logger.warning("Could not read model '%s': %s", model, e) | ||
| _fail_all(run, specs, ResultEnum.failed, f"Could not read model '{model}': {e}") | ||
|
|
@@ -676,6 +681,8 @@ def _has_array_constraints(spec: CheckSpec) -> bool: | |
| def _valid_expr(t, col, dtype, spec: CheckSpec): | ||
| """Boolean: a non-missing value satisfies all configured validity constraints.""" | ||
| conds = [] | ||
| if spec.valid_type is not None: | ||
| conds.append(csv_value(col, spec.valid_type, spec.valid_type_format).notnull()) | ||
| if spec.valid_values is not None: | ||
| conds.append(col.isin(spec.valid_values)) | ||
| if spec.valid_regex is not None: | ||
|
|
@@ -732,6 +739,10 @@ def _constraint_info(spec: CheckSpec) -> dict: | |
| single entry; several are still handled for forward-compatibility. | ||
| """ | ||
| info: dict = {} | ||
| if spec.valid_type is not None: | ||
| info["type"] = spec.valid_type | ||
| if spec.valid_type_format is not None: | ||
| info["format"] = spec.valid_type_format | ||
| if spec.valid_values is not None: | ||
| info["valid_values"] = spec.valid_values | ||
| if spec.invalid_values: | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When this integer check fails,
--output-format junitcrashes withnot well-formed (invalid token)and writes no file. The cause isstrip(): ibis compiles it toTRIM(n, ' \t\n\r\v\f'), which puts a literal vertical tab into the check's SQL, and that SQL ends up in the XML. Letting the regex accept surrounding blanks avoids it: