From c612f3599c1d2842ae216ad97d756600405e233e Mon Sep 17 00:00:00 2001 From: Nicole Hazel Date: Fri, 9 Oct 2026 14:57:08 -0700 Subject: [PATCH 1/6] Test Excel workbooks with format: xlsx Read each sheet through DuckDB's excel extension, one sheet per schema named by its physicalName. The sheet is read typed and as text, lined up row by row, so Excel dates arrive as dates and a cell of the wrong type fails its column's type check. Closes #1717 Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 1 + README.md | 1 + datacontract/engines/checks/create_checks.py | 26 ++- .../engines/ibis/connections/connect.py | 2 +- .../ibis/connections/duckdb_connection.py | 115 +++++++++++ datacontract/export/sodacl_check_builder.py | 2 +- docs/docs/installation.md | 1 + docs/docs/reference/local.md | 3 +- docs/docs/schema.md | 2 +- docs/docs/testing/local.md | 25 ++- pyproject.toml | 10 +- tests/fixtures/xlsx/datacontract.yaml | 50 +++++ tests/fixtures/xlsx/delivery.xlsx | Bin 0 -> 5669 bytes .../fixtures/xlsx/helper/create_xlsx_files.py | 29 +++ tests/test_test_local_xlsx.py | 186 ++++++++++++++++++ tests/test_test_s3_xlsx.py | 43 ++++ 16 files changed, 485 insertions(+), 11 deletions(-) create mode 100644 tests/fixtures/xlsx/datacontract.yaml create mode 100644 tests/fixtures/xlsx/delivery.xlsx create mode 100644 tests/fixtures/xlsx/helper/create_xlsx_files.py create mode 100644 tests/test_test_local_xlsx.py create mode 100644 tests/test_test_s3_xlsx.py diff --git a/CHANGELOG.md b/CHANGELOG.md index b9f10ec86..e2da9197a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - `datacontract edit`: enable the editor's AI assistant via `DATACONTRACT_EDITOR_AI_*` environment variables (endpoint, API key, model, provider, auth header) - `datacontract test`: check constraints and quality rules on nested properties on Athena and Trino servers +- `datacontract test`: test Excel workbooks (`format: xlsx`) (new `xlsx` extra) (#1717) ### Fixed - `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) diff --git a/README.md b/README.md index 0bb154baf..fd7342934 100644 --- a/README.md +++ b/README.md @@ -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]` | diff --git a/datacontract/engines/checks/create_checks.py b/datacontract/engines/checks/create_checks.py index f60ffb1ec..4efef87fe 100644 --- a/datacontract/engines/checks/create_checks.py +++ b/datacontract/engines/checks/create_checks.py @@ -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.server import get_server_type @@ -67,7 +69,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: @@ -297,7 +299,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 @@ -314,6 +318,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( @@ -347,6 +352,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), + ) + ) + # The raw view cannot provide nested type checks declared_base = normalize_type_name(prop.logicalType or prop.physicalType) nested_checks_possible = ( diff --git a/datacontract/engines/ibis/connections/connect.py b/datacontract/engines/ibis/connections/connect.py index 2b5b2d163..524a55eae 100644 --- a/datacontract/engines/ibis/connections/connect.py +++ b/datacontract/engines/ibis/connections/connect.py @@ -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(): diff --git a/datacontract/engines/ibis/connections/duckdb_connection.py b/datacontract/engines/ibis/connections/duckdb_connection.py index 1767d5dbe..bceb5984d 100644 --- a/datacontract/engines/ibis/connections/duckdb_connection.py +++ b/datacontract/engines/ibis/connections/duckdb_connection.py @@ -8,6 +8,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: @@ -66,6 +67,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: @@ -120,6 +124,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}") @@ -397,6 +403,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" + 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('"', '""') + '"' diff --git a/datacontract/export/sodacl_check_builder.py b/datacontract/export/sodacl_check_builder.py index 9ba7c9dca..3d67eeac9 100644 --- a/datacontract/export/sodacl_check_builder.py +++ b/datacontract/export/sodacl_check_builder.py @@ -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 = { diff --git a/docs/docs/installation.md b/docs/docs/installation.md index a97a38ffa..ab605871a 100644 --- a/docs/docs/installation.md +++ b/docs/docs/installation.md @@ -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) | diff --git a/docs/docs/reference/local.md b/docs/docs/reference/local.md index 77a63b8bd..e828b9309 100644 --- a/docs/docs/reference/local.md +++ b/docs/docs/reference/local.md @@ -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 @@ -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. | diff --git a/docs/docs/schema.md b/docs/docs/schema.md index 62462df8e..31b45690b 100644 --- a/docs/docs/schema.md +++ b/docs/docs/schema.md @@ -98,7 +98,7 @@ A property can declare a portable `logicalType`, a native `physicalType`, or bot - **`physicalType`** is compared against the column's real declared type read from the platform catalog. This applies on the nine backends with catalog introspection: Snowflake, BigQuery, Databricks, Postgres, Redshift, SQL Server, Oracle, Trino, and Athena. It takes precedence over `logicalType`. - **`logicalType`** is used everywhere else, and as the fallback when the native type cannot be read. Both the declared and the actual type are normalized to an ODCS category before comparison, so `integer` and `number` are mutually compatible. -On every backend except `csv`, `json`, `parquet` and `xml` files, a property with a complex `logicalType` (`object`, `array` or `map`) gets a **nested type check** covering the full declared structure. +On every backend except `csv`, `json`, `parquet`, `xml` and `xlsx` files, a property with a complex `logicalType` (`object`, `array` or `map`) gets a **nested type check** covering the full declared structure. ODCS v3.2.0 `logicalType: vector` requires `logicalTypeOptions.dimensions` to be a positive integer. Lint rejects a missing options block as well as missing or invalid dimensions, including in nested definitions. diff --git a/docs/docs/testing/local.md b/docs/docs/testing/local.md index f7acbe51f..07c78418b 100644 --- a/docs/docs/testing/local.md +++ b/docs/docs/testing/local.md @@ -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." --- # 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 @@ -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)**. @@ -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). diff --git a/pyproject.toml b/pyproject.toml index d9e979fbd..c53ed5adf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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 @@ -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", @@ -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 diff --git a/tests/fixtures/xlsx/datacontract.yaml b/tests/fixtures/xlsx/datacontract.yaml new file mode 100644 index 000000000..19138ac17 --- /dev/null +++ b/tests/fixtures/xlsx/datacontract.yaml @@ -0,0 +1,50 @@ +version: 1.0.0 +kind: DataContract +apiVersion: v3.2.0 +id: delivery-xlsx +name: delivery +status: draft +servers: +- server: local + type: local + path: fixtures/xlsx/delivery.xlsx + format: xlsx +schema: +- name: orders + physicalName: Orders + logicalType: object + properties: + - name: order_id + logicalType: string + required: true + unique: true + - name: customer_id + logicalType: string + logicalTypeOptions: + pattern: ^[0-9]{5}$ + - name: order_date + logicalType: date + required: true + - name: order_timestamp + logicalType: timestamp + - name: amount + logicalType: number + logicalTypeOptions: + minimum: 0 + - name: quantity + logicalType: integer + - name: paid + logicalType: boolean + - name: note + logicalType: string +- name: country_codes + physicalName: Country Codes + logicalType: object + properties: + - name: code + logicalType: string + required: true + logicalTypeOptions: + maxLength: 2 + - name: name + logicalType: string diff --git a/tests/fixtures/xlsx/delivery.xlsx b/tests/fixtures/xlsx/delivery.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..f92256f9068d73376248b3c3c62b1983e72dd419 GIT binary patch literal 5669 zcmZ`-1yodR*B!b$9a_2@89D@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7~p+Kh_`#T4z7)r_9_ znD{;JlO|(&flq0#+I0uze(ta`ZVnyUyKr8ghke?S4sMxNyOgZd~GzZxN4BMGYN{ zlTTwx@;SuH&}a(!R=X0f;RBe{1eG`nC`D8w&sgAa(u|{eQ05ZTM}o=ns4mar=L< zj&2j&ep&c0K_D&WFM@x4b-2xPd-D6kl7RiMEWhT!+bp-IlmD_HfpCAZ{Fzm5LvQzo zKhQ(`zq-Y3;O%<*2e^PJzla3>vj*G--!2?~z#0fo69N7oW#l%`?M?ZIN1PY{_?IoJ Xse*=Z2mt_W#0P??T46tpLco6jYp>qf literal 0 HcmV?d00001 diff --git a/tests/fixtures/xlsx/helper/create_xlsx_files.py b/tests/fixtures/xlsx/helper/create_xlsx_files.py new file mode 100644 index 000000000..ab6f3b4e7 --- /dev/null +++ b/tests/fixtures/xlsx/helper/create_xlsx_files.py @@ -0,0 +1,29 @@ +"""Writes ../delivery.xlsx, kept as a script so the workbook can be reviewed and rebuilt.""" + +import datetime as dt +from pathlib import Path + +from openpyxl import Workbook + +ORDERS = [ + ["order_id", "customer_id", "order_date", "order_timestamp", "amount", "quantity", "paid", "note"], + ["A1", "00123", dt.date(2026, 1, 2), dt.datetime(2026, 1, 2, 13, 45), 10.5, 2, True, "first"], + ["A2", "00456", dt.date(2026, 1, 3), dt.datetime(2026, 1, 3, 8, 0), 7, 1, False, None], + ["A3", "00789", dt.date(2026, 1, 5), dt.datetime(2026, 1, 5, 0, 0), 3.25, 5, True, "third"], +] +COUNTRY_CODES = [["code", "name"], ["DE", "Germany"], ["FR", "France"]] + +workbook = Workbook() +workbook.remove(workbook.active) +for title, rows in {"Orders": ORDERS, "Country Codes": COUNTRY_CODES}.items(): + sheet = workbook.create_sheet(title) + for row in rows: + sheet.append(row) + # Excel stores dates as numbers; only the format makes them dates + for cells in sheet.iter_rows(min_row=2): + for cell in cells: + if isinstance(cell.value, dt.datetime): + cell.number_format = "yyyy-mm-dd hh:mm" + elif isinstance(cell.value, dt.date): + cell.number_format = "yyyy-mm-dd" +workbook.save(Path(__file__).parent.parent / "delivery.xlsx") diff --git a/tests/test_test_local_xlsx.py b/tests/test_test_local_xlsx.py new file mode 100644 index 000000000..9897d411d --- /dev/null +++ b/tests/test_test_local_xlsx.py @@ -0,0 +1,186 @@ +"""`datacontract test` against Excel workbooks, read through DuckDB's excel extension.""" + +import datetime as dt +import shutil +from pathlib import Path + +import pytest +import yaml +from openpyxl import load_workbook +from typer.testing import CliRunner + +from datacontract.cli import app +from datacontract.data_contract import DataContract +from datacontract.engines.ibis.connections.duckdb_connection import get_duckdb_connection +from datacontract.lint import resolve +from datacontract.model.run import Run + +CONTRACT = "fixtures/xlsx/datacontract.yaml" +WORKBOOK = "fixtures/xlsx/delivery.xlsx" + + +def contract(path: str, models: list[str] | None = None, **order_changes) -> str: + data = yaml.safe_load(Path(CONTRACT).read_text()) + data["servers"][0]["path"] = path + if models is not None: + data["schema"] = [s for s in data["schema"] if s["name"] in models] + data["schema"][0].update(order_changes) + return yaml.safe_dump(data) + + +def edited(tmp_path: Path, sheet_title: str = "Orders", **cells) -> str: + """The fixture workbook with cells of its Orders sheet changed, e.g. E3="n/a".""" + workbook = load_workbook(WORKBOOK) + orders = workbook["Orders"] + for cell, value in cells.items(): + orders[cell] = value + if isinstance(value, dt.date): + orders[cell].number_format = "yyyy-mm-dd" + orders.title = sheet_title + workbook.save(tmp_path / "delivery.xlsx") + return str(tmp_path / "delivery.xlsx") + + +def failed(run) -> dict: + return {check.name: check.reason for check in run.checks if check.result is None or check.result.value != "passed"} + + +def rows(contract_str: str, view: str) -> list[tuple]: + data_contract = resolve.resolve_data_contract(data_contract_str=contract_str) + con = get_duckdb_connection(data_contract, data_contract.servers[0], Run.create_run()) + return con.sql(f'SELECT * FROM "{view}"').fetchall() + + +def test_cli(): + result = CliRunner().invoke(app, ["test", CONTRACT]) + + assert result.exit_code == 0, result.output + + +def test_both_sheets_of_a_workbook_are_checked(): + run = DataContract(data_contract_file=CONTRACT).test() + + assert run.result == "passed", [(c.name, c.reason) for c in run.checks if c.result != "passed"] + assert {"Orders", "Country Codes"} <= {check.model for check in run.checks} + + +def test_cells_are_read_with_the_types_of_the_contract(): + first, second, _ = rows(contract(WORKBOOK), "orders") + + assert first == ("A1", "00123", dt.date(2026, 1, 2), dt.datetime(2026, 1, 2, 13, 45), 10.5, 2, True, "first") + assert second[-1] is None + + +def test_a_model_without_physical_name_reads_the_first_sheet(): + data = yaml.safe_load(contract(WORKBOOK, models=["orders"])) + del data["schema"][0]["physicalName"] + + run = DataContract(data_contract_str=yaml.safe_dump(data)).test() + + assert run.result == "passed", failed(run) + + +def test_models_that_share_a_workbook_must_name_their_sheet(): + data = yaml.safe_load(contract(WORKBOOK)) + del data["schema"][1]["physicalName"] + + run = DataContract(data_contract_str=yaml.safe_dump(data)).test() + + assert run.result != "passed" + assert any("physicalName" in (c.reason or "") and "country_codes" in (c.reason or "") for c in run.checks) + + +def test_a_glob_path_is_refused(tmp_path: Path): + for name in ("a.xlsx", "b.xlsx"): + shutil.copy(WORKBOOK, tmp_path / name) + + run = DataContract(data_contract_str=contract(str(tmp_path / "*.xlsx"), models=["orders"])).test() + + assert run.result != "passed" + assert any("glob" in (c.reason or "").lower() for c in run.checks) + + +def test_a_sheet_that_is_not_in_the_workbook_fails(): + run = DataContract(data_contract_str=contract(WORKBOOK, physicalName="Shipments")).test() + + assert run.result != "passed" + assert any("Shipments" in (c.reason or "") for c in run.checks) + + +def test_a_value_of_the_wrong_type_fails_only_its_column(tmp_path: Path): + run = DataContract(data_contract_str=contract(edited(tmp_path, E3="n/a"), models=["orders"])).test() + + assert failed(run) == {"Check that field amount has type number": "Actual custom_sql(amount) was 1, expected = 0"} + + +def test_a_fraction_in_an_integer_column_is_not_rounded(tmp_path: Path): + run = DataContract(data_contract_str=contract(edited(tmp_path, F3=1.5), models=["orders"])).test() + + assert failed(run) == { + "Check that field quantity has type integer": "Actual custom_sql(quantity) was 1, expected = 0" + } + + +def test_a_header_is_matched_regardless_of_case(tmp_path: Path): + contract_str = contract(edited(tmp_path, A1="ORDER_ID"), models=["orders"]) + + assert [row[0] for row in rows(contract_str, "orders")] == ["A1", "A2", "A3"] + + +def test_a_date_that_is_not_a_date_fails_its_column(tmp_path: Path): + run = DataContract(data_contract_str=contract(edited(tmp_path, C3="soon"), models=["orders"])).test() + + # as for JSON, the value reads as NULL, so the column being required reports it too + assert failed(run) == { + "Check that field order_date has type date": "Actual custom_sql(order_date) was 1, expected = 0", + "Check that field order_date has no missing values": "Actual missing_count(order_date) was 1, expected = 0", + } + + +def test_dates_below_a_first_cell_that_is_not_a_date_are_still_dates(tmp_path: Path): + # DuckDB infers the type of a column from its first row, so these dates arrive as Excel serial numbers + contract_str = contract(edited(tmp_path, D2="unknown"), models=["orders"]) + + assert [row[3] for row in rows(contract_str, "orders")] == [ + None, + dt.datetime(2026, 1, 3, 8, 0), + dt.datetime(2026, 1, 5, 0, 0), + ] + + +def test_a_date_in_a_text_column_reads_as_the_date_not_its_serial_number(tmp_path: Path): + contract_str = contract(edited(tmp_path, H2=dt.date(2026, 2, 1)), models=["orders"]) + + assert [row[7] for row in rows(contract_str, "orders")] == ["2026-02-01", None, "third"] + + +def test_a_column_that_is_not_in_the_sheet_fails_its_presence_check(tmp_path: Path): + run = DataContract(data_contract_str=contract(edited(tmp_path, F1="qty"), models=["orders"])).test() + + assert "Check that field 'quantity' is present" in failed(run) + + +def test_a_nested_property_gets_no_type_check(): + data = yaml.safe_load(contract(WORKBOOK, models=["orders"])) + data["schema"][0]["properties"].append( + {"name": "meta", "logicalType": "object", "properties": [{"name": "source", "logicalType": "integer"}]} + ) + + run = DataContract(data_contract_str=yaml.safe_dump(data)).test() + + # a sheet has no nested columns, so such a check could only ever pass + assert not any("meta.source" in check.name and "has type" in check.name for check in run.checks) + + +@pytest.mark.parametrize("sheet", ["Bob's Orders", 'Orders"; DROP TABLE x; --']) +def test_a_sheet_name_is_not_run_as_sql(tmp_path: Path, sheet): + run = DataContract(data_contract_str=contract(edited(tmp_path, sheet_title=sheet), physicalName=sheet)).test() + + assert run.result == "passed", failed(run) + + +def test_an_untrusted_contract_reads_its_workbook(): + # The sandbox of an untrusted contract stops DuckDB from loading extensions on demand + run = DataContract(data_contract_file=CONTRACT, untrusted_contract=True, inline_references=False).test() + + assert run.result == "passed", failed(run) diff --git a/tests/test_test_s3_xlsx.py b/tests/test_test_s3_xlsx.py new file mode 100644 index 000000000..bd946f928 --- /dev/null +++ b/tests/test_test_s3_xlsx.py @@ -0,0 +1,43 @@ +from pathlib import Path + +import pytest +import yaml +from testcontainers.minio import MinioContainer + +from datacontract.data_contract import DataContract + +CONTRACT = "fixtures/xlsx/datacontract.yaml" +WORKBOOK = "fixtures/xlsx/delivery.xlsx" +bucket_name = "test-bucket" +s3_access_key = "test-access" +s3_secret_access_key = "test-secret" + + +@pytest.fixture(scope="session") +def minio_container(): + with MinioContainer( + image="cgr.dev/chainguard/minio", access_key=s3_access_key, secret_key=s3_secret_access_key + ) as minio_container: + yield minio_container + + +def test_test_s3_xlsx(minio_container, monkeypatch): + monkeypatch.setenv("DATACONTRACT_S3_ACCESS_KEY_ID", s3_access_key) + monkeypatch.setenv("DATACONTRACT_S3_SECRET_ACCESS_KEY", s3_secret_access_key) + minio_container.get_client().make_bucket(bucket_name) + minio_container.get_client().fput_object(bucket_name, "delivery.xlsx", WORKBOOK) + data = yaml.safe_load(Path(CONTRACT).read_text()) + data["servers"] = [ + { + "server": "s3", + "type": "s3", + "location": f"s3://{bucket_name}/delivery.xlsx", + "endpointUrl": f"http://{minio_container.get_container_host_ip()}:{minio_container.get_exposed_port(9000)}", + "format": "xlsx", + } + ] + + run = DataContract(data_contract_str=yaml.safe_dump(data)).test() + + assert run.result == "passed", [(c.name, c.reason) for c in run.checks if c.result != "passed"] + assert {"Orders", "Country Codes"} <= {check.model for check in run.checks} From f91aed96007f07dc9a71aa73391a2ea8c34b20de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakob=20Sch=C3=B6dl?= Date: Fri, 16 Oct 2026 18:38:55 +0200 Subject: [PATCH 2/6] Word the unnamed-sheet error for a single model too The error for models that share a workbook without a physicalName now says "The model(s) ...", so it no longer reads as plural when only one model is missing its sheet name. --- datacontract/engines/ibis/connections/duckdb_connection.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/datacontract/engines/ibis/connections/duckdb_connection.py b/datacontract/engines/ibis/connections/duckdb_connection.py index 1a103b60a..394a4149b 100644 --- a/datacontract/engines/ibis/connections/duckdb_connection.py +++ b/datacontract/engines/ibis/connections/duckdb_connection.py @@ -433,7 +433,7 @@ def check_xlsx_locations(data_contract: OpenDataContractStandard, path: str) -> type="xlsx-connection", name="sheet_not_named", reason=( - f"The models {', '.join(unnamed)} share the workbook '{workbook}' with other models, " + f"The model(s) {', '.join(unnamed)} share the workbook '{workbook}' with other models, " "so each needs the name of its sheet as physicalName." ), ) From d7bf82e35636c6e8ed5a0ba5869f0a687e3476a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakob=20Sch=C3=B6dl?= Date: Fri, 16 Oct 2026 18:38:55 +0200 Subject: [PATCH 3/6] Drop the xlsx CLI test that repeats the workbook test --- tests/test_test_local_xlsx.py | 8 -------- 1 file changed, 8 deletions(-) diff --git a/tests/test_test_local_xlsx.py b/tests/test_test_local_xlsx.py index 9897d411d..7a50c8721 100644 --- a/tests/test_test_local_xlsx.py +++ b/tests/test_test_local_xlsx.py @@ -7,9 +7,7 @@ import pytest import yaml from openpyxl import load_workbook -from typer.testing import CliRunner -from datacontract.cli import app from datacontract.data_contract import DataContract from datacontract.engines.ibis.connections.duckdb_connection import get_duckdb_connection from datacontract.lint import resolve @@ -51,12 +49,6 @@ def rows(contract_str: str, view: str) -> list[tuple]: return con.sql(f'SELECT * FROM "{view}"').fetchall() -def test_cli(): - result = CliRunner().invoke(app, ["test", CONTRACT]) - - assert result.exit_code == 0, result.output - - def test_both_sheets_of_a_workbook_are_checked(): run = DataContract(data_contract_file=CONTRACT).test() From f1c222fd9bba610308a69c30537a98f7f11e6b50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakob=20Sch=C3=B6dl?= Date: Fri, 16 Oct 2026 18:38:55 +0200 Subject: [PATCH 4/6] Clarify the Excel extras and empty header cells in the docs The installation table now labels the excel extra as import/export, next to xlsx for testing, and the Excel workbooks section notes that a sheet is cropped at its first empty header column. --- docs/docs/installation.md | 2 +- docs/docs/testing/local.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/docs/installation.md b/docs/docs/installation.md index ab605871a..ff634418d 100644 --- a/docs/docs/installation.md +++ b/docs/docs/installation.md @@ -134,7 +134,7 @@ Available extras: | DBML | `pip install datacontract-cli[dbml]` | | 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 (import / export) | `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]` | diff --git a/docs/docs/testing/local.md b/docs/docs/testing/local.md index 07c78418b..db5286d71 100644 --- a/docs/docs/testing/local.md +++ b/docs/docs/testing/local.md @@ -76,7 +76,7 @@ The command exits with code `1`, so the same call works as a gate in [CI/CD pipe ## 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. +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. Note that the table is cropped at the first empty header column. ```yaml servers: From 173910c5d4de9ee2d75322ddb0386441fdcbfe07 Mon Sep 17 00:00:00 2001 From: Nicole Hazel Date: Fri, 16 Oct 2026 18:56:49 -0700 Subject: [PATCH 5/6] Check the rows below an empty row of a sheet read_xlsx stops at the first empty row by default, so rows below a blank spacer row went unchecked. Read the whole sheet and skip the rows that are empty in every column. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../engines/ibis/connections/duckdb_connection.py | 9 ++++++--- docs/docs/testing/local.md | 2 +- tests/test_test_local_xlsx.py | 12 ++++++++++++ 3 files changed, 19 insertions(+), 4 deletions(-) diff --git a/datacontract/engines/ibis/connections/duckdb_connection.py b/datacontract/engines/ibis/connections/duckdb_connection.py index 394a4149b..6d9308eb7 100644 --- a/datacontract/engines/ibis/connections/duckdb_connection.py +++ b/datacontract/engines/ibis/connections/duckdb_connection.py @@ -449,7 +449,8 @@ def create_xlsx_views(con, schema_obj: SchemaObject, model_path: str): """ sheet = schema_obj.physicalName view = sheet or schema_obj.name - options = f"'{_sql_literal(model_path)}', header=true" + # Without stop_at_empty=false, read_xlsx stops at the first empty row and the rows below go unchecked + options = f"'{_sql_literal(model_path)}', header=true, stop_at_empty=false" if sheet: options += f", sheet='{_sql_literal(sheet)}'" typed = f"read_xlsx({options}, ignore_errors=true)" @@ -461,6 +462,8 @@ def create_xlsx_views(con, schema_obj: SchemaObject, model_path: str): # 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()} + # A row that is empty in every column is a spacer, not a record + not_empty = f"coalesce({', '.join(f'r.{_quote(row[0])}' for row in headers.values())}) IS NOT NULL" columns, errors = [], [] for name, sql_type in (to_csv_types(schema_obj) or {}).items(): sql_type = sql_type or "VARCHAR" @@ -476,9 +479,9 @@ def create_xlsx_views(con, schema_obj: SchemaObject, model_path: str): 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};") + con.sql(f"CREATE VIEW {_quote(view)} AS SELECT {', '.join(columns)} FROM {cells} WHERE {not_empty};") else: - con.sql(f"CREATE VIEW {_quote(view)} AS SELECT * FROM {typed};") + con.sql(f"CREATE VIEW {_quote(view)} AS SELECT t.* FROM {cells} WHERE {not_empty};") 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)};") diff --git a/docs/docs/testing/local.md b/docs/docs/testing/local.md index db5286d71..b5e766ab1 100644 --- a/docs/docs/testing/local.md +++ b/docs/docs/testing/local.md @@ -76,7 +76,7 @@ The command exits with code `1`, so the same call works as a gate in [CI/CD pipe ## 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. Note that the table is cropped at the first empty header column. +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. Note that the table is cropped at the first empty header column. Rows that are empty in every column are skipped. ```yaml servers: diff --git a/tests/test_test_local_xlsx.py b/tests/test_test_local_xlsx.py index 7a50c8721..fb667f62e 100644 --- a/tests/test_test_local_xlsx.py +++ b/tests/test_test_local_xlsx.py @@ -105,6 +105,18 @@ def test_a_value_of_the_wrong_type_fails_only_its_column(tmp_path: Path): assert failed(run) == {"Check that field amount has type number": "Actual custom_sql(amount) was 1, expected = 0"} +def test_rows_below_an_empty_row_are_checked(tmp_path: Path): + workbook = load_workbook(WORKBOOK) + workbook["Orders"].insert_rows(3) + workbook["Orders"]["E5"] = "n/a" + workbook.save(tmp_path / "delivery.xlsx") + + run = DataContract(data_contract_str=contract(str(tmp_path / "delivery.xlsx"), models=["orders"])).test() + + # the empty row itself is skipped, or its order_id and order_date would be missing + assert failed(run) == {"Check that field amount has type number": "Actual custom_sql(amount) was 1, expected = 0"} + + def test_a_fraction_in_an_integer_column_is_not_rounded(tmp_path: Path): run = DataContract(data_contract_str=contract(edited(tmp_path, F3=1.5), models=["orders"])).test() From 224405cb779d976a2576f17afd4fce14e6699c6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakob=20Sch=C3=B6dl?= Date: Mon, 19 Oct 2026 16:26:56 +0200 Subject: [PATCH 6/6] Describe which columns of an Excel sheet are read --- docs/docs/testing/local.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/testing/local.md b/docs/docs/testing/local.md index b5e766ab1..17c0c7b09 100644 --- a/docs/docs/testing/local.md +++ b/docs/docs/testing/local.md @@ -76,7 +76,7 @@ The command exits with code `1`, so the same call works as a gate in [CI/CD pipe ## 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. Note that the table is cropped at the first empty header column. Rows that are empty in every column are skipped. +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. Columns before the first and after the last header cell are not read, and a column with an empty header cell between them gets a generated name. Rows that are empty in every column are skipped. ```yaml servers: