Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added
- `datacontract test`: test Excel workbooks (`format: xlsx`) (new `xlsx` extra) (#1717)

## [1.2.6] - 2026-10-13

### Changed
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,7 @@ A list of available extras:
| DuckDB (local file, CSV import and API response testing) | `pip install datacontract-cli[duckdb]` |
| Exasol | `pip install datacontract-cli[exasol]` |
| Excel | `pip install datacontract-cli[excel]` |
| Excel workbooks (testing) | `pip install datacontract-cli[xlsx]` |
| GCS | `pip install datacontract-cli[gcs]` |
| SAP HANA / Datasphere | `pip install datacontract-cli[hana]` (not part of `all`: `hdbcli` is proprietary) |
| Apache Iceberg (schema import and export, REST catalog testing) | `pip install datacontract-cli[iceberg]` |
Expand Down
26 changes: 24 additions & 2 deletions datacontract/engines/checks/create_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,13 @@
Instance,
instantiate,
placeholder_pattern,
sql_literal,
)
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.native_type import supports_native_type_introspection
from datacontract.export.duckdb_type_converter import convert_to_duckdb_csv_type
from datacontract.model.enum_values import get_enum_values
from datacontract.model.map_type import get_map_key, get_map_value
from datacontract.model.server import get_server_type
Expand Down Expand Up @@ -68,7 +70,7 @@ def is_check_types(server: Optional[Server]) -> bool:
"""Type checks only make sense where the data source carries real types."""
if server is None:
return True
return server.format not in ("json", "csv", "avro", "xml")
return server.format not in ("json", "csv", "avro", "xml", "xlsx")


