diff --git a/CHANGELOG.md b/CHANGELOG.md index b9f10ec86..f3610b1aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `datacontract test`: check constraints and quality rules on nested properties on Athena and Trino servers ### Fixed +- `datacontract test`: a CSV value of the wrong type fails the type check of its column instead of stopping the run (#1721) - `datacontract lint` and `datacontract test`: warn about unknown fields, such as a misspelled `quality`, instead of silently ignoring them (will be an error in the next major version in January 2027) - `datacontract import sqlserver` and the physical type checks of `datacontract test` work on case-sensitive SQL Server databases such as Microsoft Fabric warehouses (#1705 @Octacon100) - `datacontract import`: Postgres and DuckDB `uuid` columns import as `string` with format `uuid` instead of without a logicalType diff --git a/datacontract/engines/checks/check_spec.py b/datacontract/engines/checks/check_spec.py index 18f49b38f..0c5a20d01 100644 --- a/datacontract/engines/checks/check_spec.py +++ b/datacontract/engines/checks/check_spec.py @@ -153,6 +153,8 @@ class CheckSpec: valid_min_items: Optional[int] = None # INVALID_COUNT, array columns valid_max_items: Optional[int] = None # INVALID_COUNT, array columns valid_unique_items: Optional[bool] = None # INVALID_COUNT, array columns + valid_type: Optional[str] = None # INVALID_COUNT: the logicalType a text value must convert to + valid_type_format: Optional[str] = None # INVALID_COUNT: its logicalTypeOptions.format (JDK DateTimeFormatter) expected_category: Optional[str] = None # FIELD_TYPE: human-readable label (display only) expected_type_label: Optional[str] = None # FIELD_TYPE: human-readable expected type @@ -170,7 +172,7 @@ class CheckSpec: seconds: Optional[int] = None # FRESHNESS / RETENTION threshold in seconds - uses_raw_view: bool = False # FIELD_PRESENT against the duckdb {model}__raw__ view + uses_raw_view: bool = False # FIELD_PRESENT / INVALID_COUNT against the duckdb {model}__raw__ view # Preset result/reason for checks that are not executed (UNSUPPORTED). preset_result: Optional[str] = None @@ -195,5 +197,6 @@ def has_validity_constraints(self) -> bool: self.valid_min_items, self.valid_max_items, self.valid_unique_items, + self.valid_type, ) ) diff --git a/datacontract/engines/checks/create_checks.py b/datacontract/engines/checks/create_checks.py index f60ffb1ec..9e03f213c 100644 --- a/datacontract/engines/checks/create_checks.py +++ b/datacontract/engines/checks/create_checks.py @@ -36,6 +36,7 @@ from datacontract.engines.checks.dimensions import default_dimension from datacontract.engines.checks.sql_guard import dialect_for_server_type, refusal_reason, sqlglot_dialect_by_name from datacontract.engines.checks.type_normalize import normalize_type_name +from datacontract.engines.ibis.csv_values import csv_format, csv_type from datacontract.engines.ibis.native_type import supports_native_type_introspection from datacontract.model.enum_values import get_enum_values from datacontract.model.server import get_server_type @@ -403,6 +404,25 @@ def _to_schema_checks( ) if nested_checks_possible: checks.append(_nested_type_check(model, field, prop, physical=False)) + elif uses_raw_view and server.format == "csv" and not nested and csv_type(prop) is not None: + # A CSV file holds text: each value must convert to the declared type, or this check fails, and the + # value is NULL for the other checks (see csv_values) + duckdb_type = csv_type(prop) + pattern = _get_logical_type_option(prop, "format") if duckdb_type in ("DATE", "TIMESTAMP", "TIME") else None + type_check = _invalid_count_check( + model, + field, + "field_type", + name=f"Check that field {field} has type {prop.logicalType or prop.physicalType}", + valid_type=duckdb_type, + valid_type_format=csv_format(prop, duckdb_type), + uses_raw_view=True, + ) + if pattern and type_check.valid_type_format is None: + type_check.metric = MetricType.UNSUPPORTED + type_check.preset_result = "warning" + type_check.preset_reason = f"The format '{pattern}' cannot be checked; values are read as ISO 8601." + checks.append(type_check) if prop.required: checks.append( diff --git a/datacontract/engines/ibis/connections/duckdb_connection.py b/datacontract/engines/ibis/connections/duckdb_connection.py index 1767d5dbe..d729dcc57 100644 --- a/datacontract/engines/ibis/connections/duckdb_connection.py +++ b/datacontract/engines/ibis/connections/duckdb_connection.py @@ -6,6 +6,7 @@ from datacontract.config import Config from datacontract.engines.ibis.connections.aws_credentials import resolve_aws_credentials +from datacontract.engines.ibis.csv_values import csv_format, csv_type, csv_value from datacontract.export.duckdb_type_converter import convert_to_duckdb_csv_type, convert_to_duckdb_json_type from datacontract.export.sql_type_converter import convert_to_duckdb from datacontract.model.run import Run @@ -113,9 +114,7 @@ def get_duckdb_connection( elif server.format == "parquet": create_view_with_schema_union(con, schema_obj, model_path, "read_parquet", to_parquet_types) elif server.format == "csv": - create_view_with_schema_union( - con, schema_obj, model_path, "read_csv", to_csv_types, read_options=_csv_encoding_options(server) - ) + create_csv_views(con, schema_obj, model_path, read_options=_csv_encoding_options(server)) elif server.format == "delta": con.sql(f"""CREATE VIEW "{model_name}" AS SELECT * FROM delta_scan('{model_path}');""") elif server.format == "xml": @@ -256,6 +255,45 @@ def create_view_with_schema_union( ) +def create_csv_views(con, schema_obj: SchemaObject, model_path: str, read_options: str = ""): + """The CSV files as text in a raw view, and in the contract's types in a table, NULL where a value doesn't convert.""" + import ibis + + model_name = schema_obj.name + raw_name = f"{model_name}__raw__" + # Raw view to check for absent columns (check_property_is_present) and the type of each value + con.sql( + f"""CREATE VIEW {_quote(raw_name)} AS + SELECT * FROM read_csv('{model_path}', union_by_name=true, hive_partitioning=1, all_varchar=true{read_options});""" + ) + + converted_types = to_csv_types(schema_obj) + if not converted_types: + # Fallback: no columns declared, so DuckDB infers the types + con.sql( + f"""CREATE VIEW {_quote(model_name)} AS + SELECT * FROM read_csv('{model_path}', union_by_name=true, hive_partitioning=1{read_options});""" + ) + return + + columns_def = [f"{_quote(col_name)} {col_type}" for col_name, col_type in converted_types.items()] + con.sql(f"CREATE TABLE {_quote(model_name)} ({', '.join(columns_def)});") + + present = con.sql(f"SELECT * FROM {_quote(raw_name)}").columns + properties = [p for p in schema_obj.properties if (p.physicalName or p.name) in present] + if not properties: + return + raw = ibis.table({column: "string" for column in present}, name=raw_name) + values = {} + for prop in properties: + column = raw[prop.physicalName or prop.name] + duckdb_type = csv_type(prop) + values[column.get_name()] = ( + csv_value(column, duckdb_type, csv_format(prop, duckdb_type)) if duckdb_type else column + ) + con.sql(f"INSERT INTO {_quote(model_name)} BY NAME ({ibis.to_sql(raw.select(**values), dialect='duckdb')});") + + # read_xml refuses files above 16 MB by default, with a SAX parsing error; a file is read whole either way XML_MAXIMUM_FILE_SIZE = 2**40 diff --git a/datacontract/engines/ibis/csv_values.py b/datacontract/engines/ibis/csv_values.py new file mode 100644 index 000000000..1101d3549 --- /dev/null +++ b/datacontract/engines/ibis/csv_values.py @@ -0,0 +1,104 @@ +"""CSV text converted to the contract's types: one definition for the typed table and the type check on the text.""" + +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, or None if strptime cannot express it (ISO 8601 then).""" + 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.""" + import ibis + + target = CSV_TYPES[duckdb_type] + if duckdb_type == "BIGINT": + # A cast would round 2.50 + 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) diff --git a/datacontract/engines/ibis/ibis_check_execute.py b/datacontract/engines/ibis/ibis_check_execute.py index f8e6cce54..5961aa725 100644 --- a/datacontract/engines/ibis/ibis_check_execute.py +++ b/datacontract/engines/ibis/ibis_check_execute.py @@ -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), 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}") @@ -353,7 +358,11 @@ def _invalid(c, _t=t, _dtype=dtype, _spec=spec, _flag=unconstrained): _record_sql(run, spec, t.aggregate([named])) agg_exprs.append((spec, named)) except _ColumnNotFound as e: - set_result(run, spec.key, ResultEnum.failed, str(e) or f"Column '{spec.field}' not found") + if table: + # The presence check already fails a column missing from the file + set_result(run, spec.key, ResultEnum.skipped, f"Column '{spec.field}' is missing") + else: + set_result(run, spec.key, ResultEnum.failed, str(e) or f"Column '{spec.field}' not found") except Exception as e: logger.warning("Check '%s' errored: %s", spec.key, e) set_result(run, spec.key, ResultEnum.failed, f"Error evaluating check: {e}") @@ -676,6 +685,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 +743,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: diff --git a/docs/docs/reference/azure.md b/docs/docs/reference/azure.md index f9aaa8a0c..9ac72db2a 100644 --- a/docs/docs/reference/azure.md +++ b/docs/docs/reference/azure.md @@ -44,7 +44,7 @@ Files on Azure storage are read with DuckDB. Type handling depends on the `forma | `format` | How types are handled | |---|---| -| `csv` | The file is read **as the contract's types** — no type checks are generated; a value that can't be coerced surfaces as a read error. | +| `csv` | The file is read as text, and each typed column gets a type check of its values, as for [local files](./local.md#data-types). | | `json` | Same as CSV, plus every record is validated against a JSON Schema derived from the contract's `logicalType`s. | | `parquet` | The file is read **as the contract's types**, like CSV, so checking its types is not supported yet, a value that can't be cast surfaces as a read error. | | `delta` | Column types come from the Delta table; the contract's `logicalType` is checked by category. | diff --git a/docs/docs/reference/gcs.md b/docs/docs/reference/gcs.md index bdafe3e42..c31c6503c 100644 --- a/docs/docs/reference/gcs.md +++ b/docs/docs/reference/gcs.md @@ -34,7 +34,7 @@ The `location` in the `servers` block must use the `s3://` scheme (not `gs://`). ## Data types -Same as [Amazon S3](./s3.md#data-types): CSV and JSON files are read as the contract's types (no type checks; JSON additionally validated against a JSON Schema derived from the contract), Parquet files are read as the contract's types too, so their type checks are reported as warnings (not supported yet), and Delta column types are checked against the contract's `logicalType` by category. `physicalType` is never checked against file sources. +Same as [Amazon S3](./s3.md#data-types): CSV files are read as text and the values of each typed column are type-checked, JSON files are read as the contract's types (no type checks; validated against a JSON Schema derived from the contract), Parquet files are read as the contract's types too, so their type checks are reported as warnings (not supported yet), and Delta column types are checked against the contract's `logicalType` by category. `physicalType` is never checked against file sources. {/* AUTOGENERATED TYPE MAPPING: do not edit by hand; regenerate with update_reference_types.py */} diff --git a/docs/docs/reference/index.md b/docs/docs/reference/index.md index 4c169aff5..a250e170f 100644 --- a/docs/docs/reference/index.md +++ b/docs/docs/reference/index.md @@ -25,7 +25,7 @@ When you run `datacontract test`, type checks work in one of two modes: 1. **Native type check** (`Check that field x has physical type y`) — on sources with catalog introspection (Snowflake, BigQuery, Databricks, Postgres, Redshift, SQL Server, Oracle, Trino, Athena, Exasol, ClickHouse, Hive), the declared `physicalType` is compared against the actual column type from the catalog. Timezone variants of timestamps are interchangeable; length/precision is only enforced when the contract declares it (`varchar` matches `varchar(255)`, but `varchar(255)` does not match `varchar(100)`). A `physicalType` that can't be interpreted in the server's dialect degrades to the logical check or a warning — never a hard failure. 2. **Logical type check** (`Check that field x has type y`) — everywhere else (and as fallback), both the declared and the actual type are normalized to one of the ODCS logical types and compared. `integer` and `number` are mutually compatible; a bare `object` or `array` matches any structure with the same base. -For file sources with `format: csv`, `json`, `xml`, or `avro`, no type checks are generated — the file is read *as* the contract's types, and violations surface as read errors (plus JSON Schema validation for `format: json`). +For file sources with `format: json`, `xml`, or `avro`, no type checks are generated — the file is read *as* the contract's types, and violations surface as read errors (plus JSON Schema validation for `format: json`). A `format: csv` file is read as text, and the values of each typed column are checked against its type. Independent of the type checks, `logicalTypeOptions` (`minimum`, `maximum`, `minLength`, `maxLength`, `pattern`, `enum`, …) generate value checks that behave identically on every source. diff --git a/docs/docs/reference/local.md b/docs/docs/reference/local.md index 77a63b8bd..4183a0434 100644 --- a/docs/docs/reference/local.md +++ b/docs/docs/reference/local.md @@ -44,10 +44,10 @@ Type handling depends on the `format` in the `servers` block: | `format` | How types are handled | |---|---| -| `csv` | The file is read **as the contract's types** — no type checks are generated; a value that can't be coerced surfaces as a read error. | -| `json` | Same as CSV, plus every record is validated against a JSON Schema derived from the contract's `logicalType`s (with `format` options like `date-time`, `uuid`). | -| `xml` | Like CSV: the documents are read **as the contract's types**, with nested elements as structs and repeated elements as lists. | -| `parquet` | The file is read **as the contract's types**, like CSV, so checking its types is not supported yet, and a value that can't be cast surfaces as a read error. | +| `csv` | The file is read as text, and every `integer`, `number`, `boolean`, `date`, `timestamp`, and `time` column gets a type check: each value must convert to its type, or the check fails with the number of bad values (`--include-failed-samples` shows them). An `integer` is a whole number (`2.50` and `2.00` are not); a `date`, `timestamp`, or `time` is in its `logicalTypeOptions.format` (a Java `DateTimeFormatter` pattern such as `dd/MM/yyyy`) or, without one, in ISO 8601. A bad value is missing for the other checks of its column. | +| `json` | The file is read **as the contract's types**; a value of the wrong type reads as missing, and every record is validated against a JSON Schema derived from the contract's `logicalType`s (with `format` options like `date-time`, `uuid`). | +| `xml` | The documents are read **as the contract's types**, with nested elements as structs and repeated elements as lists. | +| `parquet` | The file is read **as the contract's types**, so checking its types is not supported yet, and a value that can't be cast surfaces as a read error. | | `delta` | Column types come from the Delta table; the contract's `logicalType` is checked by category. | **Presence.** For `json` and `xml`, only the required top-level properties are checked for presence: a document may leave out a property that is not required, even in every record. For the other formats, every column of the contract must exist in the file. diff --git a/docs/docs/reference/s3.md b/docs/docs/reference/s3.md index 351e4b9d2..d15afcacd 100644 --- a/docs/docs/reference/s3.md +++ b/docs/docs/reference/s3.md @@ -55,7 +55,7 @@ Files on S3 are read with DuckDB. Type handling depends on the `format` in the ` | `format` | How types are handled | |---|---| -| `csv` | The file is read **as the contract's types** — no type checks are generated; a value that can't be coerced surfaces as a read error. | +| `csv` | The file is read as text, and each typed column gets a type check of its values, as for [local files](./local.md#data-types). | | `json` | Same as CSV, plus every record is validated against a JSON Schema derived from the contract's `logicalType`s (with `format` options like `date-time`, `uuid`). | | `parquet` | The file is read **as the contract's types**, like CSV, so checking its types is not supported yet, and a value that can't be cast surfaces as a read error. | | `delta` | Column types come from the Delta table; the contract's `logicalType` is checked by category. | diff --git a/docs/docs/schema.md b/docs/docs/schema.md index 62462df8e..1581ff103 100644 --- a/docs/docs/schema.md +++ b/docs/docs/schema.md @@ -107,7 +107,7 @@ Property-level `enum` entries must have distinct values, even if their labels, I Vector type checks compare dimensions and element types when the data source reports them. `logicalTypeOptions.elementType` defaults to `float32`; a column reported as `float64` or `int8` does not satisfy that declaration. Catalogs that expose only a numeric array without its element width cannot confirm an element-type mismatch. :::note -For file servers with `format: csv`, `json`, `xml`, `avro` or `parquet` **no type check is generated at all** — the file is read *as* the contract's types, so a mismatch surfaces as a read error instead. `format: delta` is read with the table's own types, so its types, nested ones included, are checked. `format: json` is additionally validated against a JSON Schema derived from the contract. See [Data Source Reference](./reference/index.md#how-data-types-work) for the full type-mapping rules. +For file servers with `format: json`, `xml`, `avro` or `parquet` **no type check is generated at all** — the file is read *as* the contract's types, so a mismatch surfaces as a read error instead. `format: csv` is read as text, and each value of an `integer`, `number`, `boolean`, `date`, `timestamp` or `time` column is checked against its type (and its `format`). `format: delta` is read with the table's own types, so its types, nested ones included, are checked. `format: json` is additionally validated against a JSON Schema derived from the contract. See [Data Source Reference](./reference/index.md#how-data-types-work) for the full type-mapping rules. ::: ## Required, unique, and primary keys @@ -217,7 +217,7 @@ ODCS v3.2.0 adds fields that describe a schema object or property for people and These are common sources of confusion. They are valid ODCS and appear in exports, but they generate no check: - **`isNullable`** — the CLI reads `required`, not `isNullable`. Write `required: true` to assert that a column has no nulls. -- **`logicalTypeOptions.format`** — never enforced, on any property. On a `string` property (`email`, `uuid`, `uri`, …) use `pattern` for an enforceable equivalent. On a `date`, `timestamp` or `time` property `format` holds a date pattern such as `yyyy-MM-dd`, and `pattern` is *not* an equivalent there: by the time a check runs, the column has already been parsed as a date, so there is no string left to match. Such a column is validated as a date, in whatever format the server stores it. +- **`logicalTypeOptions.format`** — not enforced, except on a `date`, `timestamp` or `time` column of a [CSV file](./reference/local.md#data-types). On a `string` property (`email`, `uuid`, `uri`, …) use `pattern` for an enforceable equivalent. On a `date`, `timestamp` or `time` property `format` holds a date pattern such as `yyyy-MM-dd`, and `pattern` is *not* an equivalent there: by the time a check runs, the column has already been parsed as a date, so there is no string left to match. Such a column is validated as a date, in whatever format the server stores it; a CSV file stores text, so there each value must be in the declared format. - **Descriptive attributes** — `description`, `businessName`, `examples`, `tags`, `classification`, `criticalDataElement`, `transformSourceObjects`, and `customProperties`. `authoritativeDefinitions` generates no check either, but it *is* resolved and inlined before the checks are built — see [Link your Semantics](./semantics.md). - **Schema-level attributes** other than `name`, `physicalName`, `properties`, and `quality`. - **Constraints and quality rules on nested properties, on some servers** — `required`, `unique`, `pattern`, `enum`, the other `logicalTypeOptions` and `quality` rules below the top level are checked on the `dataframe`, `databricks`, `trino` and `athena` servers and on every server read through DuckDB (`local`, `s3`, `gcs`, `azure`, `duckdb`, `iceberg`, `kafka`). On every other server, nested properties are only type-checked, and each of their constraints and quality rules is reported as a warning. On SAP HANA, only their quality rules are reported as warnings; their constraints are not checked. diff --git a/docs/docs/testing/local.md b/docs/docs/testing/local.md index f7acbe51f..366e6e4c9 100644 --- a/docs/docs/testing/local.md +++ b/docs/docs/testing/local.md @@ -50,7 +50,7 @@ Server: production (type=local, format=csv, path=orders.csv) │ passed │ Check that field order_total has a maximum of 4999.0 │ order_total │ │ │ ... │ │ │ │ ╰────────┴──────────────────────────────────────────────────────┴─────────────┴─────────╯ -🟢 Data contract is valid. Ran 17 checks. Took 1.2 seconds. +🟢 Data contract is valid. Ran 19 checks. Took 1.2 seconds. ``` ## 4. Let it catch a violation @@ -91,6 +91,6 @@ JSON files (`.json`, `.jsonl`, `.ndjson`) are also validated against a JSON Sche - **`No files found that match the pattern`** — the `path` is a glob over file paths, not a directory, and it is resolved relative to the working directory rather than to the contract. - **No checks run at all** — the `format` in the `servers` block must be one of `csv`, `json`, `parquet`, `xml`, or `delta`. It is never guessed at test time (only `datacontract import` infers it from the file suffix), so a missing or misspelled `format` leaves the table unreadable. - **Every schema reads the same files** — with more than one schema in the contract, put the `{model}` placeholder in the `path` (e.g. `./data/{model}/*.parquet`); it is substituted with each schema's name. -- **A CSV or XML value fails as a read error instead of a type check** — CSV and XML files are read *as* the contract's types, so a value that cannot be coerced surfaces while reading. See [Data types](../reference/local.md#data-types). +- **An XML value fails as a read error instead of a type check** — XML files are read *as* the contract's types, so a value that cannot be coerced surfaces while reading. CSV files are read as text, and a value of the wrong type fails the type check of its column. See [Data types](../reference/local.md#data-types). Ready for your real data? Do the same against [Snowflake](./snowflake.md), [BigQuery](./bigquery.md), or [Databricks](./databricks.md). diff --git a/docs/docs/testing/xml.md b/docs/docs/testing/xml.md index 62db13c7a..8166cb60e 100644 --- a/docs/docs/testing/xml.md +++ b/docs/docs/testing/xml.md @@ -150,7 +150,7 @@ The command exits with code `1`, so the same call works as a gate in [CI/CD pipe - **Presence.** An element or attribute that is not required may be absent from every document, so only the required properties of the record element are checked for presence. Required values further down are checked for missing values. - **Attributes named like an element.** The import names such an attribute with an `@` prefix (`@id`), and the test reads it under that name. When an element and an attribute of the same element share a name, DuckDB's XML reader reads only the attribute, so the element's checks cannot run, with a warning. - **Large files.** Files of any size are read, each one whole, so a file needs about its size in memory. -- **Types.** The documents are read as the contract's `logicalType`s, like [CSV files](../reference/local.md#data-types); `physicalType` is not checked. +- **Types.** The documents are read as the contract's `logicalType`s (see [Data types](../reference/local.md#data-types)); `physicalType` is not checked. ## Reference diff --git a/tests/test_test_dimension_filter.py b/tests/test_test_dimension_filter.py index 0bd5405c1..51f105a80 100644 --- a/tests/test_test_dimension_filter.py +++ b/tests/test_test_dimension_filter.py @@ -138,10 +138,10 @@ def test_builtin_unique_check_maps_to_uniqueness(): def test_builtin_presence_check_maps_to_conformity(): - """A CSV source emits no type checks, so presence is the conformity schema check here.""" + """On a CSV source, presence and the type of the values are the conformity schema checks.""" run = DataContract(data_contract_str=BUILTIN_CONTRACT, dimensions={"conformity"}).test() print(run.pretty()) - assert {check.type for check in run.checks} == {"field_is_present", "servicelevel_retention"} + assert {check.type for check in run.checks} == {"field_is_present", "field_type", "servicelevel_retention"} def test_builtin_dimension_mapping(): diff --git a/tests/test_test_local_csv_types.py b/tests/test_test_local_csv_types.py new file mode 100644 index 000000000..37f1a51f4 --- /dev/null +++ b/tests/test_test_local_csv_types.py @@ -0,0 +1,196 @@ +"""A CSV value that does not match its column's declared type fails the type check of that column. + +The file is read as text; each typed column is converted from it, so the run never stops on a bad value, and the +other checks treat that value as missing. +""" + +import pytest + +from datacontract.data_contract import DataContract +from datacontract.engines.ibis.csv_values import strptime_format +from datacontract.model.run import ResultEnum + +HEADER = "order_id|quantity|amount|order_date|paid|code" +GOOD_ROWS = [ + "A1|3|19.99|01/02/2026|true|007", + "A2|2|5.00|15/02/2026|false|010", + "A3|1|7.50|28/02/2026|true|100", +] + + +def _contract( + path, quantity_options="", order_date_options="\n logicalTypeOptions:\n format: dd/MM/yyyy" +): + return f"""apiVersion: v3.2.0 +kind: DataContract +id: orders +name: orders +version: 1.0.0 +status: active +servers: + - server: local + type: local + format: csv + path: {path} +schema: + - name: orders + quality: + - type: sql + query: SELECT COUNT(*) FROM orders WHERE code = '007' + mustBe: 1 + properties: + - name: order_id + logicalType: string + primaryKey: true + - name: quantity + logicalType: integer{quantity_options} + - name: amount + logicalType: number + - name: order_date + logicalType: date{order_date_options} + - name: paid + logicalType: boolean + - name: code + logicalType: string +""" + + +def _test(tmp_path, rows, include_failed_samples=False, **options): + data = tmp_path / "orders.csv" + data.write_text("\n".join([HEADER, *rows]) + "\n") + contract = _contract(data, **options) + return DataContract( + data_contract_str=contract, inline_references=False, include_failed_samples=include_failed_samples + ).test() + + +def _type_check(run, field): + return next(c for c in run.checks if c.type == "field_type" and c.field == field) + + +def _with(column, value, row=1): + """The good rows with one cell replaced.""" + rows = [r.split("|") for r in GOOD_ROWS] + rows[row][HEADER.split("|").index(column)] = value + return ["|".join(r) for r in rows] + + +def test_a_valid_file_passes_a_type_check_per_typed_column(tmp_path): + run = _test(tmp_path, GOOD_ROWS) + print(run.pretty()) + assert run.result == ResultEnum.passed + assert {c.field for c in run.checks if c.type == "field_type"} == {"quantity", "amount", "order_date", "paid"} + + +@pytest.mark.parametrize( + "column, value", + [ + ("quantity", "two"), + ("quantity", "2.50"), + ("quantity", "2.00"), + ("amount", "5,00"), + ("order_date", "31/02/2026"), + ("order_date", "2026-02-15"), + ("paid", "ja"), + ], +) +def test_a_value_of_the_wrong_type_fails_only_the_type_check_of_its_column(tmp_path, column, value): + run = _test(tmp_path, _with(column, value)) + print(run.pretty()) + assert run.result == ResultEnum.failed + failed = [c for c in run.checks if c.result != ResultEnum.passed] + assert [(c.type, c.field) for c in failed] == [("field_type", column)] + assert failed[0].reason == f"Actual invalid_count({column}) was 1, expected = 0" + + +def test_every_bad_value_is_counted(tmp_path): + rows = _with("quantity", "two") + rows[2] = rows[2].replace("|1|", "|1.5|") + run = _test(tmp_path, rows) + assert _type_check(run, "quantity").reason == "Actual invalid_count(quantity) was 2, expected = 0" + + +def test_an_empty_value_is_missing_not_of_the_wrong_type(tmp_path): + run = _test(tmp_path, _with("quantity", "")) + print(run.pretty()) + assert _type_check(run, "quantity").result == ResultEnum.passed + + +def test_a_bad_value_is_missing_for_the_other_checks_on_its_column(tmp_path): + # A cast would round 3.50 to 4, which fails the maximum of 3; as a missing value, only the type check fails + run = _test( + tmp_path, + _with("quantity", "3.50", row=2), + quantity_options="\n logicalTypeOptions:\n maximum: 3", + ) + print(run.pretty()) + failed = [(c.type, c.field) for c in run.checks if c.result != ResultEnum.passed] + assert failed == [("field_type", "quantity")] + + +def test_a_bad_value_in_a_required_column_is_also_missing(tmp_path): + run = _test(tmp_path, _with("quantity", "two"), quantity_options="\n required: true") + print(run.pretty()) + failed = [(c.type, c.field) for c in run.checks if c.result != ResultEnum.passed] + assert failed == [("field_type", "quantity"), ("field_required", "quantity")] + + +def test_a_missing_column_fails_only_its_presence_check(tmp_path): + paid = HEADER.split("|").index("paid") + data = tmp_path / "orders.csv" + lines = ["|".join(v for i, v in enumerate(r.split("|")) if i != paid) for r in [HEADER, *GOOD_ROWS]] + data.write_text("\n".join(lines) + "\n") + run = DataContract(data_contract_str=_contract(data), inline_references=False).test() + print(run.pretty()) + failed = [(c.type, c.field) for c in run.checks if c.result not in (ResultEnum.passed, ResultEnum.skipped)] + assert failed == [("field_is_present", "paid")] + assert _type_check(run, "paid").result == ResultEnum.skipped + + +def test_the_failed_samples_show_the_bad_value(tmp_path): + run = _test(tmp_path, _with("quantity", "two"), include_failed_samples=True) + assert _type_check(run, "quantity").failedSamples == [{"order_id": "A2", "quantity": "two"}] + + +def test_the_diagnostics_name_the_type_and_format(tmp_path): + run = _test(tmp_path, _with("order_date", "2026-02-15")) + assert _type_check(run, "order_date").diagnostics["constraint"] == {"type": "DATE", "format": "dd/MM/yyyy"} + + +def test_a_text_column_keeps_its_value(tmp_path): + # The quality rule counts code '007', which a column typed by inference would read as 7 + run = _test(tmp_path, GOOD_ROWS) + assert next(c for c in run.checks if c.type == "model_quality_sql").result == ResultEnum.passed + + +def test_a_date_without_a_format_is_iso_8601(tmp_path): + rows = [_with("order_date", "2026-02-0" + str(i + 1), row=i)[i] for i in range(len(GOOD_ROWS))] + rows[1] = GOOD_ROWS[1] + run = _test(tmp_path, rows, order_date_options="") + print(run.pretty()) + assert _type_check(run, "order_date").reason == "Actual invalid_count(order_date) was 1, expected = 0" + + +def test_a_format_that_cannot_be_checked_is_a_warning(tmp_path): + options = "\n logicalTypeOptions:\n format: yyyy-QQQ" + run = _test(tmp_path, GOOD_ROWS, order_date_options=options) + check = _type_check(run, "order_date") + assert check.result == ResultEnum.warning + assert check.reason == "The format 'yyyy-QQQ' cannot be checked; values are read as ISO 8601." + + +@pytest.mark.parametrize( + "pattern, expected", + [ + ("dd/MM/yyyy", "%d/%m/%Y"), + ("yyyy-MM-dd'T'HH:mm:ss.SSSxxx", "%Y-%m-%dT%H:%M:%S.%g%z"), + ("yyyy-MM-dd'T'HH:mm:ssXXX", None), + ("d MMM yyyy", "%-d %b %Y"), + ("hh:mm a", "%I:%M %p"), + ("''yy", "'%y"), + ("yyyy-QQQ", None), + ("'unterminated", None), + ], +) +def test_a_java_date_pattern_as_strptime(pattern, expected): + assert strptime_format(pattern) == expected diff --git a/tests/test_test_metadata_only.py b/tests/test_test_metadata_only.py index a4a5c7608..34d531b12 100644 --- a/tests/test_test_metadata_only.py +++ b/tests/test_test_metadata_only.py @@ -44,7 +44,7 @@ VALUE_CHECK_TYPES = {"field_required", "field_unique", "field_regex", "field_minimum"} -# Delta carries real types, so field_type checks run (CSV skips them, parquet warns). +# Delta carries real types, so field_type checks read the schema (CSV reads the values, parquet warns). DELTA_CONTRACT = """ apiVersion: v3.0.2 kind: DataContract @@ -110,11 +110,12 @@ def test_metadata_only_junit_output(tmp_path): output_path = tmp_path / "TEST-datacontract.xml" write_junit_test_results(run, output_path) testsuite = ET.parse(output_path).getroot() - assert int(testsuite.get("skipped")) == 5 + # The 5 value checks and the type checks of the 2 integer columns, which read the CSV values + assert int(testsuite.get("skipped")) == 7 skipped_messages = [ skipped.get("message") for testcase in testsuite.iter("testcase") for skipped in testcase.iter("skipped") ] - assert len(skipped_messages) == 5 + assert len(skipped_messages) == 7 assert all(message == SKIP_REASON for message in skipped_messages) @@ -127,7 +128,7 @@ def test_metadata_only_cli_option(tmp_path): ) assert result.exit_code == 0 assert "skipped" in result.stdout - assert "(5 skipped)" in result.stdout + assert "(7 skipped)" in result.stdout # Every check here reads row values (rowCount, custom SQL, freshness, retention), @@ -174,6 +175,7 @@ def test_metadata_only_skips_servicelevel_and_custom_sql(): assert run.result == "passed" skipped = {check.type: check.reason for check in run.checks if check.result == "skipped"} assert set(skipped) == { + "field_type", "row_count", "model_quality_sql", "servicelevel_freshness",