Skip to content

Commit 9493d1b

Browse files
jarichbclaudejschoedl
authored
Test relationships with type foreignKey (#1698)
* Test relationships with type foreignKey (#1691) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016DrmFBwhFWiWT72rvzuEi1 * Document the foreign key check Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016DrmFBwhFWiWT72rvzuEi1 * Give each relationship check a key that names its target A column with two relationships, e.g. line_items.order_id referencing both orders.order_id and invoices.order_id, no longer shares one check key: before, the second check's result overwrote the first and the second had none. The key now includes the referenced schema and columns, using physical names like the other field checks: line_items__order_id__orders__order_id__field_relationship. * Name the relationship check type field_relationships, as dbt sync does dbt sync already reports ODCS relationships as field_relationships; the datacontract test check now uses the same type and key suffix, so both report the same type and dimension (consistency) for a foreign key. * Simplify the relationship validity check and shorten its comments * Test relationship checks with physicalName on both sides * Name the cause when a relationship cannot be checked The warning for an unresolvable relationship now says what is wrong instead of listing every possibility: the contract has no schema X, schema X has no property Y, the reference is not in schema.property form (e.g. a fully qualified schema/<id>/properties/<id> reference), a composite key references more than one schema, or from and to differ in length. * Hint at --schema-name when the referenced model cannot be read With --schema-name, a file server reads only the selected schema, so a relationship to another schema ends as a warning. The warning now says so and suggests testing without --schema-name. * Warn when a relationship's from names another schema Only the declaring schema's own name is stripped from from. Before, any prefix was dropped, so a relationship declared on orders with from: line_items.order_id checked orders.order_id against itself and always passed. It is now a warning: orders has no property line_items.order_id. --------- Co-authored-by: Jarich Braeckevelt <jarichb@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Jakob Schödl <jakob.schoedl@entropy-data.com>
1 parent 991f17c commit 9493d1b

8 files changed

Lines changed: 423 additions & 1 deletion

File tree

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## [Unreleased]
99

10+
### Added
11+
- `datacontract test`: check that foreign keys declared under `relationships` have no values missing from the referenced schema (#1691)
12+
1013
## [1.2.3] - 2026-10-05
1114

1215
### Added

‎datacontract/engines/checks/check_spec.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ class MetricType(str, Enum):
2727
MISSING_COUNT = "missing_count"
2828
DUPLICATE_COUNT = "duplicate_count"
2929
INVALID_COUNT = "invalid_count"
30+
MISSING_REFERENCE_COUNT = "missing_reference_count"
3031
FIELD_PRESENT = "field_present"
3132
FIELD_TYPE = "field_type"
3233
FIELD_PHYSICAL_TYPE = "field_physical_type"
@@ -158,7 +159,10 @@ class CheckSpec:
158159
expected_schema_property: Optional["SchemaProperty"] = None # FIELD_TYPE: structural comparison
159160
expected_physical_type: Optional[str] = None # FIELD_PHYSICAL_TYPE: contract physicalType
160161

161-
columns: Optional[List[str]] = None # DUPLICATE_COUNT across multiple columns
162+
columns: Optional[List[str]] = None # DUPLICATE_COUNT across multiple columns; MISSING_REFERENCE_COUNT keys
163+
164+
referenced_model: Optional[str] = None # MISSING_REFERENCE_COUNT
165+
referenced_columns: Optional[List[str]] = None # MISSING_REFERENCE_COUNT, pairwise with `columns`
162166

163167
query: Optional[str] = None # CUSTOM_SQL (placeholders already substituted)
164168
dialect: Optional[str] = None # CUSTOM_SQL input SQL dialect

‎datacontract/engines/checks/create_checks.py‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,7 @@ def create_checks(
245245
# File-metadata checks are emitted by check_azure_blob_file
246246
continue
247247
checks.extend(_to_schema_checks(schema_obj, server, variables))
248+
checks.extend(_relationship_checks(schema_obj, data_contract.schema_, server))
248249
checks.extend(_to_servicelevel_checks(data_contract, server))
249250
checks = [c for c in checks if c is not None]
250251
# Schema and service level checks cannot declare an ODCS dimension, so fill
@@ -618,6 +619,95 @@ def _to_schema_checks(
618619
return checks
619620

620621

622+
def _relationship_checks(
623+
schema_object: SchemaObject, schemas: List[SchemaObject], server: Optional[Server]
624+
) -> List[CheckSpec]:
625+
"""A foreign key holds when every non-null key in this model exists in the referenced model."""
626+
server_type = get_server_type(server) if server is not None else None
627+
model = to_schema_name(schema_object, server_type)
628+
properties = schema_object.properties or []
629+
declared = [(prop.name, rel) for prop in properties for rel in prop.relationships or []]
630+
declared += [(None, rel) for rel in schema_object.relationships or []]
631+
632+
checks: List[CheckSpec] = []
633+
for source, rel in declared:
634+
if (rel.type or "foreignKey") != "foreignKey":
635+
continue
636+
sources = [source] if source is not None else rel.from_ if isinstance(rel.from_, list) else [rel.from_]
637+
targets = rel.to if isinstance(rel.to, list) else [rel.to]
638+
# `from` may repeat this schema's name; any other prefix is kept, so it matches no property.
639+
source_names = [str(s).removeprefix(f"{schema_object.name}.") for s in sources if s]
640+
parts = [str(t).rsplit(".", 1) for t in targets if t]
641+
target_schema = next((s for s in schemas if parts and len(parts[0]) == 2 and s.name == parts[0][0]), None)
642+
643+
def physical(props, name):
644+
prop = next((p for p in props or [] if p.name == name), None)
645+
return None if prop is None else prop.physicalName or prop.name
646+
647+
columns = [physical(properties, name) for name in source_names]
648+
referenced = [
649+
physical(target_schema.properties, part[-1])
650+
if target_schema is not None and part[0] == target_schema.name
651+
else None
652+
for part in parts
653+
]
654+
label = ", ".join(source_names) or "?"
655+
if not columns or None in columns + referenced or len(referenced) != len(columns):
656+
target_label = ", ".join(str(t) for t in targets)
657+
if not columns or len(parts) != len(columns):
658+
cause = "its from and to lists differ in length"
659+
elif None in columns:
660+
cause = f"{schema_object.name} has no property {source_names[columns.index(None)]}"
661+
elif any(len(part) == 1 for part in parts):
662+
cause = f"{next(part[0] for part in parts if len(part) == 1)} is not a schema.property reference"
663+
elif target_schema is None:
664+
cause = f"the contract has no schema {parts[0][0]}"
665+
elif any(part[0] != target_schema.name for part in parts):
666+
cause = "a composite key must reference a single schema"
667+
else:
668+
cause = f"{target_schema.name} has no property {parts[referenced.index(None)][-1]}"
669+
checks.append(
670+
CheckSpec(
671+
key=f"{model}__{'__'.join(source_names)}__{'__'.join('__'.join(p) for p in parts)}"
672+
"__field_relationships",
673+
category="schema",
674+
type="field_relationships",
675+
name=f"Check that {label} has no values missing from {target_label}",
676+
model=model,
677+
field=source_names[0] if len(source_names) == 1 else None,
678+
metric=MetricType.UNSUPPORTED,
679+
preset_result="warning",
680+
preset_reason=f"The relationship from {label} to {target_label} is not checked: {cause}.",
681+
)
682+
)
683+
continue
684+
685+
referenced_model = to_schema_name(target_schema, server_type)
686+
if len(columns) == 1:
687+
name = f"Check that field {columns[0]} has no values missing from {referenced_model}.{referenced[0]}"
688+
else:
689+
name = (
690+
f"Check that ({', '.join(columns)}) has no values missing from "
691+
f"{referenced_model} ({', '.join(referenced)})"
692+
)
693+
checks.append(
694+
CheckSpec(
695+
key=f"{model}__{'__'.join(columns)}__{referenced_model}__{'__'.join(referenced)}__field_relationships",
696+
category="schema",
697+
type="field_relationships",
698+
name=name,
699+
model=model,
700+
field=columns[0] if len(columns) == 1 else None,
701+
metric=MetricType.MISSING_REFERENCE_COUNT,
702+
threshold=Threshold(Op.EQ, 0),
703+
columns=columns,
704+
referenced_model=referenced_model,
705+
referenced_columns=referenced,
706+
)
707+
)
708+
return checks
709+
710+
621711
# ---------------------------------------------------------------------------
622712
# metric-check builders (preserve legacy keys / types)
623713
# ---------------------------------------------------------------------------

‎datacontract/engines/checks/dimensions.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@
4444
"field_max_items": "conformity",
4545
# the JSON Schema validation checks, which all share the type "schema"
4646
"schema": "conformity",
47+
# consistency — a foreign key points at a row the referenced model does not have
48+
"field_relationships": "consistency",
4749
# the dataset does not conform to the retention period it promises
4850
"servicelevel_retention": "conformity",
4951
# timeliness — the data is not current

‎datacontract/engines/ibis/ibis_check_execute.py‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,7 @@ def execute_ibis_checks(
190190
server,
191191
include_failed_samples,
192192
row_filter=(model_filters or {}).get(model),
193+
schema_name=schema_name,
193194
)
194195
finally:
195196
_maybe_disconnect(con, spark, duckdb_connection)
@@ -224,6 +225,7 @@ def _run_model(
224225
server: Optional[Server] = None,
225226
include_failed_samples: bool = False,
226227
row_filter: Optional[str] = None,
228+
schema_name: str = "all",
227229
):
228230
try:
229231
t = _resolve_table(con, model, _table_database(con, server))
@@ -330,6 +332,8 @@ def _invalid(c, _t=t, _dtype=dtype, _spec=spec, _flag=unconstrained):
330332
named = _count_true(expr).name(spec.key)
331333
elif spec.metric == MetricType.DUPLICATE_COUNT:
332334
_run_duplicate(run, t, unfiltered_t, columns, spec, model_row_count())
335+
elif spec.metric == MetricType.MISSING_REFERENCE_COUNT:
336+
_run_missing_reference(run, con, server, t, columns, spec, schema_name)
333337
elif spec.metric == MetricType.FIELD_PRESENT:
334338
_run_present(run, con, model, columns, schema, spec)
335339
elif spec.metric == MetricType.FIELD_TYPE:
@@ -806,6 +810,32 @@ def _int(value) -> int:
806810
_update_diagnostics(run, spec.key, extra)
807811

808812

813+
def _run_missing_reference(run: Run, con, server, t, columns, spec: CheckSpec, schema_name: str):
814+
"""Count the rows whose foreign key is not null and has no matching row in the referenced model."""
815+
try:
816+
referenced = _resolve_table(con, spec.referenced_model, _table_database(con, server)).view()
817+
except Exception as e:
818+
# With --schema-name, file sources only load the tested model, so the referenced one may be absent.
819+
reason = f"Could not read the referenced model '{spec.referenced_model}': {_first_line(str(e))}"
820+
if schema_name != "all":
821+
reason += (
822+
f". --schema-name {schema_name} reads only that schema from files; "
823+
"test without --schema-name to check this relationship."
824+
)
825+
set_result(run, spec.key, ResultEnum.warning, reason)
826+
return
827+
referenced_columns = {c.lower(): c for c in referenced.columns}
828+
keys = [_resolve_col(columns, c) for c in spec.columns]
829+
rows = t.filter([t[k].notnull() for k in keys])
830+
predicates = [
831+
rows[k] == referenced[_resolve_col(referenced_columns, r)] for k, r in zip(keys, spec.referenced_columns)
832+
]
833+
expr = rows.anti_join(referenced, predicates).count()
834+
_record_sql(run, spec, expr)
835+
value = expr.execute()
836+
_evaluate(run, spec, 0 if value is None else int(value))
837+
838+
809839
def _is_item_duplicate(spec: CheckSpec) -> bool:
810840
return any("[]" in c for c in (spec.columns or [spec.field]) if c)
811841

‎docs/docs/quality-rules/index.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,7 @@ Both select quality rules only — no schema or service level checks run alongsi
149149
| `completeness` | `required` fields, primary key not-null |
150150
| `uniqueness` | `unique` fields, primary key uniqueness (including composite keys) |
151151
| `conformity` | field presence, logical and physical types, nested types, `pattern`, `enum`, length and value bounds, JSON Schema validation, `slaProperties` retention |
152+
| `consistency` | `relationships` foreign keys |
152153
| `timeliness` | `slaProperties` freshness |
153154

154155
## Where quality rules are used

‎docs/docs/schema.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ datacontract test --checks properties datacontract.yaml
2424
| `required` | property | No missing values |
2525
| `unique` | property | No duplicate values |
2626
| `primaryKey` | property | No missing values **and** no duplicates |
27+
| `relationships` (`type: foreignKey`) | property, schema | Every non-null key exists in the referenced schema |
2728
| `logicalTypeOptions.minLength` / `maxLength` | property | Value length within bounds |
2829
| `logicalTypeOptions.minimum` / `maximum` | property | Value within bounds (inclusive) |
2930
| `logicalTypeOptions.exclusiveMinimum` / `exclusiveMaximum` | property | Value within bounds (exclusive) |
@@ -139,6 +140,27 @@ properties:
139140

140141
> Produces: `order_id` not null, `line_number` not null, and `(order_id, line_number)` unique.
141142

143+
## Foreign keys
144+
145+
A `relationships` entry of `type: foreignKey` checks that every non-null value of the referencing column exists in the referenced one. Declare it on the property, with `to`, or on the schema, with `from` and `to` lists for a composite key:
146+
147+
```yaml
148+
schema:
149+
- name: line_items
150+
properties:
151+
- name: order_id
152+
relationships:
153+
- type: foreignKey
154+
to: orders.order_id
155+
- name: shipments
156+
relationships:
157+
- type: foreignKey
158+
from: [shipments.order_id, shipments.line_no]
159+
to: [order_lines.order_id, order_lines.line_no]
160+
```
161+
162+
The referenced schema must be read in the same run. When `--schema-name` selects only the referencing schema of a file server, the check is reported as a warning.
163+
142164
## Value constraints
143165

144166
`logicalTypeOptions` turns into value checks that behave identically on every backend — the CLI compiles each into dialect-specific SQL.

0 commit comments

Comments
 (0)