def to_schema_name(schema_object: SchemaObject, server_type: Optional[str]) -> str:
Expand Down Expand Up @@ -271,7 +273,9 @@ def _to_schema_checks(
properties = schema_object.properties or []
check_types = is_check_types(server)
uses_raw_view = (
server is not None and server_type in _FILE_SERVER_TYPES and server.format in ("csv", "parquet", "json", "xml")
server is not None
and server_type in _FILE_SERVER_TYPES
and server.format in ("csv", "parquet", "json", "xml", "xlsx")
)

# A primary key is both not-null and unique. A composite key is unique as a
Expand All @@ -288,6 +292,7 @@ def _to_schema_checks(
# of nested elements with children. The required top-level properties are still checked for presence.
xml = server is not None and server.format == "xml"
documents = server is not None and server.format in ("json", "xml")
xlsx = server is not None and server.format == "xlsx"
if xml:
# A record element that matches nothing would pass every other check
checks.append(
Expand Down Expand Up @@ -322,6 +327,23 @@ def _to_schema_checks(
)
)

# A cell of the wrong type reads as NULL, so the checks of its column would miss it
if xlsx and not nested and convert_to_duckdb_csv_type(prop) != "VARCHAR":
type_errors = exp.to_identifier(f"{model}__type_errors__", quoted=True).sql(dialect="duckdb")
checks.append(
CheckSpec(
key=f"{model}__{field}__field_type",
category="schema",
type="field_type",
name=f"Check that field {field} has type {prop.logicalType or prop.physicalType}",
model=model,
field=field,
metric=MetricType.CUSTOM_SQL,
query=f"SELECT count(*) FROM {type_errors} WHERE field = {sql_literal(field, 'duckdb')}",
threshold=Threshold(Op.EQ, 0),
)
)

prop_type = _property_type(prop)
implied_type = _implied_type(prop)
own_type = prop
Expand Down
2 changes: 1 addition & 1 deletion datacontract/engines/ibis/connections/connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
logger = logging.getLogger(__name__)

_FILE_SERVER_TYPES = {"s3", "gcs", "azure", "local"}
_SUPPORTED_FILE_FORMATS = {"json", "parquet", "csv", "delta", "xml"}
_SUPPORTED_FILE_FORMATS = {"json", "parquet", "csv", "delta", "xml", "xlsx"}


def _import_ibis():
Expand Down
115 changes: 115 additions & 0 deletions datacontract/engines/ibis/connections/duckdb_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from datacontract.engines.ibis.connections.aws_credentials import resolve_aws_credentials
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.exceptions import DataContractException
from datacontract.model.run import Run

if TYPE_CHECKING:
Expand Down Expand Up @@ -68,6 +69,9 @@ def get_duckdb_connection(
con.load_extension("webbed")
except Exception as e:
raise RuntimeError("Failed to install the 'webbed' DuckDB community extension to read XML files.") from e
if server.format == "xlsx":
check_xlsx_locations(data_contract, path)
_load_extension(con, "excel", "xlsx")

model_paths = _model_paths(data_contract, path, schema_name)
if untrusted_contract and own_connection:
Expand Down Expand Up @@ -122,6 +126,8 @@ def get_duckdb_connection(
con.sql(f"""CREATE VIEW "{model_name}" AS SELECT * FROM delta_scan('{model_path}');""")
elif server.format == "xml":
create_xml_views(con, schema_obj, model_path)
elif server.format == "xlsx":
create_xlsx_views(con, schema_obj, model_path)
table_info = con.sql(f"PRAGMA table_info({_quote(model_name)});").fetchall()
if table_info:
run.log_info(f"DuckDB Table Info: {table_info}")
Expand Down Expand Up @@ -399,6 +405,115 @@ def _xml_name(prop: SchemaProperty) -> str:
return prop.physicalName or prop.name


# Day 0 of Excel's 1900 date system; not 1899-12-31, because Excel counts a 29 February 1900 that never was
_EXCEL_EPOCH = "1899-12-30"
_TEMPORAL_TYPES = ("DATE", "TIMESTAMP", "TIME")
_MILLISECONDS_PER_DAY = 86_400_000


def check_xlsx_locations(data_contract: OpenDataContractStandard, path: str) -> None:
"""Refuse locations read_xlsx would read silently wrong.

read_xlsx reads the first file a glob matches and nothing else, and a model without a physicalName
reads the first sheet, so in a workbook shared by several models that sheet would be tested for each.
"""
if _is_glob(path):
raise DataContractException(
type="xlsx-connection",
name="glob_path",
reason=f"The xlsx path '{path}' is a glob, but Excel workbooks are read one file at a time.",
)
by_workbook: dict[str, list[SchemaObject]] = {}
for schema_obj in data_contract.schema_ or []:
by_workbook.setdefault(_model_path(path, schema_obj.name), []).append(schema_obj)
for workbook, schema_objs in by_workbook.items():
unnamed = [s.name for s in schema_objs if not s.physicalName]
if len(schema_objs) > 1 and unnamed:
raise DataContractException(
type="xlsx-connection",
name="sheet_not_named",
reason=(
f"The models {', '.join(unnamed)} share the workbook '{workbook}' with other models, "
"so each needs the name of its sheet as physicalName."
),
)


def create_xlsx_views(con, schema_obj: SchemaObject, model_path: str):
"""Views over one sheet: the model with the contract's types, its raw text, and its cells of the wrong type.

The sheet is read twice, lined up row by row: typed, for the dates that only the cell format tells
apart from numbers, and as text, for the values that the type read_xlsx infers from the first row
turns into NULL. The checks address a schema by its physical name, quality SQL often by its name,
so both name the model view.
"""
sheet = schema_obj.physicalName
view = sheet or schema_obj.name
options = f"'{_sql_literal(model_path)}', header=true"
Comment thread
jschoedl marked this conversation as resolved.
Resolved
if sheet:
options += f", sheet='{_sql_literal(sheet)}'"
typed = f"read_xlsx({options}, ignore_errors=true)"
text = f"read_xlsx({options}, all_varchar=true)"
cells = f"(SELECT * FROM {typed}) AS t POSITIONAL JOIN (SELECT * FROM {text}) AS r"

# Raw view without the contract's columns to check for absent columns (check_property_is_present)
con.sql(f"CREATE VIEW {_quote(view + '__raw__')} AS SELECT * FROM {text};")

# Like DuckDB's own identifiers, a header answers to its name in any case
headers = {row[0].lower(): row for row in con.sql(f"DESCRIBE SELECT * FROM {typed}").fetchall()}
columns, errors = [], []
for name, sql_type in (to_csv_types(schema_obj) or {}).items():
sql_type = sql_type or "VARCHAR"
if name.lower() not in headers:
columns.append(f"NULL::{sql_type} AS {_quote(name)}")
continue
header, inferred_type = headers[name.lower()][:2]
value = _cell_value(_quote(header), sql_type, inferred_type)
columns.append(f"{value} AS {_quote(name)}")
if sql_type != "VARCHAR":
errors.append(
f"SELECT '{_sql_literal(name)}' AS field, r.{_quote(header)} AS value FROM {cells} "
f"WHERE r.{_quote(header)} IS NOT NULL AND {value} IS NULL"
)
if columns:
con.sql(f"CREATE VIEW {_quote(view)} AS SELECT {', '.join(columns)} FROM {cells};")
else:
con.sql(f"CREATE VIEW {_quote(view)} AS SELECT * FROM {typed};")
if not errors:
errors.append("SELECT NULL::VARCHAR AS field, NULL::VARCHAR AS value WHERE false")
con.sql(f"CREATE VIEW {_quote(view + '__type_errors__')} AS {' UNION ALL '.join(errors)};")
# DuckDB identifiers are case-insensitive, so sheet Orders already answers to orders
if schema_obj.name.lower() != view.lower():
con.sql(f"CREATE VIEW {_quote(schema_obj.name)} AS SELECT * FROM {_quote(view)};")


def _cell_value(column: str, sql_type: str, inferred_type: str) -> str:
"""The value of a cell as `sql_type`, NULL if it has none of that type.

A date read as a number is the Excel serial number of its days, with the time of day as fraction.
"""
typed, text = f"t.{column}", f"r.{column}"
read_as_temporal = inferred_type in _TEMPORAL_TYPES
if sql_type == "VARCHAR":
return f"COALESCE(CAST({typed} AS VARCHAR), {text})" if read_as_temporal else text
if sql_type == "BIGINT":
# TRY_CAST rounds '1.5' to 2, which would hide a fraction in an integer column
number = f"TRY_CAST({text} AS DOUBLE)"
return f"CASE WHEN {number} = floor({number}) THEN TRY_CAST({number} AS BIGINT) END"
if sql_type not in _TEMPORAL_TYPES:
return f"TRY_CAST({text} AS {sql_type})"
serial = f"TRY_CAST({text} AS DOUBLE)"
since_epoch = f"to_milliseconds(CAST(round({serial} * {_MILLISECONDS_PER_DAY}) AS BIGINT))"
from_serial = {
"DATE": f"CAST(DATE '{_EXCEL_EPOCH}' + CAST(floor({serial}) AS INTEGER) AS DATE)",
"TIMESTAMP": f"TIMESTAMP '{_EXCEL_EPOCH}' + {since_epoch}",
"TIME": f"CAST(TIMESTAMP '{_EXCEL_EPOCH}' + {since_epoch} AS TIME)",
}[sql_type]
candidates = [f"TRY_CAST({typed} AS {sql_type})"] if read_as_temporal else []
candidates += [f"TRY_CAST({text} AS {sql_type})", from_serial]
return f"COALESCE({', '.join(candidates)})"


def _quote(name: str) -> str:
return '"' + name.replace('"', '""') + '"'

Expand Down
2 changes: 1 addition & 1 deletion datacontract/export/sodacl_check_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ def check_property_is_present(
uses_raw_view = (
server is not None
and server.type in ["local", "s3", "gcs", "azure"]
and server.format in ["csv", "parquet", "json", "xml"]
and server.format in ["csv", "parquet", "json", "xml", "xlsx"]
)
target = f"{model_name}__raw__" if uses_raw_view else model_name
sodacl_check_dict = {
Expand Down
1 change: 1 addition & 0 deletions docs/docs/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ Available extras:
| DuckDB (local file, CSV import and API response testing) | `pip install datacontract-cli[duckdb]` |
| Exasol | `pip install datacontract-cli[exasol]` |
| Excel | `pip install datacontract-cli[excel]` |
| Excel workbooks (testing) | `pip install datacontract-cli[xlsx]` |
| GCS | `pip install datacontract-cli[gcs]` |
| Apache Hive | `pip install datacontract-cli[hive]` |
| SAP HANA / Datasphere | `pip install datacontract-cli[hana]` (not part of `all`: `hdbcli` is proprietary) |
Expand Down
3 changes: 2 additions & 1 deletion docs/docs/reference/local.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ servers:
- server: local
type: local
path: ./*.parquet # glob patterns and a {model} placeholder are supported
format: parquet # parquet, json, csv, xml, or delta
format: parquet # parquet, json, csv, xml, xlsx, or delta
```

## Data types
Expand Down Expand Up @@ -47,6 +47,7 @@ Type handling depends on the `format` in the `servers` block:
| `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. |
| `xlsx` | Each cell is read as the contract's type of its column, including Excel dates stored as numbers. A cell that has a value of another type fails the type check of its column. |
| `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. |

Expand Down
25 changes: 22 additions & 3 deletions docs/docs/testing/local.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
---
sidebar_position: 17
title: "Local files"
description: "Test local files in Parquet, JSON, CSV, XML, or Delta format — the fastest way to try the CLI, no credentials needed."
description: "Test local files in Parquet, JSON, CSV, XML, Excel, or Delta format — the fastest way to try the CLI, no credentials needed."
---

# <img className="page-icon" src="/img/icons/local.svg" alt="" /> Local files

Test local files in Parquet, JSON, CSV, XML, or Delta format. This is the fastest way to see the CLI in action — no warehouse, no credentials.
Test local files in Parquet, JSON, CSV, XML, Excel, or Delta format. This is the fastest way to see the CLI in action — no warehouse, no credentials.

## 1. Install

Expand Down Expand Up @@ -74,6 +74,25 @@ duplicate_count(status) was 1, expected = 0

The command exits with code `1`, so the same call works as a gate in [CI/CD pipelines](../scheduling/index.md).

## Excel workbooks

Excel workbooks (`format: xlsx`) need `pip install 'datacontract-cli[xlsx]'`. Each schema is one sheet: its `physicalName` is the sheet's name, matched case-sensitively, and a contract with a single schema may leave it out to read the first sheet. The first row of a sheet holds the column names.

```yaml
servers:
- server: local
type: local
path: ./delivery.xlsx
format: xlsx
schema:
- name: orders
physicalName: Orders
- name: country_codes
physicalName: Country Codes
```

The `path` names a single workbook, without a glob. When several schemas share it, each needs its `physicalName`. Formulas are read as the values Excel last stored for them, and the older `.xls` format is not supported.

## XML files

XML documents (`format: xml`) have a guide of their own, from importing their XML Schema to testing nested elements and attributes: **[XML files](./xml.md)**.
Expand All @@ -89,7 +108,7 @@ JSON files (`.json`, `.jsonl`, `.ndjson`) are also validated against a JSON Sche
## Troubleshooting

- **`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.
- **No checks run at all** — the `format` in the `servers` block must be one of `csv`, `json`, `parquet`, `xml`, `xlsx`, 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).

Expand Down
10 changes: 8 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,12 @@ excel = [
"openpyxl>=3.1.5,<4.0.0",
]

# Tests Excel workbooks (`format: xlsx`)
xlsx = [
"datacontract-cli[duckdb]",
"duckdb-extension-excel>=1.5.0,<1.6.0",
]


# The dataframe server type runs against a Spark session the caller passes to
# `DataContract(spark=...)`, so pyspark is necessarily importable in that process
Expand Down Expand Up @@ -266,7 +272,7 @@ dbml = [
]

# duckdb must stay in lockstep with the bundled duckdb-extension-* wheels
# (httpfs/aws/azure) used for air-gapped installs, since those extensions are
# (httpfs/aws/azure/excel) used for air-gapped installs, since those extensions are
# built per duckdb version. Both are pinned to the 1.5.x line.
duckdb = [
"duckdb>=1.5.0,<1.6.0",
Expand Down Expand Up @@ -302,7 +308,7 @@ xml = [
# the `all` meta-extra would pull a proprietary package into a default-ish
# install, so HANA support must be opted into explicitly via `datacontract-cli[hana]`.
all = [
"datacontract-cli[avro,kafka,bigquery,csv,excel,snowflake,postgres,redshift,mysql,dataframe,databricks,sqlserver,s3,gcs,azure,athena,trino,exasol,impala,clickhouse,hive,dbml,duckdb,iceberg,parquet,rdf,api,protobuf,oracle,xml]"
"datacontract-cli[avro,kafka,bigquery,csv,excel,snowflake,postgres,redshift,mysql,dataframe,databricks,sqlserver,s3,gcs,azure,athena,trino,exasol,impala,clickhouse,hive,dbml,duckdb,iceberg,parquet,rdf,api,protobuf,oracle,xml,xlsx]"
]

# for development, we pin all libraries to an exact version
Expand Down
Loading
Loading