Skip to content

Commit 2035c5e

Browse files
OGsijiclaude
andcommitted
fix: stop skipping table=True SQLModel classes; add mapping.exclude
table=True carries no information about whether a dbt model is expected to exist for a table -- two structurally identical table=True classes can need opposite treatment (a normal dbt-fed table an API also returns directly vs. one populated by a separate pipeline like Kafka). Blanket-skipping every table=True class silently exempted the former case -- likely the more common pattern -- from validation entirely, defeating the tool's purpose. table=True classes are now validated like any other target. The genuine "no source model on purpose" case is now handled via an explicit mapping.exclude list instead of being inferred from table=True. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
1 parent 7b7ef12 commit 2035c5e

8 files changed

Lines changed: 183 additions & 62 deletions

File tree

‎CHANGELOG.md‎

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

88
## [Unreleased]
99

10+
## [1.1.4] - 2026-07-03
11+
12+
### Changed
13+
- **`table=True` SQLModel classes are no longer skipped during extraction.**
14+
Whether a table is meant to come from dbt is business knowledge that can't
15+
be recovered from the Python source — two structurally identical
16+
`table=True` classes can need opposite treatment (one is a normal dbt-fed
17+
table an API also returns directly; another is populated by a separate
18+
pipeline like Kafka and was never meant to have a dbt model). Blanket-
19+
skipping every `table=True` class silently exempted the former case from
20+
validation too, which is likely the more common pattern — defeating the
21+
tool's purpose for it. `table=True` classes are now validated like any
22+
other target.
23+
- Added `mapping.exclude: [<table>, ...]` so the latter case (genuinely no
24+
source model, e.g. Kafka-populated) can be stated explicitly instead of
25+
inferred from `table=True`. Excluded tables are skipped entirely and never
26+
produce a "missing table" issue.
27+
1028
## [1.1.3] - 2026-07-03
1129

1230
Supersedes 1.1.2, which was only ever published to TestPyPI for verification

‎README.md‎

