sqlprove 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sqlprove/schema.py ADDED
@@ -0,0 +1,430 @@
1
+ """Schema definitions, integrity constraints (NOT NULL, UNIQUE, PK, FK), and dbt schema.yml ingestion."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ import json
7
+ from pathlib import Path
8
+ import re
9
+ from typing import Any
10
+
11
+
12
+ def normalize_dtype(dtype: str) -> str:
13
+ """Normalize SQL/schema type names to canonical verifier domains."""
14
+ u = dtype.strip().upper()
15
+ if u in ("INT", "INT64", "INTEGER", "BIGINT", "SMALLINT", "TINYINT", "NUMBER", "NUMERIC"):
16
+ return "INT"
17
+ if u in ("BOOL", "BOOLEAN"):
18
+ return "BOOL"
19
+ if u in ("STRING", "VARCHAR", "TEXT", "CHAR", "NVARCHAR"):
20
+ return "STRING"
21
+ if u == "DATE":
22
+ return "DATE"
23
+ if u in ("TIMESTAMP", "TIMESTAMPTZ", "DATETIME", "TIMESTAMP_NTZ", "TIMESTAMPNTZ", "TIMESTAMP_LTZ", "TIMESTAMPLTZ"):
24
+ return "TIMESTAMP"
25
+ return u
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class ColumnSpec:
30
+ name: str
31
+ dtype: str = "INT"
32
+ nullable: bool = True
33
+
34
+ @property
35
+ def canonical_dtype(self) -> str:
36
+ return normalize_dtype(self.dtype)
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class ForeignKeySpec:
41
+ columns: tuple[str, ...]
42
+ ref_table: str
43
+ ref_columns: tuple[str, ...]
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class TableSpec:
48
+ name: str
49
+ columns: tuple[ColumnSpec, ...]
50
+ unique_keys: tuple[tuple[str, ...], ...] = ()
51
+ primary_key: tuple[str, ...] = ()
52
+ foreign_keys: tuple[ForeignKeySpec, ...] = ()
53
+
54
+ @property
55
+ def column_names(self) -> tuple[str, ...]:
56
+ return tuple(c.name for c in self.columns)
57
+
58
+ def get_column(self, name: str) -> ColumnSpec:
59
+ lower = name.lower()
60
+ for col in self.columns:
61
+ if col.name.lower() == lower:
62
+ return col
63
+ raise KeyError(f"Column '{name}' not found in table '{self.name}'")
64
+
65
+ def has_column(self, name: str) -> bool:
66
+ lower = name.lower()
67
+ return any(c.name.lower() == lower for c in self.columns)
68
+
69
+ def all_unique_constraints(self) -> tuple[tuple[str, ...], ...]:
70
+ constraints = list(self.unique_keys)
71
+ if self.primary_key and self.primary_key not in constraints:
72
+ constraints.append(self.primary_key)
73
+ return tuple(constraints)
74
+
75
+ def is_nullable(self, col_name: str) -> bool:
76
+ lower = col_name.lower()
77
+ if any(pk.lower() == lower for pk in self.primary_key):
78
+ return False
79
+ return self.get_column(col_name).nullable
80
+
81
+ def has_unique_subset(self, cols: set[str]) -> tuple[str, ...] | None:
82
+ """Return a UNIQUE/PK constraint whose columns are all in `cols` (case-insensitive)."""
83
+ cols_l = {c.lower() for c in cols}
84
+ for uk in self.all_unique_constraints():
85
+ if uk and all(c.lower() in cols_l for c in uk):
86
+ return uk
87
+ return None
88
+
89
+ def has_non_null_unique_subset(self, cols: set[str]) -> tuple[str, ...] | None:
90
+ """Return a UNIQUE/PK constraint covered by `cols` where every key column is NOT NULL."""
91
+ cols_l = {c.lower() for c in cols}
92
+ for uk in self.all_unique_constraints():
93
+ if uk and all(c.lower() in cols_l and not self.is_nullable(c) for c in uk):
94
+ return uk
95
+ return None
96
+
97
+
98
+ @dataclass(frozen=True)
99
+ class DbtModelConstraints:
100
+ """Integrity constraints extracted from dbt schema.yml tests for a single model."""
101
+
102
+ model_name: str
103
+ not_null_columns: tuple[str, ...] = ()
104
+ unique_keys: tuple[tuple[str, ...], ...] = ()
105
+ foreign_keys: tuple[ForeignKeySpec, ...] = ()
106
+
107
+
108
+ @dataclass(frozen=True)
109
+ class Schema:
110
+ tables: dict[str, TableSpec] = field(default_factory=dict)
111
+
112
+ def get_table(self, name: str) -> TableSpec:
113
+ lower = name.lower()
114
+ for tname, spec in self.tables.items():
115
+ if tname.lower() == lower:
116
+ return spec
117
+ raise KeyError(f"Table '{name}' not found in schema")
118
+
119
+ def has_table(self, name: str) -> bool:
120
+ lower = name.lower()
121
+ return any(tname.lower() == lower for tname in self.tables)
122
+
123
+ def with_dbt_constraints(self, dbt_constraints: dict[str, DbtModelConstraints]) -> Schema:
124
+ """Overlay dbt schema.yml tests (not_null, unique, relationships) onto existing tables."""
125
+ updated: dict[str, TableSpec] = {}
126
+ by_lower = {k.lower(): v for k, v in dbt_constraints.items()}
127
+ for tname, tspec in self.tables.items():
128
+ dc = by_lower.get(tname.lower())
129
+ if dc is None:
130
+ updated[tname] = tspec
131
+ continue
132
+ nn_set = {c.lower() for c in dc.not_null_columns}
133
+ new_cols = tuple(
134
+ ColumnSpec(
135
+ name=c.name,
136
+ dtype=c.dtype,
137
+ nullable=False if c.name.lower() in nn_set else c.nullable,
138
+ )
139
+ for c in tspec.columns
140
+ )
141
+ existing_uks = {tuple(x.lower() for x in uk) for uk in tspec.unique_keys}
142
+ new_uks = list(tspec.unique_keys)
143
+ for uk in dc.unique_keys:
144
+ if all(tspec.has_column(c) for c in uk):
145
+ uk_l = tuple(c.lower() for c in uk)
146
+ if uk_l not in existing_uks:
147
+ new_uks.append(tuple(tspec.get_column(c).name for c in uk))
148
+ existing_uks.add(uk_l)
149
+ new_fks = list(tspec.foreign_keys)
150
+ existing_fks = {
151
+ (tuple(c.lower() for c in fk.columns), fk.ref_table.lower(), tuple(c.lower() for c in fk.ref_columns))
152
+ for fk in new_fks
153
+ }
154
+ for fk in dc.foreign_keys:
155
+ if all(tspec.has_column(c) for c in fk.columns) and self.has_table(fk.ref_table):
156
+ ref_spec = self.get_table(fk.ref_table)
157
+ if all(ref_spec.has_column(c) for c in fk.ref_columns):
158
+ sig = (
159
+ tuple(c.lower() for c in fk.columns),
160
+ ref_spec.name.lower(),
161
+ tuple(c.lower() for c in fk.ref_columns),
162
+ )
163
+ if sig not in existing_fks:
164
+ new_fks.append(
165
+ ForeignKeySpec(
166
+ columns=tuple(tspec.get_column(c).name for c in fk.columns),
167
+ ref_table=ref_spec.name,
168
+ ref_columns=tuple(ref_spec.get_column(c).name for c in fk.ref_columns),
169
+ )
170
+ )
171
+ existing_fks.add(sig)
172
+ updated[tname] = TableSpec(
173
+ name=tspec.name,
174
+ columns=new_cols,
175
+ unique_keys=tuple(new_uks),
176
+ primary_key=tspec.primary_key,
177
+ foreign_keys=tuple(new_fks),
178
+ )
179
+ return Schema(tables=updated)
180
+
181
+ @classmethod
182
+ def from_dict(cls, raw: dict[str, Any]) -> Schema:
183
+ tables: dict[str, TableSpec] = {}
184
+ for tname, tdef in raw.get("tables", {}).items():
185
+ cols = []
186
+ for cdef in tdef.get("columns", []):
187
+ if isinstance(cdef, str):
188
+ cols.append(ColumnSpec(name=cdef))
189
+ else:
190
+ cols.append(
191
+ ColumnSpec(
192
+ name=cdef["name"],
193
+ dtype=cdef.get("type", "INT"),
194
+ nullable=cdef.get("nullable", True),
195
+ )
196
+ )
197
+ unique_keys = tuple(tuple(uk) for uk in tdef.get("unique", []))
198
+ pk = tuple(tdef.get("primary_key", ()))
199
+ fks = tuple(
200
+ ForeignKeySpec(
201
+ columns=tuple(fk["columns"]),
202
+ ref_table=fk["ref_table"],
203
+ ref_columns=tuple(fk["ref_columns"]),
204
+ )
205
+ for fk in tdef.get("foreign_keys", [])
206
+ )
207
+ tables[tname] = TableSpec(
208
+ name=tname,
209
+ columns=tuple(cols),
210
+ unique_keys=unique_keys,
211
+ primary_key=pk,
212
+ foreign_keys=fks,
213
+ )
214
+ return cls(tables=tables)
215
+
216
+ @classmethod
217
+ def from_json_file(cls, path: str | Path) -> Schema:
218
+ return cls.from_dict(json.loads(Path(path).read_text()))
219
+
220
+
221
+ _REF_IN_YML_RE = re.compile(r"ref\s*\(\s*(?:['\"][^'\"]+['\"]\s*,\s*)?['\"]([^'\"]+)['\"]\s*\)")
222
+ _INLINE_LIST_RE = re.compile(r"\[([^\]]+)\]")
223
+
224
+
225
+ def parse_dbt_schema_yml_text(text: str) -> dict[str, DbtModelConstraints]:
226
+ """Parse dbt schema.yml text (no PyYAML required) for unique/not_null/relationships tests.
227
+
228
+ Supports both dbt classic (`tests:`) and dbt >=1.8 (`data_tests:`) syntax,
229
+ column-level `unique`, `not_null`, `relationships`, and model-level
230
+ `dbt_utils.unique_combination_of_columns`.
231
+ """
232
+ not_null: dict[str, set[str]] = {}
233
+ uniques: dict[str, list[tuple[str, ...]]] = {}
234
+ fks: dict[str, list[ForeignKeySpec]] = {}
235
+
236
+ def ensure(m: str) -> None:
237
+ not_null.setdefault(m, set())
238
+ uniques.setdefault(m, [])
239
+ fks.setdefault(m, [])
240
+
241
+ lines = text.splitlines()
242
+ in_models = False
243
+ model_indent: int | None = None
244
+ col_list_indent: int | None = None
245
+ cur_model: str | None = None
246
+ cur_col: str | None = None
247
+ in_combo_list = False
248
+ combo_indent: int | None = None
249
+ combo_cols: list[str] = []
250
+ in_rel = False
251
+ rel_indent: int | None = None
252
+ rel_to: str | None = None
253
+ rel_field: str | None = None
254
+
255
+ def flush_combo() -> None:
256
+ nonlocal in_combo_list, combo_indent, combo_cols
257
+ if in_combo_list and cur_model and combo_cols:
258
+ t = tuple(combo_cols)
259
+ if t not in uniques[cur_model]:
260
+ uniques[cur_model].append(t)
261
+ in_combo_list = False
262
+ combo_indent = None
263
+ combo_cols = []
264
+
265
+ def flush_rel() -> None:
266
+ nonlocal in_rel, rel_indent, rel_to, rel_field
267
+ if in_rel and cur_model and cur_col and rel_to and rel_field:
268
+ fk = ForeignKeySpec(columns=(cur_col,), ref_table=rel_to, ref_columns=(rel_field,))
269
+ if fk not in fks[cur_model]:
270
+ fks[cur_model].append(fk)
271
+ in_rel = False
272
+ rel_indent = None
273
+ rel_to = None
274
+ rel_field = None
275
+
276
+ for raw_line in lines:
277
+ # Strip YAML comments outside quotes (simple heuristic)
278
+ line = re.sub(r"\s+#.*$", "", raw_line)
279
+ stripped = line.lstrip()
280
+ if not stripped or stripped.startswith("#"):
281
+ continue
282
+ indent = len(line) - len(stripped)
283
+
284
+ if indent == 0 and not stripped.startswith("-"):
285
+ flush_combo()
286
+ flush_rel()
287
+ in_models = stripped.startswith("models:")
288
+ model_indent = None
289
+ col_list_indent = None
290
+ cur_model = None
291
+ cur_col = None
292
+ continue
293
+
294
+ if not in_models:
295
+ continue
296
+
297
+ if in_combo_list and combo_indent is not None and indent <= combo_indent and not stripped.startswith("- "):
298
+ flush_combo()
299
+ if in_rel and rel_indent is not None and indent <= rel_indent:
300
+ flush_rel()
301
+
302
+ # Detect model entry vs column entry
303
+ m_name = re.match(r"^-\s+name\s*:\s*['\"]?([a-zA-Z0-9_]+)['\"]?\s*$", stripped)
304
+ if m_name:
305
+ if model_indent is None or indent <= model_indent:
306
+ flush_combo()
307
+ flush_rel()
308
+ model_indent = indent
309
+ cur_model = m_name.group(1)
310
+ cur_col = None
311
+ col_list_indent = None
312
+ ensure(cur_model)
313
+ continue
314
+ if col_list_indent is None or indent <= col_list_indent:
315
+ flush_combo()
316
+ flush_rel()
317
+ col_list_indent = indent
318
+ cur_col = m_name.group(1)
319
+ continue
320
+
321
+ if cur_model is None:
322
+ continue
323
+
324
+ # Exiting columns section back to model properties
325
+ if col_list_indent is not None and indent < col_list_indent and not stripped.startswith("-"):
326
+ flush_rel()
327
+ cur_col = None
328
+ col_list_indent = None
329
+
330
+ if in_combo_list:
331
+ m_item = re.match(r"^-\s+['\"]?([a-zA-Z0-9_]+)['\"]?\s*$", stripped)
332
+ if m_item:
333
+ combo_cols.append(m_item.group(1))
334
+ continue
335
+ flush_combo()
336
+
337
+ if in_rel:
338
+ m_to = re.match(r"^to\s*:\s*(.+)$", stripped)
339
+ if m_to:
340
+ m_ref = _REF_IN_YML_RE.search(m_to.group(1))
341
+ if m_ref:
342
+ rel_to = m_ref.group(1)
343
+ continue
344
+ m_field = re.match(r"^field\s*:\s*['\"]?([a-zA-Z0-9_]+)['\"]?\s*$", stripped)
345
+ if m_field:
346
+ rel_field = m_field.group(1)
347
+ continue
348
+
349
+ # Model-level unique_combination_of_columns
350
+ if "combination_of_columns" in stripped:
351
+ m_inline = _INLINE_LIST_RE.search(stripped)
352
+ if m_inline:
353
+ cols = [c.strip().strip("'\"") for c in m_inline.group(1).split(",") if c.strip()]
354
+ if cols:
355
+ t = tuple(cols)
356
+ if t not in uniques[cur_model]:
357
+ uniques[cur_model].append(t)
358
+ else:
359
+ in_combo_list = True
360
+ combo_indent = indent
361
+ combo_cols = []
362
+ continue
363
+
364
+ # Column-level tests
365
+ if cur_col is not None:
366
+ if re.match(r"^-\s+not_null\s*$", stripped) or re.match(r"^-\s+not_null\s*:", stripped):
367
+ not_null[cur_model].add(cur_col)
368
+ continue
369
+ if re.match(r"^-\s+unique\s*$", stripped) or re.match(r"^-\s+unique\s*:", stripped):
370
+ t = (cur_col,)
371
+ if t not in uniques[cur_model]:
372
+ uniques[cur_model].append(t)
373
+ continue
374
+ if re.match(r"^-\s+relationships\s*:", stripped):
375
+ flush_rel()
376
+ in_rel = True
377
+ rel_indent = indent
378
+ rel_to = None
379
+ rel_field = None
380
+ continue
381
+
382
+ flush_combo()
383
+ flush_rel()
384
+
385
+ return {
386
+ m: DbtModelConstraints(
387
+ model_name=m,
388
+ not_null_columns=tuple(sorted(not_null[m])),
389
+ unique_keys=tuple(uniques[m]),
390
+ foreign_keys=tuple(fks[m]),
391
+ )
392
+ for m in sorted(not_null.keys())
393
+ if not_null[m] or uniques[m] or fks[m]
394
+ }
395
+
396
+
397
+ def load_dbt_schema_constraints(path: str | Path) -> dict[str, DbtModelConstraints]:
398
+ """Load dbt schema.yml constraints from a file or recursively from a dbt repository."""
399
+ p = Path(path)
400
+ files = [p] if p.is_file() else sorted(list(p.rglob("*.yml")) + list(p.rglob("*.yaml")))
401
+ merged_nn: dict[str, set[str]] = {}
402
+ merged_uk: dict[str, list[tuple[str, ...]]] = {}
403
+ merged_fk: dict[str, list[ForeignKeySpec]] = {}
404
+
405
+ for f in files:
406
+ if p.is_dir():
407
+ parts = [x.lower() for x in f.relative_to(p).parts]
408
+ if any(x in parts for x in ("tests", "integration_tests", "integration_test_project", ".github")):
409
+ continue
410
+ parsed = parse_dbt_schema_yml_text(f.read_text(errors="replace"))
411
+ for m, dc in parsed.items():
412
+ merged_nn.setdefault(m, set()).update(dc.not_null_columns)
413
+ merged_uk.setdefault(m, [])
414
+ for uk in dc.unique_keys:
415
+ if uk not in merged_uk[m]:
416
+ merged_uk[m].append(uk)
417
+ merged_fk.setdefault(m, [])
418
+ for fk in dc.foreign_keys:
419
+ if fk not in merged_fk[m]:
420
+ merged_fk[m].append(fk)
421
+
422
+ return {
423
+ m: DbtModelConstraints(
424
+ model_name=m,
425
+ not_null_columns=tuple(sorted(merged_nn[m])),
426
+ unique_keys=tuple(merged_uk[m]),
427
+ foreign_keys=tuple(merged_fk[m]),
428
+ )
429
+ for m in sorted(merged_nn.keys())
430
+ }