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/corpus.py ADDED
@@ -0,0 +1,448 @@
1
+ """Scan real dbt / SQL repositories for high-cost optimization candidate patterns."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import Counter
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+ import re
9
+ from typing import Any
10
+
11
+ import sqlglot
12
+ from sqlglot import exp
13
+
14
+ _JINJA_COMMENT_RE = re.compile(r"\{#.*?#\}", re.DOTALL)
15
+ _CONFIG_RE = re.compile(r"\{\{-?\s*config\s*\(.*?\)\s*-?\}\}", re.DOTALL)
16
+ _REF_2ARG_RE = re.compile(
17
+ r"\{\{-?\s*ref\s*\(\s*['\"]([^'\"]+)['\"]\s*,\s*['\"]([^'\"]+)['\"](?:\s*,.*?)?\s*\)\s*-?\}\}",
18
+ re.DOTALL,
19
+ )
20
+ _REF_1ARG_RE = re.compile(
21
+ r"\{\{-?\s*ref\s*\(\s*['\"]([^'\"]+)['\"](?:\s*,.*?)?\s*\)\s*-?\}\}",
22
+ re.DOTALL,
23
+ )
24
+ _SOURCE_RE = re.compile(
25
+ r"\{\{-?\s*source\s*\(\s*['\"]([^'\"]+)['\"]\s*,\s*['\"]([^'\"]+)['\"]\s*\)\s*-?\}\}",
26
+ re.DOTALL,
27
+ )
28
+ _TYPE_MACRO_RE = re.compile(
29
+ r"\{\{-?\s*(?:[a-zA-Z0-9_]+\.)?type_(string|int|bigint|float|numeric|boolean|timestamp|date)\s*\([^)]*\)\s*-?\}\}",
30
+ re.IGNORECASE,
31
+ )
32
+ _STAR_MACRO_RE = re.compile(
33
+ r"\{\{-?\s*(?:[a-zA-Z0-9_]+\.)?(?:star|fill_staging_columns)\s*\(.*?\)\s*-?\}\}",
34
+ re.DOTALL | re.IGNORECASE,
35
+ )
36
+ _JINJA_BLOCK_RE = re.compile(r"\{%.*?%\}", re.DOTALL)
37
+ _JINJA_EXPR_RE = re.compile(r"\{\{.*?\}\}", re.DOTALL)
38
+ _IF_TAG_RE = re.compile(r"\{%-?\s*(if|elif|else|endif)\b.*?-%\}|\{%\s*(if|elif|else|endif)\b.*?%\}", re.DOTALL)
39
+
40
+ _TYPE_MAP = {
41
+ "string": "STRING",
42
+ "int": "INT64",
43
+ "bigint": "INT64",
44
+ "float": "FLOAT64",
45
+ "numeric": "NUMERIC",
46
+ "boolean": "BOOL",
47
+ "timestamp": "TIMESTAMP",
48
+ "date": "DATE",
49
+ }
50
+
51
+ _EXCLUDED_DIR_PARTS = {
52
+ "macros",
53
+ "tests",
54
+ "test",
55
+ "integration_tests",
56
+ "integration_test_project",
57
+ "snapshots",
58
+ "seeds",
59
+ }
60
+
61
+
62
+ def _strip_jinja_else_branches(text: str) -> str:
63
+ """Keep only the primary `if` branch of Jinja if/elif/else/endif blocks for AST scanning.
64
+
65
+ NOTE: This is strictly for static corpus pattern discovery, never for formal verification.
66
+ """
67
+ out: list[str] = []
68
+ pos = 0
69
+ # Stack entries: True if we are currently emitting tokens at this nesting level.
70
+ stack: list[bool] = []
71
+ for match in _IF_TAG_RE.finditer(text):
72
+ start, end = match.span()
73
+ emitting = all(stack) if stack else True
74
+ if emitting:
75
+ out.append(text[pos:start])
76
+ tag = (match.group(1) or match.group(2) or "").lower()
77
+ if tag == "if":
78
+ stack.append(True)
79
+ elif tag in ("elif", "else"):
80
+ if stack:
81
+ stack[-1] = False
82
+ elif tag == "endif":
83
+ if stack:
84
+ stack.pop()
85
+ pos = end
86
+ if all(stack) if stack else True:
87
+ out.append(text[pos:])
88
+ return "".join(out)
89
+
90
+
91
+ def preprocess_dbt_sql(sql: str) -> str:
92
+ """Convert common dbt Jinja macros into valid SQL placeholders for corpus scanning."""
93
+ cleaned = _JINJA_COMMENT_RE.sub(" ", sql)
94
+ cleaned = _CONFIG_RE.sub(" ", cleaned)
95
+ cleaned = _strip_jinja_else_branches(cleaned)
96
+ cleaned = _REF_2ARG_RE.sub(lambda m: f"__dbt_ref_{m.group(1)}__{m.group(2)}", cleaned)
97
+ cleaned = _REF_1ARG_RE.sub(lambda m: f"__dbt_ref_{m.group(1)}", cleaned)
98
+ cleaned = _SOURCE_RE.sub(lambda m: f"__dbt_src_{m.group(1)}_{m.group(2)}", cleaned)
99
+ cleaned = _TYPE_MACRO_RE.sub(lambda m: _TYPE_MAP.get(m.group(1).lower(), "STRING"), cleaned)
100
+ cleaned = _STAR_MACRO_RE.sub(" * ", cleaned)
101
+ if "{%" in cleaned or "{{" in cleaned:
102
+ cleaned = _JINJA_BLOCK_RE.sub(" ", cleaned)
103
+ cleaned = _JINJA_EXPR_RE.sub(" __dbt_expr ", cleaned)
104
+ return cleaned.strip()
105
+
106
+
107
+ @dataclass
108
+ class FileFinding:
109
+ path: str
110
+ parsed: bool
111
+ dialect_used: str | None = None
112
+ patterns: list[str] = field(default_factory=list)
113
+ parse_error: str | None = None
114
+
115
+
116
+ @dataclass
117
+ class ScanReport:
118
+ root: str
119
+ dialect: str
120
+ total_files: int
121
+ parsed_files: int
122
+ pattern_counts: dict[str, int]
123
+ findings: list[FileFinding]
124
+
125
+ def to_dict(self) -> dict[str, Any]:
126
+ return {
127
+ "root": self.root,
128
+ "dialect": self.dialect,
129
+ "total_files": self.total_files,
130
+ "parsed_files": self.parsed_files,
131
+ "pattern_counts": self.pattern_counts,
132
+ "findings": [
133
+ {
134
+ "path": f.path,
135
+ "parsed": f.parsed,
136
+ "dialect_used": f.dialect_used,
137
+ "patterns": f.patterns,
138
+ "parse_error": f.parse_error,
139
+ }
140
+ for f in self.findings
141
+ if f.patterns or not f.parsed
142
+ ],
143
+ }
144
+
145
+
146
+ def _extract_table_alias(node: exp.Expression) -> str:
147
+ if isinstance(node, exp.Table):
148
+ return (node.alias or node.name or "").lower()
149
+ if hasattr(node, "alias") and node.alias:
150
+ return str(node.alias).lower()
151
+ return ""
152
+
153
+
154
+ def _is_null_rejecting_on_alias(where_expr: exp.Expression, rhs_alias: str) -> bool:
155
+ """Heuristically detect simple top-level conjuncts in WHERE that reject NULL rhs rows."""
156
+ # Decompose top-level AND conjuncts.
157
+ conjuncts: list[exp.Expression] = []
158
+ stack = [where_expr]
159
+ while stack:
160
+ cur = stack.pop()
161
+ if isinstance(cur, exp.Paren):
162
+ stack.append(cur.this)
163
+ elif isinstance(cur, exp.And):
164
+ stack.append(cur.this)
165
+ stack.append(cur.expression)
166
+ else:
167
+ conjuncts.append(cur)
168
+
169
+ for conj in conjuncts:
170
+ # Reject OR/NOT (could be IS NULL or OR rhs.x IS NULL)
171
+ if isinstance(conj, exp.Or):
172
+ continue
173
+ if isinstance(conj, exp.Not) and isinstance(conj.this, exp.Is) and isinstance(conj.this.expression, exp.Null):
174
+ cols = [c for c in conj.this.this.find_all(exp.Column) if c.table and c.table.lower() == rhs_alias]
175
+ if cols and not list(conj.this.this.find_all(exp.Coalesce)):
176
+ return True
177
+ if isinstance(conj, (exp.EQ, exp.NEQ, exp.LT, exp.LTE, exp.GT, exp.GTE, exp.Like, exp.ILike, exp.In)):
178
+ # If the comparison directly compares a column of rhs_alias (not wrapped in COALESCE/CASE)
179
+ lhs = conj.this
180
+ if isinstance(lhs, exp.Column) and lhs.table and lhs.table.lower() == rhs_alias:
181
+ return True
182
+ return False
183
+
184
+
185
+ def _has_row_number_window(node: exp.Expression) -> bool:
186
+ for win in node.find_all(exp.Window):
187
+ if isinstance(win.this, exp.RowNumber):
188
+ return True
189
+ return False
190
+
191
+
192
+ def _is_function_wrapped_column(expr: exp.Expression) -> bool:
193
+ """Detect f(col) inside a predicate (e.g., DATE(ts), LOWER(s), CAST(ts AS DATE))."""
194
+ if isinstance(expr, (exp.Column, exp.Literal, exp.Null, exp.Boolean, exp.Coalesce)):
195
+ return False
196
+ if isinstance(expr, exp.Paren):
197
+ return _is_function_wrapped_column(expr.this)
198
+ if isinstance(expr, (exp.Func, exp.Cast, exp.TryCast)):
199
+ return any(True for _ in expr.find_all(exp.Column))
200
+ return False
201
+
202
+
203
+ def analyze_sql_ast(ast: exp.Expression) -> list[str]:
204
+ """Flag candidate cost-optimization patterns in a parsed SQL AST."""
205
+ patterns: set[str] = set()
206
+
207
+ # 1. Repeated scans of the same base table or repeated references to the same CTE.
208
+ table_counts = Counter(
209
+ t.name.lower()
210
+ for t in ast.find_all(exp.Table)
211
+ if t.name and t.name.lower() != "__dbt_expr"
212
+ )
213
+ cte_map: dict[str, exp.CTE] = {
214
+ cte.alias.lower(): cte for cte in ast.find_all(exp.CTE) if cte.alias
215
+ }
216
+ cte_names = set(cte_map.keys())
217
+
218
+ repeated_base = [t for t, c in table_counts.items() if c >= 2 and t not in cte_names]
219
+ if repeated_base:
220
+ patterns.add("repeated_base_table_scan")
221
+
222
+ repeated_ctes = [t for t, c in table_counts.items() if c >= 2 and t in cte_names]
223
+ if repeated_ctes:
224
+ patterns.add("repeated_cte_reference")
225
+
226
+ # Classify CTE contents for downstream outer-filter / window-dedup checks.
227
+ cte_has_window = {name: _has_row_number_window(cte.this) or bool(list(cte.this.find_all(exp.Window))) for name, cte in cte_map.items()}
228
+ cte_has_row_number = {name: _has_row_number_window(cte.this) for name, cte in cte_map.items()}
229
+ cte_has_union = {name: bool(list(cte.this.find_all(exp.Union))) for name, cte in cte_map.items()}
230
+ cte_has_group = {name: any(s.args.get("group") is not None for s in cte.this.find_all(exp.Select)) for name, cte in cte_map.items()}
231
+
232
+ for sel in ast.find_all(exp.Select):
233
+ has_distinct = bool(sel.args.get("distinct"))
234
+ has_group = sel.args.get("group") is not None
235
+ if has_distinct:
236
+ patterns.add("select_distinct")
237
+ if has_distinct and has_group:
238
+ patterns.add("distinct_with_group_by")
239
+
240
+ has_star = any(
241
+ isinstance(e, exp.Star) or (isinstance(e, exp.Column) and isinstance(e.this, exp.Star))
242
+ for e in sel.expressions
243
+ )
244
+ if has_star:
245
+ patterns.add("select_star")
246
+
247
+ qualify = sel.args.get("qualify")
248
+ if qualify is not None:
249
+ patterns.add("qualify_clause")
250
+ if _has_row_number_window(qualify) or _has_row_number_window(sel):
251
+ patterns.add("row_number_dedup")
252
+
253
+ # Inspect WHERE clause patterns.
254
+ where = sel.args.get("where")
255
+ if where is not None:
256
+ w_expr = where.this
257
+ if list(w_expr.find_all(exp.Or)):
258
+ patterns.add("or_predicate_in_where")
259
+ if list(w_expr.find_all(exp.Coalesce)):
260
+ patterns.add("coalesce_in_where")
261
+
262
+ # Function-wrapped column comparisons in WHERE (e.g. DATE(ts) = ..., LOWER(x) = ...).
263
+ for cmp in w_expr.find_all((exp.EQ, exp.NEQ, exp.LT, exp.LTE, exp.GT, exp.GTE, exp.Between, exp.In)):
264
+ lhs = cmp.this
265
+ if lhs is not None and _is_function_wrapped_column(lhs):
266
+ patterns.add("function_wrapped_filter_col")
267
+ break
268
+
269
+ # Outer filter over CTE / subquery / UNION / Window.
270
+ from_clause = sel.args.get("from_")
271
+ from_targets: list[exp.Expression] = []
272
+ if from_clause is not None and from_clause.this is not None:
273
+ from_targets.append(from_clause.this)
274
+ for j in sel.args.get("joins") or []:
275
+ if j.this is not None:
276
+ from_targets.append(j.this)
277
+
278
+ for target in from_targets:
279
+ if isinstance(target, exp.Table) and target.name.lower() in cte_map:
280
+ cname = target.name.lower()
281
+ patterns.add("outer_filter_over_cte")
282
+ if cte_has_union.get(cname):
283
+ patterns.add("outer_filter_over_union")
284
+ if cte_has_window.get(cname):
285
+ patterns.add("outer_filter_over_window")
286
+ if cte_has_row_number.get(cname):
287
+ # Heuristic: filtering on = 1 after a ROW_NUMBER() CTE
288
+ for eq in w_expr.find_all(exp.EQ):
289
+ if (isinstance(eq.expression, exp.Literal) and str(eq.expression.this) == "1") or (
290
+ isinstance(eq.this, exp.Literal) and str(eq.this.this) == "1"
291
+ ):
292
+ patterns.add("row_number_dedup")
293
+ if cte_has_group.get(cname):
294
+ patterns.add("outer_filter_over_group_by")
295
+ elif isinstance(target, exp.Subquery):
296
+ patterns.add("outer_filter_over_subquery")
297
+ if list(target.this.find_all(exp.Union)):
298
+ patterns.add("outer_filter_over_union")
299
+ if list(target.this.find_all(exp.Window)):
300
+ patterns.add("outer_filter_over_window")
301
+ if _has_row_number_window(target.this):
302
+ for eq in w_expr.find_all(exp.EQ):
303
+ if isinstance(eq.expression, exp.Literal) and str(eq.expression.this) == "1":
304
+ patterns.add("row_number_dedup")
305
+
306
+ # Inspect JOINs.
307
+ joins = sel.args.get("joins") or []
308
+ if joins:
309
+ # Collect all column references outside each join's own ON clause.
310
+ non_join_parts = [
311
+ *sel.expressions,
312
+ sel.args.get("where"),
313
+ sel.args.get("group"),
314
+ sel.args.get("having"),
315
+ sel.args.get("qualify"),
316
+ sel.args.get("order"),
317
+ ]
318
+ non_join_cols = [
319
+ c for part in non_join_parts if part is not None for c in part.find_all(exp.Column)
320
+ ]
321
+ has_unqualified_col = any(not c.table for c in non_join_cols if not isinstance(c.this, exp.Star))
322
+ referenced_outside_joins = {c.table.lower() for c in non_join_cols if c.table}
323
+
324
+ for idx, join in enumerate(joins):
325
+ on_expr = join.args.get("on")
326
+ if on_expr is not None and list(on_expr.find_all(exp.Coalesce)):
327
+ patterns.add("coalesce_in_join_on")
328
+
329
+ if (join.side or "").upper() == "LEFT":
330
+ patterns.add("left_join_present")
331
+ rhs_alias = _extract_table_alias(join.this)
332
+ if not rhs_alias:
333
+ continue
334
+
335
+ # Check if any OTHER join's ON clause references rhs_alias.
336
+ other_join_refs = {
337
+ c.table.lower()
338
+ for j_idx, other_j in enumerate(joins)
339
+ if j_idx != idx and other_j.args.get("on") is not None
340
+ for c in other_j.args["on"].find_all(exp.Column)
341
+ if c.table
342
+ }
343
+ all_refs = referenced_outside_joins | other_join_refs
344
+
345
+ if where is not None and _is_null_rejecting_on_alias(where.this, rhs_alias):
346
+ patterns.add("left_join_null_rejected_in_where")
347
+
348
+ if rhs_alias not in all_refs and not has_star:
349
+ patterns.add("potentially_unused_left_join")
350
+ if not has_unqualified_col:
351
+ patterns.add("unused_left_join_strict")
352
+
353
+ for u in ast.find_all(exp.Union):
354
+ patterns.add("union_branch")
355
+ if u.args.get("distinct", True):
356
+ patterns.add("union_distinct")
357
+ else:
358
+ patterns.add("union_all")
359
+
360
+ if list(ast.find_all(exp.Window)):
361
+ patterns.add("window_function")
362
+
363
+ for node in ast.find_all(exp.In):
364
+ if node.args.get("query") is not None:
365
+ patterns.add("in_subquery")
366
+ if isinstance(node.parent, exp.Not):
367
+ patterns.add("not_in_subquery")
368
+
369
+ return sorted(patterns)
370
+
371
+
372
+ def _should_skip_file(rel_parts: tuple[str, ...], models_only: bool) -> bool:
373
+ if not models_only:
374
+ return False
375
+ lower_parts = [p.lower() for p in rel_parts]
376
+ if any(p in _EXCLUDED_DIR_PARTS for p in lower_parts):
377
+ return True
378
+ return False
379
+
380
+
381
+ def _parse_with_fallback(cleaned: str, primary_dialect: str, fallback_dialects: tuple[str, ...]) -> tuple[exp.Expression, str]:
382
+ dialects = [primary_dialect] + [d for d in fallback_dialects if d != primary_dialect]
383
+ last_exc: Exception | None = None
384
+ for d in dialects:
385
+ try:
386
+ ast = sqlglot.parse_one(cleaned, read=d)
387
+ if isinstance(ast, exp.Command):
388
+ last_exc = ValueError(f"Parsed as opaque Command under dialect={d}")
389
+ continue
390
+ return ast, d
391
+ except Exception as exc:
392
+ last_exc = exc
393
+ assert last_exc is not None
394
+ raise last_exc
395
+
396
+
397
+ def scan_directory(
398
+ root: str | Path,
399
+ *,
400
+ dialect: str = "bigquery",
401
+ models_only: bool = False,
402
+ fallback_dialects: tuple[str, ...] = ("snowflake", "duckdb"),
403
+ ) -> ScanReport:
404
+ root_path = Path(root)
405
+ sql_files = [
406
+ p
407
+ for p in sorted(root_path.rglob("*.sql"))
408
+ if not _should_skip_file(p.relative_to(root_path).parts, models_only)
409
+ ]
410
+ findings: list[FileFinding] = []
411
+ counts: Counter[str] = Counter()
412
+ parsed_files = 0
413
+
414
+ for path in sql_files:
415
+ raw = path.read_text(errors="replace")
416
+ cleaned = preprocess_dbt_sql(raw)
417
+ if not cleaned:
418
+ continue
419
+ try:
420
+ ast, used_dialect = _parse_with_fallback(cleaned, dialect, fallback_dialects)
421
+ pats = analyze_sql_ast(ast)
422
+ parsed_files += 1
423
+ counts.update(pats)
424
+ findings.append(
425
+ FileFinding(
426
+ path=str(path.relative_to(root_path)),
427
+ parsed=True,
428
+ dialect_used=used_dialect,
429
+ patterns=pats,
430
+ )
431
+ )
432
+ except Exception as exc:
433
+ findings.append(
434
+ FileFinding(
435
+ path=str(path.relative_to(root_path)),
436
+ parsed=False,
437
+ parse_error=str(exc)[:180],
438
+ )
439
+ )
440
+
441
+ return ScanReport(
442
+ root=str(root_path),
443
+ dialect=dialect,
444
+ total_files=len(sql_files),
445
+ parsed_files=parsed_files,
446
+ pattern_counts=dict(counts.most_common()),
447
+ findings=findings,
448
+ )
sqlprove/cost.py ADDED
@@ -0,0 +1,92 @@
1
+ """Cost & execution measurement hooks (DuckDB 2.0 native JSON profiler + BigQuery dry-run interface)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ import json
7
+ from typing import Any
8
+
9
+ import duckdb
10
+ import sqlglot
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class CostMeasurement:
15
+ engine: str
16
+ elapsed_ms: float
17
+ row_count: int
18
+ plan_text: str
19
+ cpu_ms: float = 0.0
20
+ rows_scanned: int = 0
21
+ row_groups_scanned: int = 0
22
+ bytes_read: int = 0
23
+ intermediate_bytes: int = 0
24
+
25
+
26
+ def measure_duckdb_query(
27
+ con: duckdb.DuckDBPyConnection,
28
+ sql: str,
29
+ *,
30
+ dialect: str = "duckdb",
31
+ repeats: int = 3,
32
+ ) -> CostMeasurement:
33
+ """Measure pure C++ DuckDB execution time, scan metrics, and physical plan."""
34
+ duck_sql = sql if dialect.lower() == "duckdb" else sqlglot.transpile(sql, read=dialect, write="duckdb")[0]
35
+ plan_rows = con.execute(f"EXPLAIN {duck_sql}").fetchall()
36
+ plan_text = "\n".join(str(r[-1]) for r in plan_rows)
37
+
38
+ wall_ms: list[float] = []
39
+ cpu_ms: list[float] = []
40
+ last_prof: dict[str, Any] = {}
41
+ for _ in range(repeats):
42
+ prof_str = con.execute(f"EXPLAIN (ANALYZE, FORMAT JSON) {duck_sql}").fetchall()[0][-1]
43
+ prof = json.loads(prof_str)
44
+ last_prof = prof
45
+ q = prof.get("query") or {}
46
+ wall_ms.append(float(q.get("total_time", 0.0)) * 1000.0)
47
+ cpu_ms.append(float(q.get("cpu_time", 0.0)) * 1000.0)
48
+
49
+ wall_ms.sort()
50
+ cpu_ms.sort()
51
+ q_m = last_prof.get("query") or {}
52
+ io_m = last_prof.get("io") or {}
53
+
54
+ # Extract final output row count from top-level operator (avoids Python tuple materialization)
55
+ row_count = 0
56
+ ops = last_prof.get("operator") or []
57
+ if ops:
58
+ # RESULT_COLLECTOR -> EXPLAIN_ANALYZE -> root query operator
59
+ node = ops[0]
60
+ while node.get("name") in ("RESULT_COLLECTOR", "EXPLAIN_ANALYZE") and node.get("children"):
61
+ node = node["children"][0]
62
+ row_count = int(node.get("intermediate_rows", 0))
63
+
64
+ return CostMeasurement(
65
+ engine="duckdb",
66
+ elapsed_ms=round(wall_ms[len(wall_ms) // 2], 3),
67
+ cpu_ms=round(cpu_ms[len(cpu_ms) // 2], 3),
68
+ row_count=row_count,
69
+ rows_scanned=int(q_m.get("total_rows_scanned", 0)),
70
+ row_groups_scanned=int(q_m.get("total_row_groups_scanned", 0)),
71
+ bytes_read=int(io_m.get("total_bytes_read", 0)),
72
+ intermediate_bytes=int(q_m.get("total_intermediate_size_bytes", 0)),
73
+ plan_text=plan_text,
74
+ )
75
+
76
+
77
+ def estimate_bigquery_dry_run_bytes(sql: str, *, project: str | None = None) -> dict[str, Any]:
78
+ """Optional free BigQuery dry-run estimator (requires google-cloud-bigquery + GCP auth)."""
79
+ try:
80
+ from google.cloud import bigquery # type: ignore[import-not-found]
81
+ except ImportError as exc:
82
+ raise RuntimeError(
83
+ "google-cloud-bigquery is not installed. Install it only when running BigQuery dry-runs."
84
+ ) from exc
85
+
86
+ client = bigquery.Client(project=project)
87
+ job_config = bigquery.QueryJobConfig(dry_run=True, use_query_cache=False)
88
+ job = client.query(sql, job_config=job_config)
89
+ return {
90
+ "total_bytes_processed": job.total_bytes_processed,
91
+ "estimated_tb": (job.total_bytes_processed or 0) / (1024**4),
92
+ }