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/__init__.py +28 -0
- sqlprove/algebra.py +1302 -0
- sqlprove/audit.py +347 -0
- sqlprove/cli.py +281 -0
- sqlprove/corpus.py +448 -0
- sqlprove/cost.py +92 -0
- sqlprove/dbt_manifest.py +582 -0
- sqlprove/fuzzer.py +312 -0
- sqlprove/prover.py +1568 -0
- sqlprove/rewrites.py +819 -0
- sqlprove/schema.py +430 -0
- sqlprove/targets.py +482 -0
- sqlprove-0.1.0.dist-info/LICENSE +21 -0
- sqlprove-0.1.0.dist-info/METADATA +99 -0
- sqlprove-0.1.0.dist-info/RECORD +18 -0
- sqlprove-0.1.0.dist-info/WHEEL +5 -0
- sqlprove-0.1.0.dist-info/entry_points.txt +2 -0
- sqlprove-0.1.0.dist-info/top_level.txt +1 -0
sqlprove/dbt_manifest.py
ADDED
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
"""dbt compile (`target/manifest.json`) ingestion, constraint extraction, and sound cross-model view unfolding."""
|
|
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
|
+
import sqlglot
|
|
12
|
+
from sqlglot import exp
|
|
13
|
+
|
|
14
|
+
from sqlprove.schema import (
|
|
15
|
+
ColumnSpec,
|
|
16
|
+
DbtModelConstraints,
|
|
17
|
+
ForeignKeySpec,
|
|
18
|
+
Schema,
|
|
19
|
+
TableSpec,
|
|
20
|
+
_REF_IN_YML_RE,
|
|
21
|
+
normalize_dtype,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
_VOLATILE_FUNCS = frozenset(
|
|
25
|
+
{
|
|
26
|
+
"rand",
|
|
27
|
+
"random",
|
|
28
|
+
"uuid",
|
|
29
|
+
"uuid_string",
|
|
30
|
+
"generate_uuid",
|
|
31
|
+
"current_timestamp",
|
|
32
|
+
"current_date",
|
|
33
|
+
"current_time",
|
|
34
|
+
"now",
|
|
35
|
+
"getdate",
|
|
36
|
+
"sysdate",
|
|
37
|
+
}
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _norm_ident(s: str) -> str:
|
|
42
|
+
return s.strip().strip('"`[]').lower()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _norm_relation_name(rel: str | None) -> str | None:
|
|
46
|
+
if not rel:
|
|
47
|
+
return None
|
|
48
|
+
parts = [_norm_ident(p) for p in rel.split(".") if p.strip()]
|
|
49
|
+
return ".".join(parts) if parts else None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _table_ref_key(tbl: exp.Table) -> tuple[str | None, str]:
|
|
53
|
+
"""Return (qualified_key_or_none, unqualified_name_lower) for a sqlglot Table node."""
|
|
54
|
+
parts = [_norm_ident(p) for p in (tbl.catalog, tbl.db, tbl.name) if p]
|
|
55
|
+
qual = ".".join(parts) if len(parts) > 1 else None
|
|
56
|
+
return qual, _norm_ident(tbl.name)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _has_volatile_func(ast: exp.Expression) -> bool:
|
|
60
|
+
for fn in ast.find_all(exp.Func):
|
|
61
|
+
fname = type(fn).__name__.lower()
|
|
62
|
+
sql_head = fn.sql().split("(")[0].strip().lower()
|
|
63
|
+
if fname in ("rand", "random", "currenttimestamp", "currentdate", "currenttime", "uuid"):
|
|
64
|
+
return True
|
|
65
|
+
if sql_head in _VOLATILE_FUNCS:
|
|
66
|
+
return True
|
|
67
|
+
return False
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass(frozen=True)
|
|
71
|
+
class DbtManifestModel:
|
|
72
|
+
unique_id: str
|
|
73
|
+
name: str
|
|
74
|
+
alias: str
|
|
75
|
+
resource_type: str # "model" | "seed" | "source"
|
|
76
|
+
materialized: str # "view" | "ephemeral" | "table" | "incremental" | "source" | "seed"
|
|
77
|
+
relation_name: str | None
|
|
78
|
+
original_file_path: str
|
|
79
|
+
compiled_sql: str | None
|
|
80
|
+
raw_sql: str | None
|
|
81
|
+
depends_on: tuple[str, ...] = ()
|
|
82
|
+
columns: dict[str, str] = field(default_factory=dict) # col_name -> canonical dtype
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass(frozen=True)
|
|
86
|
+
class DbtManifest:
|
|
87
|
+
models: dict[str, DbtManifestModel] # unique_id -> model
|
|
88
|
+
relations: dict[str, DbtManifestModel] # unique_id -> model/seed/source
|
|
89
|
+
constraints: dict[str, DbtModelConstraints] # model_name_lower -> constraints
|
|
90
|
+
adapter_type: str | None = None
|
|
91
|
+
|
|
92
|
+
def find_relation_for_table(self, tbl: exp.Table) -> DbtManifestModel | None:
|
|
93
|
+
"""Resolve an AST Table reference to a manifest node (exact relation_name first, then alias/name)."""
|
|
94
|
+
qual, unqual = _table_ref_key(tbl)
|
|
95
|
+
if qual:
|
|
96
|
+
for rel in self.relations.values():
|
|
97
|
+
rn = _norm_relation_name(rel.relation_name)
|
|
98
|
+
if rn and (rn == qual or rn.endswith("." + qual)):
|
|
99
|
+
return rel
|
|
100
|
+
matches = [
|
|
101
|
+
rel
|
|
102
|
+
for rel in self.relations.values()
|
|
103
|
+
if rel.alias.lower() == unqual or rel.name.lower() == unqual
|
|
104
|
+
]
|
|
105
|
+
if len(matches) == 1:
|
|
106
|
+
return matches[0]
|
|
107
|
+
return None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _extract_model_constraints(
|
|
111
|
+
manifest_raw: dict[str, Any],
|
|
112
|
+
id_to_model: dict[str, DbtManifestModel],
|
|
113
|
+
) -> dict[str, DbtModelConstraints]:
|
|
114
|
+
"""Extract unconditional NOT NULL, UNIQUE, PK, and FK constraints from dbt tests & model contracts.
|
|
115
|
+
|
|
116
|
+
Fail-closed soundness rules:
|
|
117
|
+
- Skip any test with a `config.where` filter (partial test does NOT hold table-wide).
|
|
118
|
+
- Skip any test with `config.severity == 'warn'` (non-enforced warning).
|
|
119
|
+
"""
|
|
120
|
+
not_null: dict[str, set[str]] = {}
|
|
121
|
+
uniques: dict[str, list[tuple[str, ...]]] = {}
|
|
122
|
+
fks: dict[str, list[ForeignKeySpec]] = {}
|
|
123
|
+
|
|
124
|
+
def ensure(m_lower: str) -> None:
|
|
125
|
+
not_null.setdefault(m_lower, set())
|
|
126
|
+
uniques.setdefault(m_lower, [])
|
|
127
|
+
fks.setdefault(m_lower, [])
|
|
128
|
+
|
|
129
|
+
# 1. Model-level & column-level dbt contracts (`constraints:` in dbt >=1.5)
|
|
130
|
+
for node in manifest_raw.get("nodes", {}).values():
|
|
131
|
+
if node.get("resource_type") != "model":
|
|
132
|
+
continue
|
|
133
|
+
m_name = str(node.get("name", "")).lower()
|
|
134
|
+
m_alias = str(node.get("alias") or m_name).lower()
|
|
135
|
+
for key in {m_name, m_alias}:
|
|
136
|
+
if key:
|
|
137
|
+
ensure(key)
|
|
138
|
+
|
|
139
|
+
for cname, cinfo in (node.get("columns") or {}).items():
|
|
140
|
+
for con in cinfo.get("constraints") or []:
|
|
141
|
+
ctype = str(con.get("type", "")).lower()
|
|
142
|
+
if ctype == "not_null":
|
|
143
|
+
for key in {m_name, m_alias}:
|
|
144
|
+
not_null[key].add(cname)
|
|
145
|
+
elif ctype in ("unique", "primary_key"):
|
|
146
|
+
for key in {m_name, m_alias}:
|
|
147
|
+
if (cname,) not in uniques[key]:
|
|
148
|
+
uniques[key].append((cname,))
|
|
149
|
+
if ctype == "primary_key":
|
|
150
|
+
not_null[key].add(cname)
|
|
151
|
+
|
|
152
|
+
for con in node.get("constraints") or []:
|
|
153
|
+
ctype = str(con.get("type", "")).lower()
|
|
154
|
+
cols = tuple(str(c) for c in (con.get("columns") or []) if c)
|
|
155
|
+
if not cols:
|
|
156
|
+
continue
|
|
157
|
+
if ctype in ("unique", "primary_key"):
|
|
158
|
+
for key in {m_name, m_alias}:
|
|
159
|
+
if cols not in uniques[key]:
|
|
160
|
+
uniques[key].append(cols)
|
|
161
|
+
if ctype == "primary_key":
|
|
162
|
+
not_null[key].update(cols)
|
|
163
|
+
|
|
164
|
+
# 2. Generic test nodes (`resource_type == 'test'`)
|
|
165
|
+
for node in manifest_raw.get("nodes", {}).values():
|
|
166
|
+
if node.get("resource_type") != "test":
|
|
167
|
+
continue
|
|
168
|
+
cfg = node.get("config") or {}
|
|
169
|
+
if cfg.get("where"):
|
|
170
|
+
continue
|
|
171
|
+
if str(cfg.get("severity", "error")).strip().lower() == "warn":
|
|
172
|
+
continue
|
|
173
|
+
|
|
174
|
+
meta = node.get("test_metadata") or {}
|
|
175
|
+
tname = str(meta.get("name", "")).strip().lower()
|
|
176
|
+
kwargs = meta.get("kwargs") or {}
|
|
177
|
+
|
|
178
|
+
deps = list((node.get("depends_on") or {}).get("nodes") or [])
|
|
179
|
+
attached = node.get("attached_node")
|
|
180
|
+
if not attached and deps:
|
|
181
|
+
attached = deps[0]
|
|
182
|
+
if not attached or attached not in id_to_model:
|
|
183
|
+
continue
|
|
184
|
+
|
|
185
|
+
target_model = id_to_model[attached]
|
|
186
|
+
keys = {target_model.name.lower(), target_model.alias.lower()}
|
|
187
|
+
for k in keys:
|
|
188
|
+
ensure(k)
|
|
189
|
+
|
|
190
|
+
col_name = node.get("column_name") or kwargs.get("column_name")
|
|
191
|
+
if isinstance(col_name, str):
|
|
192
|
+
col_name = col_name.strip().strip('"`')
|
|
193
|
+
|
|
194
|
+
if tname == "not_null" and col_name:
|
|
195
|
+
for k in keys:
|
|
196
|
+
not_null[k].add(col_name)
|
|
197
|
+
elif tname == "unique" and col_name:
|
|
198
|
+
for k in keys:
|
|
199
|
+
if (col_name,) not in uniques[k]:
|
|
200
|
+
uniques[k].append((col_name,))
|
|
201
|
+
elif tname == "unique_combination_of_columns":
|
|
202
|
+
combo = kwargs.get("combination_of_columns") or []
|
|
203
|
+
cols = tuple(str(c).strip().strip('"`') for c in combo if str(c).strip())
|
|
204
|
+
if cols:
|
|
205
|
+
for k in keys:
|
|
206
|
+
if cols not in uniques[k]:
|
|
207
|
+
uniques[k].append(cols)
|
|
208
|
+
elif tname == "relationships" and col_name:
|
|
209
|
+
field_name = kwargs.get("field")
|
|
210
|
+
if not isinstance(field_name, str) or not field_name.strip():
|
|
211
|
+
continue
|
|
212
|
+
field_name = field_name.strip().strip('"`')
|
|
213
|
+
|
|
214
|
+
ref_model_name: str | None = None
|
|
215
|
+
# Prefer depends_on second model/source node if present
|
|
216
|
+
other_deps = [d for d in deps if d != attached and d in id_to_model]
|
|
217
|
+
if len(other_deps) == 1:
|
|
218
|
+
ref_model_name = id_to_model[other_deps[0]].alias
|
|
219
|
+
else:
|
|
220
|
+
to_val = str(kwargs.get("to") or "")
|
|
221
|
+
m_ref = _REF_IN_YML_RE.search(to_val)
|
|
222
|
+
if m_ref:
|
|
223
|
+
ref_model_name = m_ref.group(1)
|
|
224
|
+
if ref_model_name:
|
|
225
|
+
fk = ForeignKeySpec(
|
|
226
|
+
columns=(col_name,),
|
|
227
|
+
ref_table=ref_model_name,
|
|
228
|
+
ref_columns=(field_name,),
|
|
229
|
+
)
|
|
230
|
+
for k in keys:
|
|
231
|
+
if fk not in fks[k]:
|
|
232
|
+
fks[k].append(fk)
|
|
233
|
+
|
|
234
|
+
out: dict[str, DbtModelConstraints] = {}
|
|
235
|
+
for k in sorted(not_null.keys()):
|
|
236
|
+
if not_null[k] or uniques[k] or fks[k]:
|
|
237
|
+
out[k] = DbtModelConstraints(
|
|
238
|
+
model_name=k,
|
|
239
|
+
not_null_columns=tuple(sorted(not_null[k])),
|
|
240
|
+
unique_keys=tuple(uniques[k]),
|
|
241
|
+
foreign_keys=tuple(fks[k]),
|
|
242
|
+
)
|
|
243
|
+
return out
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def load_dbt_manifest(path: str | Path) -> DbtManifest:
|
|
247
|
+
"""Load a dbt `target/manifest.json` file (supports dbt v1.3–v1.9+ / schema v8–v12)."""
|
|
248
|
+
raw = json.loads(Path(path).read_text(encoding="utf-8"))
|
|
249
|
+
adapter_type = (raw.get("metadata") or {}).get("adapter_type")
|
|
250
|
+
|
|
251
|
+
models: dict[str, DbtManifestModel] = {}
|
|
252
|
+
relations: dict[str, DbtManifestModel] = {}
|
|
253
|
+
|
|
254
|
+
for uid, node in (raw.get("nodes") or {}).items():
|
|
255
|
+
rtype = str(node.get("resource_type", "")).lower()
|
|
256
|
+
if rtype not in ("model", "seed"):
|
|
257
|
+
continue
|
|
258
|
+
cfg = node.get("config") or {}
|
|
259
|
+
mat = str(cfg.get("materialized") or ("seed" if rtype == "seed" else "view")).lower()
|
|
260
|
+
name = str(node.get("name", ""))
|
|
261
|
+
alias = str(node.get("alias") or name)
|
|
262
|
+
cols: dict[str, str] = {}
|
|
263
|
+
for cname, cinfo in (node.get("columns") or {}).items():
|
|
264
|
+
dt_raw = cinfo.get("data_type")
|
|
265
|
+
cols[cname] = normalize_dtype(dt_raw) if isinstance(dt_raw, str) and dt_raw.strip() else "INT"
|
|
266
|
+
m = DbtManifestModel(
|
|
267
|
+
unique_id=uid,
|
|
268
|
+
name=name,
|
|
269
|
+
alias=alias,
|
|
270
|
+
resource_type=rtype,
|
|
271
|
+
materialized=mat,
|
|
272
|
+
relation_name=node.get("relation_name"),
|
|
273
|
+
original_file_path=str(node.get("original_file_path") or ""),
|
|
274
|
+
compiled_sql=node.get("compiled_code") or node.get("compiled_sql"),
|
|
275
|
+
raw_sql=node.get("raw_code") or node.get("raw_sql"),
|
|
276
|
+
depends_on=tuple((node.get("depends_on") or {}).get("nodes") or ()),
|
|
277
|
+
columns=cols,
|
|
278
|
+
)
|
|
279
|
+
relations[uid] = m
|
|
280
|
+
if rtype == "model":
|
|
281
|
+
models[uid] = m
|
|
282
|
+
|
|
283
|
+
for uid, src in (raw.get("sources") or {}).items():
|
|
284
|
+
name = str(src.get("name", ""))
|
|
285
|
+
ident = str(src.get("identifier") or name)
|
|
286
|
+
cols = {}
|
|
287
|
+
for cname, cinfo in (src.get("columns") or {}).items():
|
|
288
|
+
dt_raw = cinfo.get("data_type")
|
|
289
|
+
cols[cname] = normalize_dtype(dt_raw) if isinstance(dt_raw, str) and dt_raw.strip() else "INT"
|
|
290
|
+
relations[uid] = DbtManifestModel(
|
|
291
|
+
unique_id=uid,
|
|
292
|
+
name=name,
|
|
293
|
+
alias=ident,
|
|
294
|
+
resource_type="source",
|
|
295
|
+
materialized="source",
|
|
296
|
+
relation_name=src.get("relation_name"),
|
|
297
|
+
original_file_path=str(src.get("original_file_path") or ""),
|
|
298
|
+
compiled_sql=None,
|
|
299
|
+
raw_sql=None,
|
|
300
|
+
depends_on=(),
|
|
301
|
+
columns=cols,
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
constraints = _extract_model_constraints(raw, relations)
|
|
305
|
+
return DbtManifest(
|
|
306
|
+
models=models,
|
|
307
|
+
relations=relations,
|
|
308
|
+
constraints=constraints,
|
|
309
|
+
adapter_type=adapter_type,
|
|
310
|
+
)
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
@dataclass(frozen=True)
|
|
314
|
+
class UnfoldedQuery:
|
|
315
|
+
sql: str
|
|
316
|
+
unfolded_views: tuple[str, ...]
|
|
317
|
+
skipped_views: tuple[str, ...]
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def unfold_upstream_views(
|
|
321
|
+
model: DbtManifestModel,
|
|
322
|
+
manifest: DbtManifest,
|
|
323
|
+
*,
|
|
324
|
+
dialect: str = "bigquery",
|
|
325
|
+
max_depth: int = 2,
|
|
326
|
+
) -> UnfoldedQuery:
|
|
327
|
+
"""Soundly inline upstream `view`/`ephemeral` dbt models as leading CTEs.
|
|
328
|
+
|
|
329
|
+
Soundness invariants (fail-closed):
|
|
330
|
+
- NEVER unfolds `table`, `incremental`, `materialized_view`, `seed`, or `source` models.
|
|
331
|
+
- NEVER unfolds a view containing volatile/non-deterministic functions (e.g., CURRENT_TIMESTAMP, RANDOM).
|
|
332
|
+
- NEVER unfolds recursive or cyclic view chains.
|
|
333
|
+
- Renames hoisted inner CTEs on collision so outer scope bindings cannot be shadowed.
|
|
334
|
+
"""
|
|
335
|
+
if not model.compiled_sql:
|
|
336
|
+
return UnfoldedQuery(sql="", unfolded_views=(), skipped_views=())
|
|
337
|
+
|
|
338
|
+
root_ast = sqlglot.parse_one(model.compiled_sql, read=dialect)
|
|
339
|
+
if not isinstance(root_ast, (exp.Select, exp.Union)):
|
|
340
|
+
return UnfoldedQuery(sql=model.compiled_sql, unfolded_views=(), skipped_views=())
|
|
341
|
+
|
|
342
|
+
existing_ctes: list[exp.CTE] = list(root_ast.args["with_"].expressions) if root_ast.args.get("with_") else []
|
|
343
|
+
used_names: set[str] = {c.alias.lower() for c in existing_ctes if c.alias}
|
|
344
|
+
unfolded_views: list[str] = []
|
|
345
|
+
skipped_views: list[str] = []
|
|
346
|
+
hoisted_ctes: list[exp.CTE] = []
|
|
347
|
+
# Map view unique_id -> allocated CTE alias
|
|
348
|
+
inlined_map: dict[str, str] = {}
|
|
349
|
+
|
|
350
|
+
def _alloc_name(preferred: str) -> str:
|
|
351
|
+
base = re.sub(r"[^a-zA-Z0-9_]", "_", preferred).lower() or "v"
|
|
352
|
+
cand = base
|
|
353
|
+
idx = 1
|
|
354
|
+
while cand in used_names:
|
|
355
|
+
cand = f"__sqlprove_{base}_{idx}"
|
|
356
|
+
idx += 1
|
|
357
|
+
used_names.add(cand)
|
|
358
|
+
return cand
|
|
359
|
+
|
|
360
|
+
def _rewrite_table_refs(node: exp.Expression, rename_map: dict[str, str]) -> None:
|
|
361
|
+
for t in list(node.find_all(exp.Table)):
|
|
362
|
+
if not t.catalog and not t.db and t.name and t.name.lower() in rename_map:
|
|
363
|
+
t.set("this", exp.to_identifier(rename_map[t.name.lower()]))
|
|
364
|
+
|
|
365
|
+
def _inline_in_ast(target_ast: exp.Expression, active_stack: set[str], depth: int) -> None:
|
|
366
|
+
if depth > max_depth:
|
|
367
|
+
return
|
|
368
|
+
# Snapshot table refs before mutation
|
|
369
|
+
tables = list(target_ast.find_all(exp.Table))
|
|
370
|
+
for tbl in tables:
|
|
371
|
+
# Skip already-bound local CTE names
|
|
372
|
+
if not tbl.catalog and not tbl.db and tbl.name and tbl.name.lower() in used_names:
|
|
373
|
+
continue
|
|
374
|
+
rel = manifest.find_relation_for_table(tbl)
|
|
375
|
+
if rel is None or rel.resource_type != "model":
|
|
376
|
+
continue
|
|
377
|
+
# Only unfold logical views / ephemeral models (NEVER materialized tables!)
|
|
378
|
+
if rel.materialized not in ("view", "ephemeral"):
|
|
379
|
+
continue
|
|
380
|
+
if rel.unique_id in active_stack:
|
|
381
|
+
if rel.name not in skipped_views:
|
|
382
|
+
skipped_views.append(rel.name)
|
|
383
|
+
continue
|
|
384
|
+
if rel.unique_id in inlined_map:
|
|
385
|
+
cte_name = inlined_map[rel.unique_id]
|
|
386
|
+
tbl.set("catalog", None)
|
|
387
|
+
tbl.set("db", None)
|
|
388
|
+
tbl.set("this", exp.to_identifier(cte_name))
|
|
389
|
+
continue
|
|
390
|
+
if not rel.compiled_sql:
|
|
391
|
+
if rel.name not in skipped_views:
|
|
392
|
+
skipped_views.append(rel.name)
|
|
393
|
+
continue
|
|
394
|
+
try:
|
|
395
|
+
view_ast = sqlglot.parse_one(rel.compiled_sql, read=dialect)
|
|
396
|
+
except Exception:
|
|
397
|
+
if rel.name not in skipped_views:
|
|
398
|
+
skipped_views.append(rel.name)
|
|
399
|
+
continue
|
|
400
|
+
if not isinstance(view_ast, (exp.Select, exp.Union)) or _has_volatile_func(view_ast):
|
|
401
|
+
if rel.name not in skipped_views:
|
|
402
|
+
skipped_views.append(rel.name)
|
|
403
|
+
continue
|
|
404
|
+
|
|
405
|
+
# Recursively unfold views referenced inside this view first (topological order!)
|
|
406
|
+
_inline_in_ast(view_ast, active_stack | {rel.unique_id}, depth + 1)
|
|
407
|
+
|
|
408
|
+
# Hoist any inner CTEs from the view cleanly with collision-free aliases
|
|
409
|
+
inner_rename: dict[str, str] = {}
|
|
410
|
+
if view_ast.args.get("with_"):
|
|
411
|
+
for inner_cte in list(view_ast.args["with_"].expressions):
|
|
412
|
+
old_alias = inner_cte.alias.lower()
|
|
413
|
+
new_alias = _alloc_name(old_alias)
|
|
414
|
+
inner_body = inner_cte.this.copy()
|
|
415
|
+
_rewrite_table_refs(inner_body, inner_rename)
|
|
416
|
+
hoisted_ctes.append(
|
|
417
|
+
exp.CTE(this=inner_body, alias=exp.TableAlias(this=exp.to_identifier(new_alias)))
|
|
418
|
+
)
|
|
419
|
+
inner_rename[old_alias] = new_alias
|
|
420
|
+
view_ast.set("with_", None)
|
|
421
|
+
|
|
422
|
+
_rewrite_table_refs(view_ast, inner_rename)
|
|
423
|
+
view_cte_name = _alloc_name(rel.alias or rel.name)
|
|
424
|
+
hoisted_ctes.append(
|
|
425
|
+
exp.CTE(this=view_ast, alias=exp.TableAlias(this=exp.to_identifier(view_cte_name)))
|
|
426
|
+
)
|
|
427
|
+
inlined_map[rel.unique_id] = view_cte_name
|
|
428
|
+
unfolded_views.append(rel.name)
|
|
429
|
+
|
|
430
|
+
# Point the consuming table reference to the new CTE (preserving alias!)
|
|
431
|
+
tbl.set("catalog", None)
|
|
432
|
+
tbl.set("db", None)
|
|
433
|
+
tbl.set("this", exp.to_identifier(view_cte_name))
|
|
434
|
+
|
|
435
|
+
_inline_in_ast(root_ast, {model.unique_id}, 1)
|
|
436
|
+
|
|
437
|
+
if hoisted_ctes:
|
|
438
|
+
combined_ctes = [*hoisted_ctes, *existing_ctes]
|
|
439
|
+
root_ast.set("with_", exp.With(expressions=combined_ctes))
|
|
440
|
+
|
|
441
|
+
return UnfoldedQuery(
|
|
442
|
+
sql=root_ast.sql(dialect=dialect),
|
|
443
|
+
unfolded_views=tuple(unfolded_views),
|
|
444
|
+
skipped_views=tuple(skipped_views),
|
|
445
|
+
)
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def _infer_col_types_from_ast(ast: exp.Expression) -> dict[str, str]:
|
|
449
|
+
"""Conservative AST-based column type hints for columns lacking explicit manifest data_type."""
|
|
450
|
+
hints: dict[str, str] = {}
|
|
451
|
+
for co in ast.find_all(exp.Coalesce):
|
|
452
|
+
if isinstance(co.this, exp.Column) and co.expressions:
|
|
453
|
+
d0 = co.expressions[0]
|
|
454
|
+
if isinstance(d0, exp.Boolean):
|
|
455
|
+
hints[co.this.name.lower()] = "BOOL"
|
|
456
|
+
elif isinstance(d0, exp.Literal) and d0.is_string:
|
|
457
|
+
hints[co.this.name.lower()] = "STRING"
|
|
458
|
+
for eq in ast.find_all((exp.EQ, exp.NEQ, exp.GT, exp.GTE, exp.LT, exp.LTE)):
|
|
459
|
+
for side_a, side_b in ((eq.this, eq.expression), (eq.expression, eq.this)):
|
|
460
|
+
if isinstance(side_a, exp.Column):
|
|
461
|
+
cn = side_a.name.lower()
|
|
462
|
+
if isinstance(side_b, exp.Boolean):
|
|
463
|
+
hints[cn] = "BOOL"
|
|
464
|
+
elif isinstance(side_b, exp.Literal) and side_b.is_string:
|
|
465
|
+
hints.setdefault(cn, "STRING")
|
|
466
|
+
elif isinstance(side_b, exp.Cast) and isinstance(side_b.to, exp.DataType):
|
|
467
|
+
dt_u = side_b.to.sql().upper()
|
|
468
|
+
if "TIMESTAMP" in dt_u or "DATETIME" in dt_u:
|
|
469
|
+
hints[cn] = "TIMESTAMP"
|
|
470
|
+
elif dt_u == "DATE":
|
|
471
|
+
hints[cn] = "DATE"
|
|
472
|
+
for fn in ast.find_all((exp.Extract, exp.TimestampTrunc, exp.DateTrunc, exp.TimeToStr)):
|
|
473
|
+
for c in fn.find_all(exp.Column):
|
|
474
|
+
hints[c.name.lower()] = "TIMESTAMP"
|
|
475
|
+
return hints
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def build_schema_for_query(
|
|
479
|
+
sql: str,
|
|
480
|
+
manifest: DbtManifest,
|
|
481
|
+
*,
|
|
482
|
+
dialect: str = "bigquery",
|
|
483
|
+
extra_dbt_constraints: dict[str, DbtModelConstraints] | None = None,
|
|
484
|
+
) -> Schema | None:
|
|
485
|
+
"""Build a sound conservative Schema for a compiled (or unfolded) dbt SQL query.
|
|
486
|
+
|
|
487
|
+
Returns None (fail closed) if two distinct qualified relations in the same query
|
|
488
|
+
collide on the same unqualified table name.
|
|
489
|
+
"""
|
|
490
|
+
ast = sqlglot.parse_one(sql, read=dialect)
|
|
491
|
+
cte_names: set[str] = set()
|
|
492
|
+
for cte in ast.find_all(exp.CTE):
|
|
493
|
+
if cte.alias:
|
|
494
|
+
cte_names.add(cte.alias.lower())
|
|
495
|
+
|
|
496
|
+
# Detect unqualified name collisions across distinct qualified base tables
|
|
497
|
+
seen_base: dict[str, tuple[str | None, DbtManifestModel | None]] = {}
|
|
498
|
+
for tbl in ast.find_all(exp.Table):
|
|
499
|
+
if not tbl.name:
|
|
500
|
+
continue
|
|
501
|
+
qual, unqual = _table_ref_key(tbl)
|
|
502
|
+
if not qual and unqual in cte_names:
|
|
503
|
+
continue
|
|
504
|
+
rel = manifest.find_relation_for_table(tbl)
|
|
505
|
+
if unqual in seen_base:
|
|
506
|
+
prev_qual, prev_rel = seen_base[unqual]
|
|
507
|
+
if prev_qual and qual and prev_qual != qual:
|
|
508
|
+
return None
|
|
509
|
+
if prev_rel and rel and prev_rel.unique_id != rel.unique_id:
|
|
510
|
+
return None
|
|
511
|
+
seen_base[unqual] = (qual, rel)
|
|
512
|
+
|
|
513
|
+
if not seen_base:
|
|
514
|
+
return Schema(tables={})
|
|
515
|
+
|
|
516
|
+
# Collect referenced column names per table alias / unqualified pool
|
|
517
|
+
type_hints = _infer_col_types_from_ast(ast)
|
|
518
|
+
all_col_names = {c.name for c in ast.find_all(exp.Column) if c.name}
|
|
519
|
+
|
|
520
|
+
# Merge manifest constraints + optional extra schema.yml constraints
|
|
521
|
+
merged_constraints: dict[str, DbtModelConstraints] = dict(manifest.constraints)
|
|
522
|
+
if extra_dbt_constraints:
|
|
523
|
+
for k, dc in extra_dbt_constraints.items():
|
|
524
|
+
kl = k.lower()
|
|
525
|
+
if kl in merged_constraints:
|
|
526
|
+
cur = merged_constraints[kl]
|
|
527
|
+
nn = tuple(sorted(set(cur.not_null_columns) | set(dc.not_null_columns)))
|
|
528
|
+
uks = list(cur.unique_keys)
|
|
529
|
+
for uk in dc.unique_keys:
|
|
530
|
+
if uk not in uks:
|
|
531
|
+
uks.append(uk)
|
|
532
|
+
fks = list(cur.foreign_keys)
|
|
533
|
+
for fk in dc.foreign_keys:
|
|
534
|
+
if fk not in fks:
|
|
535
|
+
fks.append(fk)
|
|
536
|
+
merged_constraints[kl] = DbtModelConstraints(kl, nn, tuple(uks), tuple(fks))
|
|
537
|
+
else:
|
|
538
|
+
merged_constraints[kl] = dc
|
|
539
|
+
|
|
540
|
+
tables: dict[str, TableSpec] = {}
|
|
541
|
+
for unqual, (_, rel) in seen_base.items():
|
|
542
|
+
col_map: dict[str, ColumnSpec] = {}
|
|
543
|
+
if rel is not None:
|
|
544
|
+
for cname, dtype in rel.columns.items():
|
|
545
|
+
col_map[cname.lower()] = ColumnSpec(cname, dtype, nullable=True)
|
|
546
|
+
|
|
547
|
+
# Lookup constraints by relation alias, model name, or unqualified table name
|
|
548
|
+
dc: DbtModelConstraints | None = None
|
|
549
|
+
candidates = [unqual]
|
|
550
|
+
if rel is not None:
|
|
551
|
+
candidates = [rel.alias.lower(), rel.name.lower(), unqual]
|
|
552
|
+
for ck in candidates:
|
|
553
|
+
if ck in merged_constraints:
|
|
554
|
+
dc = merged_constraints[ck]
|
|
555
|
+
break
|
|
556
|
+
|
|
557
|
+
if dc is not None:
|
|
558
|
+
for cname in dc.not_null_columns:
|
|
559
|
+
col_map.setdefault(cname.lower(), ColumnSpec(cname, type_hints.get(cname.lower(), "INT"), nullable=True))
|
|
560
|
+
for uk in dc.unique_keys:
|
|
561
|
+
for cname in uk:
|
|
562
|
+
col_map.setdefault(cname.lower(), ColumnSpec(cname, type_hints.get(cname.lower(), "INT"), nullable=True))
|
|
563
|
+
for fk in dc.foreign_keys:
|
|
564
|
+
for cname in fk.columns:
|
|
565
|
+
col_map.setdefault(cname.lower(), ColumnSpec(cname, type_hints.get(cname.lower(), "INT"), nullable=True))
|
|
566
|
+
|
|
567
|
+
for cname in sorted(all_col_names):
|
|
568
|
+
col_map.setdefault(cname.lower(), ColumnSpec(cname, type_hints.get(cname.lower(), "INT"), nullable=True))
|
|
569
|
+
|
|
570
|
+
tables[unqual] = TableSpec(name=unqual, columns=tuple(col_map.values()))
|
|
571
|
+
|
|
572
|
+
base_schema = Schema(tables=tables)
|
|
573
|
+
# Re-key constraints by unqualified table name present in `base_schema`
|
|
574
|
+
rekeyed: dict[str, DbtModelConstraints] = {}
|
|
575
|
+
for unqual, (_, rel) in seen_base.items():
|
|
576
|
+
candidates = [rel.alias.lower(), rel.name.lower(), unqual] if rel is not None else [unqual]
|
|
577
|
+
for ck in candidates:
|
|
578
|
+
if ck in merged_constraints:
|
|
579
|
+
rekeyed[unqual] = merged_constraints[ck]
|
|
580
|
+
break
|
|
581
|
+
|
|
582
|
+
return base_schema.with_dbt_constraints(rekeyed)
|