Lines changed: 40 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -112,10 +112,10 @@ avoids the sharp edges:
112112
- Target name doesn't match the dbt model by convention (renamed/prefixed)
113113
→ add an entry under `mapping.tables` in `.retl-validator.yml` (see
114114
[When do I need `mapping`?](#when-do-i-need-mapping)).
115-
- A `SQLModel(table=True)` class with no corresponding dbt model at all
116-
(e.g. populated by a separate streaming pipeline) → this should be
117-
skipped automatically; if it's still flagged, please
118-
[open an issue](https://github.com/OGsiji/data-contract-validator/issues).
115+
- A table that's genuinely populated by something other than dbt (e.g. a
116+
separate streaming pipeline) and has no source model on purpose → add
117+
it to `mapping.exclude`. `table=True` alone is **not** used to infer
118+
this automatically — see [FastAPI side](#fastapi-side) for why.
119119

120120
8. **For accurate type-checking** (not just column-presence checks), run
121121
`dbt docs generate` before `validate` so it picks up `catalog.json` (Tier 1,
@@ -158,8 +158,18 @@ CI job.
158158
### FastAPI side
159159

160160
Pydantic / SQLModel classes are parsed from source with Python's `ast` (no
161-
imports executed). `Optional[...]` controls whether a field is required;
162-
`table=True` SQLModel classes (DB tables, not API contracts) are skipped.
161+
imports executed). `Optional[...]` controls whether a field is required.
162+
An explicit `__tablename__` is used as the table name when present;
163+
otherwise the class name is converted to `snake_case`.
164+
165+
`table=True` SQLModel classes are validated the same as any other class —
166+
they are **not** skipped. Whether a table is meant to come from dbt is
167+
business knowledge that isn't recoverable from the Python source: two
168+
structurally identical `table=True` classes can need opposite treatment (one
169+
is a normal dbt-fed table your API also returns directly; another is
170+
populated by a Kafka stream and was never meant to have a dbt model). Use
171+
`mapping.exclude` to state the latter case explicitly rather than relying on
172+
`table=True` to imply it.
163173

164174
## 🚦 What gets flagged
165175

@@ -214,6 +224,10 @@ mapping:
214224
user_analytics:
215225
# target column : source column
216226
userId: user_id
227+
# Target tables with no source model on purpose (e.g. Kafka-populated,
228+
# not dbt) -- see "When do I need mapping?" below.
229+
exclude:
230+
- feed_interaction
217231

218232
validation:
219233
fail_on: ["missing_tables", "missing_required_columns"]
@@ -244,8 +258,26 @@ Most of the time you don't. Names are matched automatically across:
244258
- **plural ↔ singular** — dbt's plural `users` matches Pydantic's `User` (→ `user`)
245259
with no config (and it won't over-match — `address` is never confused with `addres`).
246260

247-
Reach for `mapping` only when a model or column is named so differently that
248-
convention can't bridge it (e.g. Pydantic `user_id` ↔ dbt `customer_identifier`).
261+
Reach for `mapping.tables` / `mapping.columns` only when a model or column is
262+
named so differently that convention can't bridge it (e.g. Pydantic
263+
`user_id` ↔ dbt `customer_identifier`).
264+
265+
`mapping.exclude` is different — it's not about renamed models, it's for a
266+
target table that has **no source model on purpose**, because it's
267+
populated by something other than dbt (a Kafka stream, a cron job, etc.).
268+
This can't be inferred from the code (a `table=True` SQLModel class looks
269+
identical whether or not dbt is supposed to feed it), so it has to be a
270+
deliberate, human-stated exception:
271+
272+
```yaml
273+
mapping:
274+
exclude:
275+
- feed_interaction
276+
- affiliate_reward
277+
```
278+
279+
Anything not listed is validated normally — including `table=True` classes,
280+
which are treated the same as any other target and are not silently skipped.
249281

250282
## 🐍 Python API
251283

‎data_contract_validator/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
your data pipelines and API frameworks.
66
"""
77

8-
__version__ = "1.1.3"
8+
__version__ = "1.1.4"
99
__author__ = "Ogunniran Siji"
1010
__email__ = "ogunniransiji@gmail.com"
1111

‎data_contract_validator/core/validator.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,16 @@ def __init__(
3737
{
3838
"tables": {"<target_table>": "<source_table>"},
3939
"columns": {"<target_table>": {"<target_col>": "<source_col>"}},
40+
"exclude": ["<target_table>", ...],
4041
}
4142
4243
Keys are matched case/style-insensitively (userId == user_id).
44+
45+
``exclude`` is for targets that are known to have no source
46+
model on purpose (e.g. a table populated by a separate
47+
streaming pipeline instead of dbt) -- that's business
48+
knowledge no extractor can infer from the code, so it must
49+
be stated explicitly rather than guessed.
4350
"""
4451
self.source_extractor = source_extractor
4552
self.target_extractor = target_extractor
@@ -57,6 +64,10 @@ def __init__(
5764
}
5865
for table, cols in (mapping.get("columns") or {}).items()
5966
}
67+
# normalized set of target tables to skip entirely
68+
self.excluded_tables: set = {
69+
normalize_name(t) for t in (mapping.get("exclude") or [])
70+
}
6071

