Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 that does not match its column's type fails a type check of that column, instead of stopping the run with a conversion error; integers must be whole numbers, and dates, timestamps and times must be in their declared `format`
- `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
Expand Down
5 changes: 4 additions & 1 deletion datacontract/engines/checks/check_spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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,
)
)
20 changes: 20 additions & 0 deletions datacontract/engines/checks/create_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
50 changes: 47 additions & 3 deletions datacontract/engines/ibis/connections/duckdb_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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":
Expand Down Expand Up @@ -256,6 +255,51 @@ 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 as the contract's types in a table built from it.

A value that does not convert to its column's type is NULL in the table, so the other checks on its column
treat it as missing; the type check on the raw view reports it (see csv_values).
"""
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

# Create empty table with contract schema
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)});")

# Insert the columns existing in both the contract and the data, converted to the contract's types
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

Expand Down
114 changes: 114 additions & 0 deletions datacontract/engines/ibis/csv_values.py
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))

Copy link
Copy Markdown
Collaborator

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 junit crashes with not well-formed (invalid token) and writes no file. The cause is strip(): ibis compiles it to TRIM(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:

Suggested change
return text.strip().re_search(r"^[+-]?[0-9]+$").ifelse(text.strip().try_cast(target), ibis.null(target))
return text.re_search(r"^\s*[+-]?[0-9]+\s*$").ifelse(text.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)
21 changes: 16 additions & 5 deletions datacontract/engines/ibis/ibis_check_execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This type check ignores --filter, so a filtered run fails on rows outside the filter: with id,n / 1,2 / 2,x and --filter "id = 1", field_type n fails on row 2. Could it run on the filtered typed table instead?

schema_name=schema_name,
table=f"{model}__raw__" if raw else None,
)
finally:
_maybe_disconnect(con, spark, duckdb_connection)
Expand Down Expand Up @@ -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}")
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/reference/azure.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/reference/gcs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 */}

Expand Down
2 changes: 1 addition & 1 deletion docs/docs/reference/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
Loading
Loading