diff --git a/CHANGELOG.md b/CHANGELOG.md index 25a6bda60..175c89525 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/datacontract/engines/checks/check_spec.py b/datacontract/engines/checks/check_spec.py index 2b0617aaf..d583fdec5 100644 --- a/datacontract/engines/checks/check_spec.py +++ b/datacontract/engines/checks/check_spec.py @@ -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 diff --git a/datacontract/engines/checks/create_checks.py b/datacontract/engines/checks/create_checks.py index c3ff2b097..f63032740 100644 --- a/datacontract/engines/checks/create_checks.py +++ b/datacontract/engines/checks/create_checks.py @@ -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, ) ] diff --git a/datacontract/engines/checks/custom_quality_check.py b/datacontract/engines/checks/custom_quality_check.py index 92898a208..918bce440 100644 --- a/datacontract/engines/checks/custom_quality_check.py +++ b/datacontract/engines/checks/custom_quality_check.py @@ -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] @@ -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: @@ -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): @@ -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, diff --git a/datacontract/engines/ibis/connections/connect.py b/datacontract/engines/ibis/connections/connect.py index 890c6c8cc..4b1b1a0d6 100644 --- a/datacontract/engines/ibis/connections/connect.py +++ b/datacontract/engines/ibis/connections/connect.py @@ -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: diff --git a/datacontract/engines/ibis/ibis_check_execute.py b/datacontract/engines/ibis/ibis_check_execute.py index b92354eb0..427e80d89 100644 --- a/datacontract/engines/ibis/ibis_check_execute.py +++ b/datacontract/engines/ibis/ibis_check_execute.py @@ -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) diff --git a/tests/test_connect_bigquery.py b/tests/test_connect_bigquery.py index a89c3144e..2201a98ec 100644 --- a/tests/test_connect_bigquery.py +++ b/tests/test_connect_bigquery.py @@ -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 diff --git a/tests/test_custom_quality_checks.py b/tests/test_custom_quality_checks.py index cdbb013d4..939b7a98a 100644 --- a/tests/test_custom_quality_checks.py +++ b/tests/test_custom_quality_checks.py @@ -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" @@ -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"