6172
def validate(self) -> ValidationResult:
6273
"""
@@ -88,6 +99,9 @@ def validate(self) -> ValidationResult:
8899
# Validate each target schema against source
89100
print("🔍 Validating schema compatibility...")
90101
for table_name, target_schema in target_schemas.items():
102+
if normalize_name(table_name) in self.excluded_tables:
103+
print(f" ⏭️ Skipping excluded table: {table_name}")
104+
continue
91105
self._validate_table(table_name, target_schema, source_by_norm)
92106

93107
# Determine success

‎data_contract_validator/extractors/fastapi.py‎

Lines changed: 11 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -405,11 +405,17 @@ def _is_pydantic_model(self, node: ast.ClassDef) -> bool:
405405
def _analyze_pydantic_class(
406406
self, node: ast.ClassDef, file_source: str = None
407407
) -> Optional[Schema]:
408-
"""Analyze a Pydantic class to extract schema."""
409-
# Skip SQLModel tables (database models, not API models)
410-
if self._is_sqlmodel_table(node):
411-
return None
412-
408+
"""Analyze a Pydantic class to extract schema.
409+
410+
`table=True` SQLModel classes are intentionally NOT skipped here:
411+
whether a table is expected to come from dbt is business knowledge
412+
that isn't recoverable from the Python source (two structurally
413+
identical `table=True` classes can have opposite answers), so it
414+
can't be inferred from the class definition. Tables that genuinely
415+
have no corresponding dbt model (e.g. Kafka-populated) are excluded
416+
via the explicit `mapping.exclude` config instead -- see
417+
ContractValidator.
418+
"""
413419
# An explicit __tablename__ is the source of truth for the target name
414420
# (e.g. `class VideoViewed(SQLModel): __tablename__ = "int_unified_video_viewed"`).
415421
# Only the class-name heuristic is used when it's absent.
@@ -451,31 +457,6 @@ def _analyze_pydantic_class(
451457
metadata={"confidence": "high", "complete": True},
452458
)
453459

454-
def _is_sqlmodel_table(self, node: ast.ClassDef) -> bool:
455-
"""Check if this is a SQLModel table (database model, not API model)."""
456-
# `class Foo(SQLModel, table=True):` puts `table=True` on the class
457-
# definition's own keywords, not nested inside a base -- SQLModel here
458-
# is a plain ast.Name, not an ast.Call. Check both forms so the more
459-
# common `keywords` case isn't silently missed.
460-
for keyword in node.keywords:
461-
if (
462-
keyword.arg == "table"
463-
and isinstance(keyword.value, ast.Constant)
464-
and keyword.value.value is True
465-
):
466-
return True
467-
468-
for base in node.bases:
469-
if isinstance(base, ast.Call):
470-
for keyword in base.keywords:
471-
if (
472-
keyword.arg == "table"
473-
and isinstance(keyword.value, ast.Constant)
474-
and keyword.value.value is True
475-
):
476-
return True
477-
return False
478-
479460
def _get_tablename(self, node: ast.ClassDef) -> Optional[str]:
480461
"""Return the value of an explicit `__tablename__ = "..."`, if present."""
481462
for item in node.body:

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
44

55
[project]
66
name = "data-contract-validator"
7-
version = "1.1.3"
7+
version = "1.1.4"
88
description = "Validate data contracts between dbt models and FastAPI/Pydantic APIs with accurate, low-false-positive schema checks"
99
readme = "README.md"
1010
license = {text = "MIT"}

‎tests/test_core/test_validator.py‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,3 +315,82 @@ def test_column_mapping_resolves_renamed_columns(self):
315315

316316
assert result.success is True
317317
assert len(result.critical_issues) == 0
318+
319+
def test_exclude_skips_a_target_table_with_no_source_model(self):
320+
"""A target table that's genuinely populated by something other than
321+
dbt (e.g. a Kafka stream) has no source model on purpose -- that's
322+
not inferable from the code, so it must be excluded explicitly
323+
rather than producing a permanent, unfixable 'missing table'."""
324+
source_extractor, target_extractor = self._extractors(
325+
{}, # no source models at all
326+
{
327+
"feed_interaction": Schema(
328+
name="feed_interaction",
329+
columns=[{"name": "id", "type": "str", "required": True}],
330+
source="test",
331+
)
332+
},
333+
)
334+
335+
# Without exclude: no matching source model -> missing table (critical).
336+
no_exclude = ContractValidator(source_extractor, target_extractor).validate()
337+
assert no_exclude.success is False
338+
assert no_exclude.critical_issues[0].category == "Missing Table"
339+
340+
# With exclude: the table is skipped entirely, no issue raised.
341+
mapping = {"exclude": ["feed_interaction"]}
342+
excluded = ContractValidator(
343+
source_extractor, target_extractor, mapping=mapping
344+
).validate()
345+
assert excluded.success is True
346+
assert len(excluded.issues) == 0
347+
348+
def test_exclude_does_not_affect_other_tables(self):
349+
"""Excluding one table must not suppress real issues on others."""
350+
source_extractor, target_extractor = self._extractors(
351+
{},
352+
{
353+
"feed_interaction": Schema(
354+
name="feed_interaction",
355+
columns=[{"name": "id", "type": "str", "required": True}],
356+
source="test",
357+
),
358+
"orders": Schema(
359+
name="orders",
360+
columns=[{"name": "order_id", "type": "str", "required": True}],
361+
source="test",
362+
),
363+
},
364+
)
365+
366+
mapping = {"exclude": ["feed_interaction"]}
367+
result = ContractValidator(
368+
source_extractor, target_extractor, mapping=mapping
369+
).validate()
370+
371+
assert result.success is False
372+
assert len(result.critical_issues) == 1
373+
assert result.critical_issues[0].table == "orders"
374+
375+
def test_exclude_is_normalized_like_table_mapping(self):
376+
"""Exclude entries should match case/style-insensitively, same as
377+
`mapping.tables`, so 'FeedInteraction' and 'feed_interaction' are
378+
treated as the same table."""
379+
source_extractor, target_extractor = self._extractors(
380+
{},
381+
{
382+
"feed_interaction": Schema(
383+
name="feed_interaction",
384+
columns=[{"name": "id", "type": "str", "required": True}],
385+
source="test",
386+
)
387+
},
388+
)
389+
390+
mapping = {"exclude": ["FeedInteraction"]}
391+
result = ContractValidator(
392+
source_extractor, target_extractor, mapping=mapping
393+
).validate()
394+
395+
assert result.success is True
396+
assert len(result.issues) == 0

‎tests/test_extractors/test_fastapi.py‎

Lines changed: 19 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -82,32 +82,29 @@ class VideoViewed(SQLModel):
8282
assert "int_unified_video_viewed" in schemas
8383
assert "video_viewed" not in schemas
8484

85-
def test_table_true_via_class_keyword_is_skipped(self):
86-
"""`class Foo(SQLModel, table=True):` puts `table=True` in the class
87-
definition's keywords, not nested inside a Call base -- this is the
88-
standard SQLModel syntax and must be recognized as a DB table (and
89-
therefore skipped), not evaluated as a required API contract."""
85+
def test_table_true_classes_are_extracted_not_skipped(self):
86+
"""`table=True` alone carries no information about whether a source
87+
(dbt) model is expected to exist for a table -- two structurally
88+
identical `table=True` classes can need opposite treatment (one
89+
genuinely has no dbt model because it's Kafka-populated, another is
90+
a normal dbt-fed table someone also uses as their API response
91+
shape). So `table=True` must NOT cause a class to be skipped at
92+
extraction time; the extractor has no way to make that call
93+
correctly. Tables that truly have no source model are excluded via
94+
the validator's `mapping.exclude`, an explicit human decision, not
95+
an inferred one."""
9096
content = """
9197
from sqlmodel import SQLModel, Field
9298
93-
class FeedInteraction(SQLModel, table=True):
94-
id: str = Field(primary_key=True)
95-
user_id: str
96-
"""
97-
extractor = FastAPIExtractor(content, source="test")
98-
schemas = extractor.extract_schemas()
99-
100-
assert schemas == {}
101-
102-
def test_table_true_without_tablename_still_skipped(self):
103-
"""Skip logic must not depend on __tablename__ being present."""
104-
content = """
105-
from sqlmodel import SQLModel
106-
107-
class AffiliateReward(SQLModel, table=True):
108-
reward_id: str
99+
class CreatorAudienceDemographics(SQLModel, table=True):
100+
__tablename__ = "creator_audience_demographics"
101+
creator_id: str = Field(primary_key=True)
102+
fan_count: int
109103
"""
110104
extractor = FastAPIExtractor(content, source="test")
111105
schemas = extractor.extract_schemas()
112106

113-
assert schemas == {}
107+
assert "creator_audience_demographics" in schemas
108+
columns = [c["name"] for c in schemas["creator_audience_demographics"].columns]
109+
assert "creator_id" in columns
110+
assert "fan_count" in columns

0 commit comments

Comments
 (0)