bqguard 0.4.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.
- bqguard/__init__.py +4 -0
- bqguard/__main__.py +6 -0
- bqguard/baseline.py +132 -0
- bqguard/cli.py +388 -0
- bqguard/config.py +89 -0
- bqguard/engine/__init__.py +18 -0
- bqguard/engine/fixer.py +425 -0
- bqguard/engine/parser.py +228 -0
- bqguard/engine/patching.py +245 -0
- bqguard/engine/runner.py +159 -0
- bqguard/estimators/__init__.py +5 -0
- bqguard/estimators/bigquery_dryrun.py +85 -0
- bqguard/loaders/__init__.py +28 -0
- bqguard/loaders/dbt_loader.py +175 -0
- bqguard/loaders/git_loader.py +125 -0
- bqguard/loaders/metadata_loader.py +155 -0
- bqguard/loaders/sql_loader.py +65 -0
- bqguard/models.py +247 -0
- bqguard/reporters/__init__.py +8 -0
- bqguard/reporters/json_reporter.py +23 -0
- bqguard/reporters/markdown.py +84 -0
- bqguard/reporters/sarif.py +96 -0
- bqguard/reporters/terminal.py +92 -0
- bqguard/rules/__init__.py +21 -0
- bqguard/rules/base.py +76 -0
- bqguard/rules/builtin.py +664 -0
- bqguard/rules/helpers.py +135 -0
- bqguard/rules/specs.py +74 -0
- bqguard/service.py +220 -0
- bqguard/web/__init__.py +5 -0
- bqguard/web/server.py +234 -0
- bqguard/web/static/index.html +237 -0
- bqguard-0.4.0.dist-info/METADATA +434 -0
- bqguard-0.4.0.dist-info/RECORD +38 -0
- bqguard-0.4.0.dist-info/WHEEL +5 -0
- bqguard-0.4.0.dist-info/entry_points.txt +2 -0
- bqguard-0.4.0.dist-info/licenses/LICENSE +21 -0
- bqguard-0.4.0.dist-info/top_level.txt +1 -0
bqguard/__init__.py
ADDED
bqguard/__main__.py
ADDED
bqguard/baseline.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Line-independent baseline fingerprinting for incremental bqguard adoption."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
from collections import Counter
|
|
8
|
+
from datetime import datetime, timezone
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from pydantic import BaseModel, Field
|
|
12
|
+
|
|
13
|
+
from bqguard.models import AnalysisSummary, Finding, QueryReport
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class BaselineEntry(BaseModel):
|
|
17
|
+
"""A single fingerprinted legacy violation stored in a baseline file."""
|
|
18
|
+
|
|
19
|
+
fingerprint: str
|
|
20
|
+
source_path: str
|
|
21
|
+
rule_id: str
|
|
22
|
+
table: str | None = None
|
|
23
|
+
column: str | None = None
|
|
24
|
+
count: int = Field(default=1, ge=1)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Baseline(BaseModel):
|
|
28
|
+
"""Serialized snapshot of known legacy findings to suppress in future runs."""
|
|
29
|
+
|
|
30
|
+
version: int = 1
|
|
31
|
+
generated_at: str = Field(
|
|
32
|
+
default_factory=lambda: datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
33
|
+
)
|
|
34
|
+
entries: list[BaselineEntry] = Field(default_factory=list)
|
|
35
|
+
|
|
36
|
+
def counts(self) -> Counter[str]:
|
|
37
|
+
return Counter({e.fingerprint: e.count for e in self.entries})
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _normalize_path(path: str) -> str:
|
|
41
|
+
norm = path.replace("\\", "/").strip()
|
|
42
|
+
while norm.startswith("./"):
|
|
43
|
+
norm = norm[2:]
|
|
44
|
+
return norm.lower()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def finding_fingerprint(finding: Finding) -> str:
|
|
48
|
+
"""Compute a deterministic, line-independent fingerprint for a Finding.
|
|
49
|
+
|
|
50
|
+
Omits line numbers so inserting/deleting lines above a legacy violation
|
|
51
|
+
does not break baseline suppression.
|
|
52
|
+
"""
|
|
53
|
+
norm_path = _normalize_path(finding.source_path)
|
|
54
|
+
detail = " ".join((finding.snippet or finding.message).split()).lower()
|
|
55
|
+
raw_key = "|".join(
|
|
56
|
+
[
|
|
57
|
+
norm_path,
|
|
58
|
+
finding.rule_id.upper(),
|
|
59
|
+
(finding.table or "").lower(),
|
|
60
|
+
(finding.column or "").lower(),
|
|
61
|
+
detail,
|
|
62
|
+
]
|
|
63
|
+
)
|
|
64
|
+
return hashlib.sha256(raw_key.encode("utf-8")).hexdigest()[:16]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def create_baseline(summary: AnalysisSummary) -> Baseline:
|
|
68
|
+
"""Build a Baseline object from an AnalysisSummary."""
|
|
69
|
+
counts: Counter[str] = Counter()
|
|
70
|
+
samples: dict[str, Finding] = {}
|
|
71
|
+
|
|
72
|
+
for report in summary.reports:
|
|
73
|
+
for finding in report.findings:
|
|
74
|
+
fp = finding_fingerprint(finding)
|
|
75
|
+
counts[fp] += 1
|
|
76
|
+
samples.setdefault(fp, finding)
|
|
77
|
+
|
|
78
|
+
entries = [
|
|
79
|
+
BaselineEntry(
|
|
80
|
+
fingerprint=fp,
|
|
81
|
+
source_path=_normalize_path(samples[fp].source_path),
|
|
82
|
+
rule_id=samples[fp].rule_id,
|
|
83
|
+
table=samples[fp].table,
|
|
84
|
+
column=samples[fp].column,
|
|
85
|
+
count=count,
|
|
86
|
+
)
|
|
87
|
+
for fp, count in sorted(counts.items(), key=lambda kv: (samples[kv[0]].source_path, samples[kv[0]].rule_id, kv[0]))
|
|
88
|
+
]
|
|
89
|
+
return Baseline(entries=entries)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def save_baseline(summary: AnalysisSummary, path: str | Path) -> Baseline:
|
|
93
|
+
"""Generate and persist a JSON baseline file."""
|
|
94
|
+
baseline = create_baseline(summary)
|
|
95
|
+
out = Path(path)
|
|
96
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
97
|
+
out.write_text(json.dumps(baseline.model_dump(mode="json"), indent=2) + "\n", encoding="utf-8")
|
|
98
|
+
return baseline
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def load_baseline(path: str | Path) -> Baseline:
|
|
102
|
+
"""Load and validate a JSON baseline file."""
|
|
103
|
+
file_path = Path(path)
|
|
104
|
+
if not file_path.exists():
|
|
105
|
+
raise FileNotFoundError(f"Baseline file not found: {file_path}")
|
|
106
|
+
data = json.loads(file_path.read_text(encoding="utf-8"))
|
|
107
|
+
return Baseline.model_validate(data)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def apply_baseline(summary: AnalysisSummary, baseline: Baseline) -> AnalysisSummary:
|
|
111
|
+
"""Return a new AnalysisSummary with baseline-matched legacy findings suppressed."""
|
|
112
|
+
remaining = baseline.counts()
|
|
113
|
+
suppressed = 0
|
|
114
|
+
new_reports: list[QueryReport] = []
|
|
115
|
+
|
|
116
|
+
for report in summary.reports:
|
|
117
|
+
kept: list[Finding] = []
|
|
118
|
+
for finding in report.findings:
|
|
119
|
+
fp = finding_fingerprint(finding)
|
|
120
|
+
if remaining[fp] > 0:
|
|
121
|
+
remaining[fp] -= 1
|
|
122
|
+
suppressed += 1
|
|
123
|
+
else:
|
|
124
|
+
kept.append(finding)
|
|
125
|
+
new_reports.append(report.model_copy(update={"findings": kept}))
|
|
126
|
+
|
|
127
|
+
return summary.model_copy(
|
|
128
|
+
update={
|
|
129
|
+
"reports": new_reports,
|
|
130
|
+
"baseline_suppressed_count": summary.baseline_suppressed_count + suppressed,
|
|
131
|
+
}
|
|
132
|
+
)
|
bqguard/cli.py
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
"""Command-line interface for bqguard (v0.3 — BigQuery, Snowflake, Databricks)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Literal
|
|
8
|
+
|
|
9
|
+
import click
|
|
10
|
+
from colorama import Fore, Style
|
|
11
|
+
from colorama import init as colorama_init
|
|
12
|
+
|
|
13
|
+
from bqguard import __version__
|
|
14
|
+
from bqguard.baseline import save_baseline
|
|
15
|
+
from bqguard.config import BQGuardConfig, load_config
|
|
16
|
+
from bqguard.loaders.metadata_loader import generate_metadata_sync_sql
|
|
17
|
+
from bqguard.reporters import render_json, render_markdown, render_sarif, render_terminal
|
|
18
|
+
from bqguard.rules.specs import RULE_SPECS
|
|
19
|
+
from bqguard.service import BQGuardError, CheckRequest, run_check
|
|
20
|
+
|
|
21
|
+
STARTER_CONFIG_YAML = """# bqguard configuration — SQL & dbt FinOps Guardrail
|
|
22
|
+
dialect: bigquery # bigquery | snowflake | databricks
|
|
23
|
+
min_table_size_gb: 1.0
|
|
24
|
+
fail_on: error # error | warning
|
|
25
|
+
metadata_path: metadata.yaml
|
|
26
|
+
|
|
27
|
+
rules:
|
|
28
|
+
BQ001: error # SELECT * on large columnar tables
|
|
29
|
+
BQ002: error # Missing partition filter on large partitioned tables
|
|
30
|
+
BQ003: error # Non-SARGable predicate on partition/cluster column
|
|
31
|
+
BQ004: error # Unintended CROSS JOIN / comma join (UNNEST / FLATTEN allowed)
|
|
32
|
+
BQ005: warning # ORDER BY without LIMIT inside CTE or subquery
|
|
33
|
+
BQ006: warning # UNION DISTINCT / UNION instead of UNION ALL
|
|
34
|
+
BQ007: warning # Leading wildcard LIKE '%...' on clustered/large column
|
|
35
|
+
BQ008: error # BigQuery Dry Run cost/bytes threshold exceeded
|
|
36
|
+
|
|
37
|
+
cost:
|
|
38
|
+
price_per_tb_usd: 6.25
|
|
39
|
+
max_cost_usd: 5.0
|
|
40
|
+
warn_cost_usd: 1.0
|
|
41
|
+
# max_gb_scanned: 500
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
STARTER_METADATA_YAML = """# Offline metadata snapshot — zero row data or PII
|
|
45
|
+
# Refresh nightly using `bqguard sync-sql --dataset your_project.your_dataset`
|
|
46
|
+
tables:
|
|
47
|
+
- name: prod.analytics.user_events
|
|
48
|
+
size_gb: 4500.0
|
|
49
|
+
row_count: 18000000000
|
|
50
|
+
partition_column: event_timestamp
|
|
51
|
+
partition_type: DAY
|
|
52
|
+
cluster_columns:
|
|
53
|
+
- country_code
|
|
54
|
+
- event_name
|
|
55
|
+
require_partition_filter: true
|
|
56
|
+
|
|
57
|
+
- name: prod.analytics.dim_countries
|
|
58
|
+
size_gb: 0.002
|
|
59
|
+
row_count: 249
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@click.group()
|
|
64
|
+
@click.version_option(version=__version__, prog_name="bqguard")
|
|
65
|
+
def main() -> None:
|
|
66
|
+
"""bqguard — SQL & dbt FinOps and Performance Guardrail (BigQuery, Snowflake, Databricks)."""
|
|
67
|
+
colorama_init()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@main.command()
|
|
71
|
+
@click.argument("paths", nargs=-1, type=click.Path(exists=True))
|
|
72
|
+
@click.option(
|
|
73
|
+
"-c",
|
|
74
|
+
"--config",
|
|
75
|
+
"config_path",
|
|
76
|
+
type=click.Path(exists=True),
|
|
77
|
+
default=None,
|
|
78
|
+
help="Path to bqguard.yaml configuration file.",
|
|
79
|
+
)
|
|
80
|
+
@click.option(
|
|
81
|
+
"-d",
|
|
82
|
+
"--dialect",
|
|
83
|
+
type=click.Choice(["bigquery", "snowflake", "databricks"], case_sensitive=False),
|
|
84
|
+
default=None,
|
|
85
|
+
help="Target SQL warehouse dialect (overrides bqguard.yaml).",
|
|
86
|
+
)
|
|
87
|
+
@click.option(
|
|
88
|
+
"-m",
|
|
89
|
+
"--metadata",
|
|
90
|
+
"metadata_path",
|
|
91
|
+
type=click.Path(exists=True),
|
|
92
|
+
default=None,
|
|
93
|
+
help="Path to offline table metadata YAML/JSON snapshot.",
|
|
94
|
+
)
|
|
95
|
+
@click.option(
|
|
96
|
+
"--baseline",
|
|
97
|
+
"baseline_path",
|
|
98
|
+
type=click.Path(exists=True),
|
|
99
|
+
default=None,
|
|
100
|
+
help="Path to a bqguard baseline JSON file (suppresses legacy findings, blocks only new ones).",
|
|
101
|
+
)
|
|
102
|
+
@click.option(
|
|
103
|
+
"--dbt-dir",
|
|
104
|
+
type=click.Path(exists=True),
|
|
105
|
+
default=None,
|
|
106
|
+
help="Path to a compiled dbt project root (or target/ directory).",
|
|
107
|
+
)
|
|
108
|
+
@click.option(
|
|
109
|
+
"--dbt-model",
|
|
110
|
+
"dbt_models",
|
|
111
|
+
multiple=True,
|
|
112
|
+
help="Filter specific dbt model name(s) to check (repeatable).",
|
|
113
|
+
)
|
|
114
|
+
@click.option(
|
|
115
|
+
"--changed-only",
|
|
116
|
+
is_flag=True,
|
|
117
|
+
default=False,
|
|
118
|
+
help="Only inspect SQL files / dbt models modified in git (working tree or vs --base-ref).",
|
|
119
|
+
)
|
|
120
|
+
@click.option(
|
|
121
|
+
"--base-ref",
|
|
122
|
+
default=None,
|
|
123
|
+
help="Git base ref for --changed-only diff (e.g., origin/main). Implies --changed-only.",
|
|
124
|
+
)
|
|
125
|
+
@click.option(
|
|
126
|
+
"--fix",
|
|
127
|
+
is_flag=True,
|
|
128
|
+
default=False,
|
|
129
|
+
help="Automatically apply safe AST fixes (BQ003 SARGable ranges, BQ005 CTE ORDER BY) to .sql files.",
|
|
130
|
+
)
|
|
131
|
+
@click.option(
|
|
132
|
+
"--fix-dry-run",
|
|
133
|
+
is_flag=True,
|
|
134
|
+
default=False,
|
|
135
|
+
help="Preview unified diffs for safe auto-fixes without modifying files on disk.",
|
|
136
|
+
)
|
|
137
|
+
@click.option(
|
|
138
|
+
"--dry-run",
|
|
139
|
+
is_flag=True,
|
|
140
|
+
default=False,
|
|
141
|
+
help="Run BigQuery Dry Run API (free) to estimate exact bytes scanned and USD cost.",
|
|
142
|
+
)
|
|
143
|
+
@click.option("--project", "gcp_project", default=None, help="GCP project ID for BigQuery dry-run.")
|
|
144
|
+
@click.option("--max-cost-usd", type=float, default=None, help="Override max allowed USD cost per query.")
|
|
145
|
+
@click.option("--max-gb", type=float, default=None, help="Override max allowed GB scanned per query.")
|
|
146
|
+
@click.option(
|
|
147
|
+
"--fail-on",
|
|
148
|
+
type=click.Choice(["error", "warning"], case_sensitive=False),
|
|
149
|
+
default=None,
|
|
150
|
+
help="Exit non-zero on errors only (default) or on warnings too.",
|
|
151
|
+
)
|
|
152
|
+
@click.option(
|
|
153
|
+
"-f",
|
|
154
|
+
"--format",
|
|
155
|
+
"output_format",
|
|
156
|
+
type=click.Choice(["terminal", "markdown", "json", "sarif"], case_sensitive=False),
|
|
157
|
+
default="terminal",
|
|
158
|
+
show_default=True,
|
|
159
|
+
help="Report output format.",
|
|
160
|
+
)
|
|
161
|
+
@click.option(
|
|
162
|
+
"-o",
|
|
163
|
+
"--output",
|
|
164
|
+
"output_file",
|
|
165
|
+
type=click.Path(),
|
|
166
|
+
default=None,
|
|
167
|
+
help="Write formatted report to a file (e.g., pr-comment.md).",
|
|
168
|
+
)
|
|
169
|
+
@click.option("--no-color", is_flag=True, default=False, help="Disable ANSI color codes.")
|
|
170
|
+
def check(
|
|
171
|
+
paths: tuple[str, ...],
|
|
172
|
+
config_path: str | None,
|
|
173
|
+
dialect: str | None,
|
|
174
|
+
metadata_path: str | None,
|
|
175
|
+
baseline_path: str | None,
|
|
176
|
+
dbt_dir: str | None,
|
|
177
|
+
dbt_models: tuple[str, ...],
|
|
178
|
+
changed_only: bool,
|
|
179
|
+
base_ref: str | None,
|
|
180
|
+
fix: bool,
|
|
181
|
+
fix_dry_run: bool,
|
|
182
|
+
dry_run: bool,
|
|
183
|
+
gcp_project: str | None,
|
|
184
|
+
max_cost_usd: float | None,
|
|
185
|
+
max_gb: float | None,
|
|
186
|
+
fail_on: str | None,
|
|
187
|
+
output_format: str,
|
|
188
|
+
output_file: str | None,
|
|
189
|
+
no_color: bool,
|
|
190
|
+
) -> None:
|
|
191
|
+
"""Analyze SQL files and/or a compiled dbt project for cost & performance risks."""
|
|
192
|
+
use_changed_only = changed_only or bool(base_ref)
|
|
193
|
+
if not paths and not dbt_dir and not use_changed_only:
|
|
194
|
+
raise click.UsageError(
|
|
195
|
+
"Provide at least one SQL file/directory path, `--dbt-dir`, or `--changed-only`."
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
cfg: BQGuardConfig = load_config(config_path)
|
|
199
|
+
if dialect:
|
|
200
|
+
cfg.dialect = dialect.lower() # type: ignore[assignment]
|
|
201
|
+
if fail_on:
|
|
202
|
+
cfg.fail_on = fail_on.lower() # type: ignore[assignment]
|
|
203
|
+
if gcp_project:
|
|
204
|
+
cfg.cost.project_id = gcp_project
|
|
205
|
+
if max_cost_usd is not None:
|
|
206
|
+
cfg.cost.max_cost_usd = max_cost_usd
|
|
207
|
+
if max_gb is not None:
|
|
208
|
+
cfg.cost.max_gb_scanned = max_gb
|
|
209
|
+
|
|
210
|
+
fix_mode: Literal["off", "dry-run", "apply"] = (
|
|
211
|
+
"dry-run" if fix_dry_run else ("apply" if fix else "off")
|
|
212
|
+
)
|
|
213
|
+
req = CheckRequest(
|
|
214
|
+
paths=list(paths),
|
|
215
|
+
dbt_dir=dbt_dir,
|
|
216
|
+
dbt_models=set(dbt_models) if dbt_models else None,
|
|
217
|
+
metadata_path=metadata_path,
|
|
218
|
+
baseline_path=baseline_path,
|
|
219
|
+
changed_only=use_changed_only,
|
|
220
|
+
base_ref=base_ref,
|
|
221
|
+
fix=fix_mode,
|
|
222
|
+
dry_run_cost=dry_run,
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
try:
|
|
226
|
+
outcome = run_check(cfg, req)
|
|
227
|
+
except BQGuardError as exc:
|
|
228
|
+
raise click.ClickException(str(exc)) from exc
|
|
229
|
+
|
|
230
|
+
if outcome.summary.total_queries == 0:
|
|
231
|
+
click.echo("No matching SQL queries found to analyze.")
|
|
232
|
+
sys.exit(0)
|
|
233
|
+
|
|
234
|
+
if fix_mode != "off":
|
|
235
|
+
cyan = "" if no_color else Fore.CYAN
|
|
236
|
+
green = "" if no_color else Fore.GREEN
|
|
237
|
+
reset = "" if no_color else Style.RESET_ALL
|
|
238
|
+
any_fix = False
|
|
239
|
+
for res in outcome.fix_results:
|
|
240
|
+
if not res.changed:
|
|
241
|
+
continue
|
|
242
|
+
any_fix = True
|
|
243
|
+
mode_label = "DRY-RUN FIX" if fix_mode == "dry-run" else "FIXED"
|
|
244
|
+
click.echo(f"{cyan}[{mode_label}]{reset} {res.source_path}")
|
|
245
|
+
for change in res.changes:
|
|
246
|
+
click.echo(f" {green}+{reset} {change}")
|
|
247
|
+
if fix_mode == "dry-run":
|
|
248
|
+
click.echo(res.unified_diff())
|
|
249
|
+
if not any_fix:
|
|
250
|
+
click.echo("No auto-fixable issues (BQ003/BQ005) found.")
|
|
251
|
+
|
|
252
|
+
fmt = output_format.lower()
|
|
253
|
+
if fmt == "markdown":
|
|
254
|
+
rendered = render_markdown(outcome.summary)
|
|
255
|
+
elif fmt == "json":
|
|
256
|
+
rendered = render_json(outcome.summary)
|
|
257
|
+
elif fmt == "sarif":
|
|
258
|
+
rendered = render_sarif(outcome.summary)
|
|
259
|
+
else:
|
|
260
|
+
rendered = render_terminal(outcome.summary, use_color=not no_color)
|
|
261
|
+
|
|
262
|
+
if output_file:
|
|
263
|
+
out_path = Path(output_file)
|
|
264
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
265
|
+
out_path.write_text(rendered, encoding="utf-8")
|
|
266
|
+
click.echo(f"Report written to {out_path}")
|
|
267
|
+
else:
|
|
268
|
+
click.echo(rendered)
|
|
269
|
+
|
|
270
|
+
sys.exit(0 if outcome.summary.passed else 1)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
@main.command()
|
|
274
|
+
@click.option(
|
|
275
|
+
"--dir",
|
|
276
|
+
"target_dir",
|
|
277
|
+
type=click.Path(),
|
|
278
|
+
default=".",
|
|
279
|
+
show_default=True,
|
|
280
|
+
help="Directory where starter bqguard.yaml and metadata.yaml will be created.",
|
|
281
|
+
)
|
|
282
|
+
@click.option("--force", is_flag=True, default=False, help="Overwrite existing starter files.")
|
|
283
|
+
def init(target_dir: str, force: bool) -> None:
|
|
284
|
+
"""Create starter bqguard.yaml and metadata.yaml files."""
|
|
285
|
+
base = Path(target_dir)
|
|
286
|
+
base.mkdir(parents=True, exist_ok=True)
|
|
287
|
+
|
|
288
|
+
files = {
|
|
289
|
+
base / "bqguard.yaml": STARTER_CONFIG_YAML,
|
|
290
|
+
base / "metadata.yaml": STARTER_METADATA_YAML,
|
|
291
|
+
}
|
|
292
|
+
for path, content in files.items():
|
|
293
|
+
if path.exists() and not force:
|
|
294
|
+
click.echo(f"Skipped existing file: {path} (use --force to overwrite)")
|
|
295
|
+
continue
|
|
296
|
+
path.write_text(content, encoding="utf-8")
|
|
297
|
+
click.echo(f"Created {path}")
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
@main.command("sync-sql")
|
|
301
|
+
@click.option(
|
|
302
|
+
"--dataset",
|
|
303
|
+
required=True,
|
|
304
|
+
help="Target dataset/schema (BigQuery: project.dataset, Snowflake: DB.SCHEMA, Databricks: catalog.schema).",
|
|
305
|
+
)
|
|
306
|
+
@click.option(
|
|
307
|
+
"-d",
|
|
308
|
+
"--dialect",
|
|
309
|
+
type=click.Choice(["bigquery", "snowflake", "databricks"], case_sensitive=False),
|
|
310
|
+
default="bigquery",
|
|
311
|
+
show_default=True,
|
|
312
|
+
help="Target warehouse dialect.",
|
|
313
|
+
)
|
|
314
|
+
def sync_sql(dataset: str, dialect: str) -> None:
|
|
315
|
+
"""Print a safe INFORMATION_SCHEMA query to refresh your offline metadata.yaml."""
|
|
316
|
+
click.echo(generate_metadata_sync_sql(dataset, dialect=dialect))
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
@main.command("rules")
|
|
320
|
+
def list_rules() -> None:
|
|
321
|
+
"""List all built-in cost and performance rules."""
|
|
322
|
+
click.echo("Built-in bqguard rules:\n")
|
|
323
|
+
for spec in RULE_SPECS:
|
|
324
|
+
tag = " [auto-fix]" if spec.autofix else ""
|
|
325
|
+
click.echo(f" {spec.id} ({spec.name}){tag}")
|
|
326
|
+
click.echo(f" {spec.description}")
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
@main.command("baseline")
|
|
330
|
+
@click.argument("paths", nargs=-1, type=click.Path(exists=True))
|
|
331
|
+
@click.option("-c", "--config", "config_path", type=click.Path(exists=True), default=None)
|
|
332
|
+
@click.option(
|
|
333
|
+
"-d",
|
|
334
|
+
"--dialect",
|
|
335
|
+
type=click.Choice(["bigquery", "snowflake", "databricks"], case_sensitive=False),
|
|
336
|
+
default=None,
|
|
337
|
+
)
|
|
338
|
+
@click.option("-m", "--metadata", "metadata_path", type=click.Path(exists=True), default=None)
|
|
339
|
+
@click.option("--dbt-dir", type=click.Path(exists=True), default=None)
|
|
340
|
+
@click.option(
|
|
341
|
+
"-o",
|
|
342
|
+
"--output",
|
|
343
|
+
"output_file",
|
|
344
|
+
type=click.Path(),
|
|
345
|
+
default=".bqguard-baseline.json",
|
|
346
|
+
show_default=True,
|
|
347
|
+
help="Output path for the generated baseline JSON file.",
|
|
348
|
+
)
|
|
349
|
+
def generate_baseline(
|
|
350
|
+
paths: tuple[str, ...],
|
|
351
|
+
config_path: str | None,
|
|
352
|
+
dialect: str | None,
|
|
353
|
+
metadata_path: str | None,
|
|
354
|
+
dbt_dir: str | None,
|
|
355
|
+
output_file: str,
|
|
356
|
+
) -> None:
|
|
357
|
+
"""Snapshot current violations into a baseline file so CI blocks only newly introduced issues."""
|
|
358
|
+
if not paths and not dbt_dir:
|
|
359
|
+
raise click.UsageError("Provide at least one SQL file/directory path or `--dbt-dir`.")
|
|
360
|
+
|
|
361
|
+
cfg = load_config(config_path)
|
|
362
|
+
if dialect:
|
|
363
|
+
cfg.dialect = dialect.lower() # type: ignore[assignment]
|
|
364
|
+
|
|
365
|
+
req = CheckRequest(paths=list(paths), dbt_dir=dbt_dir, metadata_path=metadata_path)
|
|
366
|
+
try:
|
|
367
|
+
outcome = run_check(cfg, req)
|
|
368
|
+
except BQGuardError as exc:
|
|
369
|
+
raise click.ClickException(str(exc)) from exc
|
|
370
|
+
|
|
371
|
+
baseline = save_baseline(outcome.summary, output_file)
|
|
372
|
+
total = sum(e.count for e in baseline.entries)
|
|
373
|
+
click.echo(f"Baseline written to {output_file} ({total} finding(s) across {len(baseline.entries)} fingerprint(s)).")
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
@main.command("ui")
|
|
377
|
+
@click.option("--host", default="127.0.0.1", show_default=True, help="Host interface to bind.")
|
|
378
|
+
@click.option("--port", type=int, default=8765, show_default=True, help="Local port for the playground.")
|
|
379
|
+
@click.option("--no-open", is_flag=True, default=False, help="Do not automatically open the browser.")
|
|
380
|
+
def web_ui(host: str, port: int, no_open: bool) -> None:
|
|
381
|
+
"""Launch the local interactive SQL Cost & Performance Web Playground."""
|
|
382
|
+
from bqguard.web.server import run_web_ui
|
|
383
|
+
|
|
384
|
+
run_web_ui(host=host, port=port, open_browser=not no_open)
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
if __name__ == "__main__":
|
|
388
|
+
main()
|
bqguard/config.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Configuration schema and loader for bqguard.yaml."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Literal
|
|
7
|
+
|
|
8
|
+
import yaml
|
|
9
|
+
from pydantic import BaseModel, Field
|
|
10
|
+
|
|
11
|
+
from bqguard.models import Severity
|
|
12
|
+
from bqguard.rules.specs import RULE_SPECS
|
|
13
|
+
|
|
14
|
+
DEFAULT_RULE_SEVERITIES: dict[str, Severity] = {
|
|
15
|
+
spec.id: spec.default_severity for spec in RULE_SPECS
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class CostConfig(BaseModel):
|
|
20
|
+
"""BigQuery pricing and dry-run budget thresholds."""
|
|
21
|
+
|
|
22
|
+
price_per_tb_usd: float = Field(default=6.25, gt=0)
|
|
23
|
+
max_cost_usd: float | None = Field(default=5.0, ge=0)
|
|
24
|
+
warn_cost_usd: float | None = Field(default=1.0, ge=0)
|
|
25
|
+
max_gb_scanned: float | None = Field(default=None, ge=0)
|
|
26
|
+
project_id: str | None = None
|
|
27
|
+
location: str | None = None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
SupportedDialect = Literal["bigquery", "snowflake", "databricks"]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class BQGuardConfig(BaseModel):
|
|
34
|
+
"""Top-level configuration for bqguard."""
|
|
35
|
+
|
|
36
|
+
dialect: SupportedDialect = "bigquery"
|
|
37
|
+
min_table_size_gb: float = Field(default=1.0, ge=0.0)
|
|
38
|
+
max_metadata_age_days: int | None = Field(default=30, ge=1)
|
|
39
|
+
fail_on_stale_metadata: bool = False
|
|
40
|
+
fail_on: Literal["error", "warning"] = "error"
|
|
41
|
+
metadata_path: str | None = None
|
|
42
|
+
rules: dict[str, Severity] = Field(default_factory=lambda: dict(DEFAULT_RULE_SEVERITIES))
|
|
43
|
+
cost: CostConfig = Field(default_factory=CostConfig)
|
|
44
|
+
ignore_paths: list[str] = Field(
|
|
45
|
+
default_factory=lambda: [".git", ".venv", "venv", "node_modules", "__pycache__"]
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
def get_rule_severity(self, rule_id: str, default: Severity = Severity.WARNING) -> Severity:
|
|
49
|
+
return self.rules.get(rule_id.upper(), DEFAULT_RULE_SEVERITIES.get(rule_id.upper(), default))
|
|
50
|
+
|
|
51
|
+
def is_rule_enabled(self, rule_id: str) -> bool:
|
|
52
|
+
return self.get_rule_severity(rule_id) != Severity.OFF
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def load_config(config_path: str | Path | None = None) -> BQGuardConfig:
|
|
56
|
+
"""Load bqguard configuration from YAML, falling back to defaults."""
|
|
57
|
+
resolved: Path | None = None
|
|
58
|
+
if config_path is not None:
|
|
59
|
+
resolved = Path(config_path)
|
|
60
|
+
if not resolved.exists():
|
|
61
|
+
raise FileNotFoundError(f"Config file not found: {resolved}")
|
|
62
|
+
else:
|
|
63
|
+
for candidate in ("bqguard.yaml", "bqguard.yml", ".bqguard.yaml", ".bqguard.yml"):
|
|
64
|
+
p = Path(candidate)
|
|
65
|
+
if p.exists():
|
|
66
|
+
resolved = p
|
|
67
|
+
break
|
|
68
|
+
|
|
69
|
+
if resolved is None:
|
|
70
|
+
return BQGuardConfig()
|
|
71
|
+
|
|
72
|
+
raw = yaml.safe_load(resolved.read_text(encoding="utf-8")) or {}
|
|
73
|
+
if not isinstance(raw, dict):
|
|
74
|
+
raise ValueError(f"Invalid config format in {resolved}: expected a YAML mapping.")
|
|
75
|
+
|
|
76
|
+
merged_rules = dict(DEFAULT_RULE_SEVERITIES)
|
|
77
|
+
if "rules" in raw and isinstance(raw["rules"], dict):
|
|
78
|
+
for k, v in raw["rules"].items():
|
|
79
|
+
merged_rules[str(k).upper()] = Severity(str(v).lower())
|
|
80
|
+
raw["rules"] = merged_rules
|
|
81
|
+
|
|
82
|
+
cfg = BQGuardConfig.model_validate(raw)
|
|
83
|
+
if cfg.metadata_path:
|
|
84
|
+
meta_p = Path(cfg.metadata_path)
|
|
85
|
+
if not meta_p.is_absolute():
|
|
86
|
+
rel_to_cfg = resolved.parent / meta_p
|
|
87
|
+
if rel_to_cfg.exists():
|
|
88
|
+
cfg.metadata_path = str(rel_to_cfg)
|
|
89
|
+
return cfg
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""AST parsing, rule execution, and surgical auto-fix engine for bqguard."""
|
|
2
|
+
|
|
3
|
+
from bqguard.engine import patching
|
|
4
|
+
from bqguard.engine.fixer import FixResult, SQLAutoFixer
|
|
5
|
+
from bqguard.engine.parser import ParsedQuery, parse_bigquery_sql, parse_sql
|
|
6
|
+
from bqguard.engine.runner import AnalysisEngine
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"AnalysisEngine",
|
|
10
|
+
"FixResult",
|
|
11
|
+
"ParsedQuery",
|
|
12
|
+
"SQLAutoFixer",
|
|
13
|
+
"parse_bigquery_sql",
|
|
14
|
+
"parse_sql",
|
|
15
|
+
"patching",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
|