Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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 @@ -15,6 +15,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- `datacontract test` matches custom quality check IDs regardless of case

### Fixed
- `datacontract test` on BigQuery: SQL quality rules and custom quality checks can name the table without its dataset again (#1770)

## [1.2.8] - 2026-10-26

### Added
Expand Down
1 change: 1 addition & 0 deletions datacontract/engines/checks/check_spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ class CheckSpec:
query: Optional[str] = None # CUSTOM_SQL (placeholders already substituted)
dialect: Optional[str] = None # CUSTOM_SQL input SQL dialect
diagnostics: Optional[dict] = None # CUSTOM_SQL: reported alongside the measured value
custom_quality_check: Optional[str] = None # CUSTOM_SQL: the check's ID and arguments, as between(min=1, max=100)
warnings: Optional[List[str]] = None # for the run's log

seconds: Optional[int] = None # FRESHNESS / RETENTION threshold in seconds
Expand Down
1 change: 1 addition & 0 deletions datacontract/engines/checks/create_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -1001,6 +1001,7 @@ def _quality_rule_checks(
severity=rule.severity,
dimension=rule.dimension,
diagnostics=instance.diagnostics,
custom_quality_check=instance.call,
warnings=instance.warnings,
)
]
Expand Down
6 changes: 5 additions & 1 deletion datacontract/engines/checks/custom_quality_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,8 @@ class Instance:
# The rule with the check's defaults filled in: expected result and dimension.
quality: DataQuality
name: str
# The check's ID with the rule's arguments, as between(min=1, max=100)
call: str
diagnostics: dict
warnings: list[str]

Expand Down Expand Up @@ -531,6 +533,7 @@ def value_text(value) -> str:
for item in (value if isinstance(value, list) else [value])
]
arguments[argument] = (False, numbers if isinstance(value, list) else numbers[0])
call = f"{check.id}({', '.join(f'{name}={value_text(value)}' for name, (_, value) in arguments.items())})"
if quality.description:
name = quality.description
elif check.description:
Expand All @@ -550,7 +553,7 @@ def fill(match: re.Match) -> str:

name = reference_pattern(TABLE_PLACEHOLDERS + COLUMN_PLACEHOLDERS).sub(fill, check.description)
else:
name = f"{check.id}({', '.join(f'{name}={value_text(value)}' for name, (_, value) in arguments.items())})"
name = call

for argument, (identifier, value) in arguments.items():
if identifier and (not isinstance(value, str) or not value):
Expand Down Expand Up @@ -612,6 +615,7 @@ def fill(match: re.Match) -> str:
arguments=arguments,
quality=quality.model_copy(update=updates),
name=name,
call=call,
diagnostics={
"custom_quality_check": check.id,
"query": query_dialect,
Expand Down
2 changes: 2 additions & 0 deletions datacontract/engines/ibis/connections/connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,8 @@ def _connect_bigquery(ibis, server: Server, config: Config):
if location:
kwargs["location"] = location
con = ibis.bigquery.connect(**kwargs)
# BigQuery requires a dataset on every table name, but the SQL of quality rules may name the table bare.
con.client.default_query_job_config.default_dataset = f"{con.data_project}.{con.dataset}"

kms_key_name = config.get_bigquery_kms_key_name() or _get_custom_property(server, "kmsKeyName")
if kms_key_name:
Expand Down
14 changes: 12 additions & 2 deletions datacontract/engines/ibis/ibis_check_execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,8 +363,18 @@ def _invalid(c, _t=t, _dtype=dtype, _spec=spec, _flag=unconstrained):
except _ColumnNotFound as e:
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}")
# BigQuery spells its message out twice; its first error holds it once
try:
detail = e.errors[0]["message"]
except (AttributeError, LookupError, TypeError):
detail = str(e)
logger.warning("Check '%s' errored: %s", spec.key, detail)
reason = (
f"The custom quality check {spec.custom_quality_check} could not run: {detail}"
if spec.custom_quality_check
else f"Error evaluating check: {detail}"
)
set_result(run, spec.key, ResultEnum.failed, reason)

if agg_exprs:
_run_aggregation(run, t, agg_exprs)
Expand Down
1 change: 1 addition & 0 deletions tests/test_connect_bigquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ def test_billing_project_keeps_the_contract_project_as_the_data_project(env):
assert con.data_project == "my-project"
assert con.billing_project == "my-billing-project"
assert con.dataset == "my_dataset"
assert str(con.client.default_query_job_config.default_dataset) == "my-project.my_dataset"
assert client.call_args.kwargs["credentials"] is impersonated.return_value


Expand Down
29 changes: 29 additions & 0 deletions tests/test_custom_quality_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@

import pytest
import responses
from google.api_core.exceptions import BadRequest
from open_data_contract_standard.model import Server

from datacontract.config import Config
from datacontract.data_contract import DataContract
from datacontract.engines.checks.create_checks import create_checks
from datacontract.engines.checks.custom_quality_check import CustomQualityChecks
from datacontract.engines.ibis import ibis_check_execute
from datacontract.model.run import ResultEnum

CHECKS = "./fixtures/custom-quality-checks/checks"
Expand Down Expand Up @@ -467,6 +469,33 @@ def test_a_value_in_a_string_that_is_not_plain_makes_the_check_invalid(tmp_path)
_unexecuted(spec, "error", "${arguments.x} in queries.postgres is inside a string written as E'...'.")


def test_a_query_the_database_rejects_names_the_check_and_its_arguments(tmp_path):
checks = _check_file(tmp_path, "below", " min:\n", "SELECT COUNT(*) FROM ${table} WHERE email < ${arguments.min}")
run = _test(_contract(schema_quality=_schema_rule(_rule("below", "min: 0"))), checks)

check = next(c for c in run.checks if c.type == "model_quality_custom")
assert check.result == ResultEnum.failed
assert check.reason.startswith("The custom quality check below(min=0) could not run: Binder Error:")


def test_a_bigquery_error_shows_its_message_once(tmp_path, monkeypatch):
message = "Unrecognized name: nope at [1:38]"
error = BadRequest(
f"{message}; reason: invalidQuery, location: query, message: {message}\n\nLocation: US\nJob ID: 1234\n",
errors=[{"reason": "invalidQuery", "location": "query", "message": message}],
)

def reject(con, query, dialect):
raise error

monkeypatch.setattr(ibis_check_execute, "_run_scalar", reject)
checks = _check_file(tmp_path, "below", " min:\n", "SELECT COUNT(*) FROM ${table} WHERE nope < ${arguments.min}")
run = _test(_contract(schema_quality=_schema_rule(_rule("below", "min: 0"))), checks)

check = next(c for c in run.checks if c.type == "model_quality_custom")
assert check.reason == f"The custom quality check below(min=0) could not run: {message}"


def test_a_negative_number_after_a_minus_does_not_start_a_comment(tmp_path):
checks = _check_file(
tmp_path, "check", " x:\n", "SELECT COUNT(*) FROM ${table} WHERE ${column} < 5 -${arguments.x} AND 1 = 1"
Expand Down
Loading