bqguard
BigQuery-first, metadata-aware SQL & dbt FinOps guardrail (with Snowflake and Databricks SQL static AST support) — built for local development, pre-commit, GitHub Code Scanning (SARIF), and CI/CD Pull Requests.
bqguard is a preventive, pre-execution guardrail: it catches expensive analytical SQL anti-patterns and broken partition pruning before code merges into production or runs against your warehouse. By default, static checks run completely offline with zero production credentials; optional --dry-run cost enforcement uses read-only BigQuery dry-run permissions when explicitly enabled.
Table of Contents
- Why bqguard?
- Real-World Example
- Architecture
- Installation
- Quickstart
- CLI Reference
- Configuration & Offline Metadata
- Built-in Rules
- Dialect Compatibility Matrix
- CI/CD & Tooling Integration
- Local Web Playground
- How bqguard Compares
- Known Limitations & Roadmap
- Development & Testing
- License
Why bqguard?
Traditional SQL linters check formatting and style, but cannot tell a 2 MB lookup table from a 4.5 TB partitioned event table. Meanwhile, cloud FinOps dashboards only alert after an expensive query has already run in production.
bqguard bridges that gap at Pull Request time:
- Metadata-Aware with Offline CI by Default: Reads an offline
metadata.yamlsnapshot (ordbt catalog.json) containing only table sizes,partition_data_type, and partition/cluster keys—zero customer rows, zero PII, zero prod credentials in default CI, and built-in freshness TTL warnings (max_metadata_age_days). - AST-Powered (
sqlglot) with Exact Line Numbers: Understands CTEs, table aliases, subqueries, and dialect-specific syntax—ignoring small tables,COUNT(*),UNNEST,LATERAL FLATTEN, andLATERAL VIEW EXPLODE. - Type-Safe & Timezone-Safe Surgical Auto-Fix (
--fix): Patches only the exact token byte spans of offending predicates and CTEORDER BYclauses—preserving--comments, indentation, backticks, and;—verifies AST equivalence before accepting a patch, and skips timezone-shifted expressions (DATE(ts, 'tz'),AT TIME ZONE). - Incremental Adoption via Baselines (
--baseline): Snapshot legacy findings with line-independent fingerprints so existing repositories can block new cost regressions on day one. - Enterprise CI Ready: Outputs Terminal, GitHub PR Markdown comments, JSON, and SARIF 2.1.0 for GitHub Code Scanning, plus optional free BigQuery Dry Run byte/USD enforcement (
--dry-run, requiring read-only BigQuery job/metadata credentials only when enabled).
Real-World Example
Consider an hourly BigQuery query against a 4.5 TB table (prod.analytics.user_events, partitioned by event_timestamp) and a 2 MB lookup table (prod.analytics.dim_countries):
-- examples/sql/bad_hourly_checkouts.sql
WITH sorted_events AS (
SELECT
e.*,
c.country_name
FROM `prod.analytics.user_events` e
JOIN `prod.analytics.dim_countries` c
ON e.country_code = c.code
WHERE EXTRACT(YEAR FROM e.event_timestamp) = 2026
AND e.event_name LIKE '%checkout'
ORDER BY e.event_timestamp DESC
)
SELECT
event_id,
user_id,
event_timestamp,
country_name
FROM sorted_events
UNION DISTINCT
SELECT
event_id,
user_id,
event_timestamp,
country_name
FROM `prod.analytics.legacy_checkouts`
Without a guardrail, EXTRACT(YEAR FROM e.event_timestamp) disables partition pruning and SELECT * inside the CTE scans every column—billing 4.5 TB (~$28/run, ~$20,000/month) on an hourly schedule.
Running bqguard check examples/sql/bad_hourly_checkouts.sql --metadata examples/metadata.yaml --fix-dry-run catches every issue in under a second (while ignoring the 2 MB dim_countries table) and produces a surgical diff that preserves comments and formatting:
--- a/examples/sql/bad_hourly_checkouts.sql
+++ b/examples/sql/bad_hourly_checkouts.sql
@@ -4,9 +4,8 @@
FROM `prod.analytics.user_events` e
JOIN `prod.analytics.dim_countries` c
ON e.country_code = c.code
- WHERE EXTRACT(YEAR FROM e.event_timestamp) = 2026
+ WHERE e.event_timestamp >= '2026-01-01' AND e.event_timestamp < '2027-01-01'
AND e.event_name LIKE '%checkout'
- ORDER BY e.event_timestamp DESC
)
SELECT
event_id,
Architecture
bqguard uses a layered architecture where both the CLI and local Web UI delegate to a single application service layer:
flowchart LR
CLI["CLI (cli.py)"] --> SVC["Service Layer (service.py)"]
WEB["Web UI (web/server.py + static/index.html)"] --> SVC
SVC --> LOADERS["Loaders: sql / dbt / git / metadata"]
SVC --> ENGINE["Engine: parser / runner / fixer + patching"]
SVC --> BASELINE["Baseline Fingerprinting (baseline.py)"]
ENGINE --> RULES["Rules: specs / helpers / builtin"]
ENGINE --> EST["Estimators: bigquery_dryrun"]
SVC --> REP["Reporters: terminal / markdown / json / sarif"]
For full module responsibilities and design rationale, see docs/ARCHITECTURE.md.
Installation
Requirements: Python 3.10+
# Install directly from PyPI
pip install bqguard
# Optional: enable live BigQuery Dry Run cost estimation (--dry-run)
pip install "bqguard[bigquery]"
For local development from source:
git clone https://github.com/Ahmed-Gomaa1/bqguard.git
cd bqguard
pip install -e ".[dev]"
No-install option: You can also run directly from the repository root without installing:
python run_bqguard.py check examples/sql --metadata examples/metadata.yaml
Quickstart
# 1. Scaffold starter bqguard.yaml and metadata.yaml in your project
bqguard init
# 2. Check SQL files against your offline metadata snapshot
bqguard check examples/sql --metadata examples/metadata.yaml
# 3. Preview surgical auto-fixes (unified diff, no files modified)
bqguard check examples/sql/bad_hourly_checkouts.sql --metadata examples/metadata.yaml --fix-dry-run
# 4. Apply surgical auto-fixes in place
bqguard check path/to/query.sql --metadata metadata.yaml --fix
# 5. Check a compiled dbt project and generate a GitHub PR Markdown report
bqguard check --dbt-dir examples/dbt_project --format markdown
# 6. Snapshot existing violations into a baseline, then fail only on NEW violations
bqguard baseline examples/sql --metadata examples/metadata.yaml -o .bqguard-baseline.json
bqguard check examples/sql --metadata examples/metadata.yaml --baseline .bqguard-baseline.json
# 7. Launch the local interactive Web Playground
bqguard ui --port 8765
CLI Reference
| Command | Description |
|---|---|
bqguard check [PATHS...] |
Analyze raw .sql files and/or compiled dbt models for cost & performance violations. |
bqguard baseline [PATHS...] |
Snapshot current violations into a line-independent JSON baseline file. |
bqguard sync-sql --dataset <NAME> |
Print a safe, read-only INFORMATION_SCHEMA query to refresh metadata.yaml. |
bqguard init |
Create starter bqguard.yaml and metadata.yaml files. |
bqguard rules |
List all built-in rules (BQ001–BQ008) and mark [auto-fix] capabilities. |
bqguard ui |
Launch the local interactive SQL playground bound to 127.0.0.1. |
Key bqguard check Options
| Option | Default | Description |
|---|---|---|
-c, --config <PATH> |
auto-detect | Path to bqguard.yaml (auto-discovers bqguard.yaml / .bqguard.yaml). |
-d, --dialect <NAME> |
bigquery |
Target warehouse dialect: bigquery, snowflake, or databricks. |
--preset <NAME> |
balanced |
Apply built-in strictness preset: strict, balanced, or lenient. |
-m, --metadata <PATH> |
from config | Path to offline table metadata YAML/JSON snapshot. |
--dbt-dir <PATH> |
— | Path to a compiled dbt project root (or target/ directory). |
--dbt-model <NAME> |
all | Restrict dbt analysis to specific model name(s) (repeatable). |
--changed-only |
false |
Inspect only .sql files / dbt models modified in git. |
--base-ref <REF> |
— | Git base ref for PR diffs (e.g., origin/main). Implies --changed-only. |
--baseline <PATH> |
— | Suppress legacy findings recorded in a baseline JSON file. |
--fix / --fix-dry-run |
false |
Apply or preview safe surgical AST fixes (BQ003, BQ005). |
--dry-run |
false |
Run free BigQuery Dry Run API to estimate exact GB scanned & USD cost (BQ008). |
--max-cost-usd <FLOAT> |
5.0 |
Override maximum allowed USD cost per query in --dry-run mode. |
--max-gb <FLOAT> |
— | Override maximum allowed GB scanned per query in --dry-run mode. |
--fail-on <LEVEL> |
error |
Exit non-zero on error (default) or warning. |
-f, --format <FMT> |
terminal |
Output format: terminal, markdown, json, or sarif. |
-o, --output <PATH> |
stdout | Write formatted report to a file (e.g., bqguard.sarif or pr-comment.md). |
Configuration & Offline Metadata
bqguard.yaml
dialect: bigquery # bigquery | snowflake | databricks
min_table_size_gb: 1.0 # Tables smaller than this are skipped by high-cost rules
max_metadata_age_days: 30 # Warn when metadata snapshot exceeds this age
fail_on_stale_metadata: false
fail_on: error # error | warning
metadata_path: metadata.yaml # Resolved relative to this config file's directory
rules:
BQ001: error
BQ002: error
BQ003: error
BQ004: error
BQ005: warning
BQ006: warning
BQ007: warning
BQ008: error
cost:
price_per_tb_usd: 6.25
max_cost_usd: 5.0
warn_cost_usd: 1.0
# max_gb_scanned: 500
metadata.yaml (Offline Metadata Snapshot)
generated_at: "2026-12-03"
tables:
- name: prod.analytics.user_events
size_gb: 4500.0
row_count: 18500000000
partition_column: event_timestamp
partition_type: DAY
partition_data_type: TIMESTAMP # DATE | DATETIME | TIMESTAMP (used for type-safe --fix)
cluster_columns:
- country_code
- event_name
require_partition_filter: true
- name: prod.analytics.dim_countries
size_gb: 0.002
row_count: 249
Refresh your snapshot nightly without giving CI runners production access:
bqguard sync-sql --dataset prod.analytics --dialect bigquery
bqguard sync-sql --dataset PROD_DW.ANALYTICS --dialect snowflake
bqguard sync-sql --dataset main.lakehouse --dialect databricks
Inline Rule Suppression
Suppress an intentional pattern on the same line or the line immediately above:
-- bqguard: ignore=BQ006
SELECT event_id FROM table_a
UNION DISTINCT
SELECT event_id FROM table_b
Built-in Rules
See the full Rules Reference for bad/good SQL examples, false-positive safeguards, and suppression guides for every rule.
| Rule | Name | Default | Auto-Fix | Description & False-Positive Safeguards |
|---|---|---|---|---|
BQ001 |
no-select-star |
error |
— | Flags SELECT * on large columnar tables. Ignores COUNT(*), skips tables < min_table_size_gb, and downgrades to warning when table size is unknown. |
BQ002 |
missing-partition-filter |
error |
— | Flags queries reading large partitioned tables without a WHERE filter on the partition column (scope-based CTE lineage, per-instance UNION ALL / self-join checks, ignores JOIN ON-only references). |
BQ003 |
non-sargable-predicate |
error |
Yes | Flags functions, casts, or math wrapping partition/cluster columns (e.g., EXTRACT(YEAR FROM ts) = 2026, DATE(ts) = '...', TO_DATE(...)). Auto-fix is type-aware and skips timezone-shifted calls. |
BQ004 |
cross-join-risk |
error |
— | Flags unconditioned CROSS JOIN / comma joins. Explicitly allows UNNEST (BigQuery), LATERAL FLATTEN (Snowflake), and LATERAL VIEW (Databricks), and skips tiny broadcast tables (< 10 MB). |
BQ005 |
order-by-without-limit-in-cte |
warning |
Yes | Flags wasted ORDER BY without LIMIT inside CTEs or subqueries (does not touch window OVER (... ORDER BY ...) or ARRAY_AGG). |
BQ006 |
union-distinct-cost |
warning |
— | Flags UNION DISTINCT (BigQuery) / UNION (Snowflake, Databricks) where UNION ALL avoids expensive distributed deduplication. |
BQ007 |
leading-wildcard-like |
warning |
— | Flags leading wildcard LIKE '%...' patterns on clustered or large (>= 100 GB) table columns. |
BQ008 |
cost-threshold-exceeded |
error |
— | Flags queries whose free BigQuery Dry Run estimate exceeds max_cost_usd, max_gb_scanned, or warn_cost_usd. |
BQ009 |
limit-does-not-reduce-scan |
warning |
— | Warns when LIMIT is used on a large table without a WHERE filter (LIMIT does not reduce bytes billed in BigQuery). |
BQ010 |
dbt-incremental-missing-guard |
error |
— | Flags dbt models configured as materialized='incremental' that omit an is_incremental() guard. |
BQ011 |
repeated-cte-scan |
warning |
— | Warns when a CTE reading a large table is referenced multiple times (BigQuery may re-evaluate it per reference). |
Dialect Compatibility Matrix
bqguard is BigQuery-first, with static AST rule and auto-fix support for Snowflake and Databricks SQL:
| Capability | BigQuery | Snowflake | Databricks SQL |
|---|---|---|---|
Static AST rules (BQ001–BQ011, excl. BQ008) |
Full | Full | Full |
| Idiomatic array/table expansion allowed | UNNEST |
LATERAL FLATTEN |
LATERAL VIEW EXPLODE |
Surgical Auto-Fix (BQ003, BQ005) |
Full | Full (TO_DATE, YEAR) |
Full (YEAR, DATE) |
| Offline Metadata Snapshot + Freshness TTL | Full | Full | Full |
sync-sql metadata export query |
Full | Sizes + clustering_key |
Table list (pair with DESCRIBE DETAIL) |
Live Dry Run byte/USD cost check (BQ008) |
Full (free API) | — | — |
CI/CD & Tooling Integration
1. Official GitHub Action (action.yml)
Drop bqguard into any Pull Request workflow in a few lines:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: Ahmed-Gomaa1/bqguard@v0.5.0
with:
metadata: metadata.yaml
preset: balanced
changed-only: "true"
format: markdown
output: bqguard-report.md
A full PR-commenting workflow is also included in .github/workflows/bqguard-pr.yml.
2. GitHub Code Scanning (SARIF 2.1.0)
Upload SARIF findings directly to GitHub's Security / Files changed annotations:
- name: Run bqguard (SARIF)
continue-on-error: true
run: |
bqguard check --changed-only --base-ref "origin/${{ github.base_ref }}" \
--metadata metadata.yaml \
--format sarif \
--output bqguard.sarif
- name: Upload SARIF to GitHub Code Scanning
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: bqguard.sarif
3. pre-commit Hook
Add to your repository's .pre-commit-config.yaml:
repos:
- repo: https://github.com/Ahmed-Gomaa1/bqguard
rev: v0.5.0
hooks:
- id: bqguard
args: ["--metadata", "metadata.yaml"]
Local & Online Web Playground
Try bqguard directly in your browser with zero installation (100% client-side via Pyodide WebAssembly, hosted via GitHub Pages):
- Online Playground: docs/playground/index.html (
https://ahmed-gomaa1.github.io/bqguard/once GitHub Pages is enabled)
Or run the local interactive browser UI with built-in BigQuery, Snowflake, and Databricks presets, live metadata editing, PR Markdown preview, and surgical Auto-Fix diffs:
bqguard ui --port 8765
Security: By default, bqguard ui binds strictly to 127.0.0.1 (loopback only — never exposed to the local network) and rejects POST payloads larger than 1,000,000 bytes with HTTP 413.
How bqguard Compares
| Tool | Primary Focus | Metadata-Aware Table Sizes | Offline CI (No Prod Creds) | Surgical Cost Auto-Fix | Dry-Run Cost Gate |
|---|---|---|---|---|---|
| SQLFluff | SQL formatting & style linting | No | Yes | Style only | No |
| dbt-checkpoint | dbt schema, docs & test hygiene | No | Yes | No | No |
| bqguard | Warehouse cost & pruning guardrails | Yes (metadata.yaml / catalog.json) |
Yes | Yes (BQ003, BQ005) |
Yes (BigQuery) |
Known Limitations & Roadmap
- Per-Column Byte Sizes: BigQuery is columnar, so
SELECT *cost scales with column widths rather than total table size alone; adding optional per-column size metadata is planned. - Pre-Execution Only (
INFORMATION_SCHEMA.JOBSRoadmap):bqguardis a preventive static/dry-run check before execution and does not inspect live runtime execution plans; integrating historical cost feedback fromINFORMATION_SCHEMA.JOBSis on the roadmap. - Databricks
sync-sqlSizes: Unity Cataloginformation_schema.tablesdoes not expose table byte sizes directly (pair withDESCRIBE DETAIL <table>). - Dry-Run Estimation Scope: Live byte/USD cost estimation (
--dry-run/BQ008) is BigQuery-only; Snowflake/Databricks billing depends on warehouse uptime/DBUs rather than bytes scanned alone.
Development & Testing
# Run the full test suite (66 tests covering AST rules, warehouse adapters, Snowflake EXPLAIN pruning, PR cost diff, GitHub suggestions, surgical patching, dbt, git, baseline, SARIF, Golden Corpus, and Web UI)
pytest -v
CI runs automatically via .github/workflows/ci.yml across Python 3.10, 3.11, 3.12, and 3.13.
License
MIT — see LICENSE.
Metadata
Release files for bqguard 0.6.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| bqguard-0.6.0.tar.gz | 85.6 kB | With provenance | Details for bqguard-0.6.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| bqguard-0.6.0-py3-none-any.whl | Python 3 | none | any | Details for bqguard-0.6.0-py3-none-any.whl |
Total release size: 162.5 kB
Release files / bqguard-0.6.0.tar.gz
| Download URL | bqguard-0.6.0.tar.gz |
|---|---|
| Size | 85.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
54090b516a9fc3e2031b2204a69df21c478a356642aed2af3c6d57ee20be345b
|
|
BLAKE2b-256 checksum How to use checksums |
0bbd5d569623beaa03fb0d142fb2ee2b6adb707a73e86c2e8e1597812eac85b5
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.
Transparency logRelease files / bqguard-0.6.0-py3-none-any.whl
| Download URL | bqguard-0.6.0-py3-none-any.whl |
|---|---|
| Size | 76.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
f307d9a8ee3b5104e3f41a8f889c61cf4e8a7205703313299a4ff51e330c150b
|
|
BLAKE2b-256 checksum How to use checksums |
e7c42c6cfd9469e5da5d8052e29d8bc2621271189ae0feaabb71504e13ad56e8
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.
Transparency logSecurity for bqguard 0.6.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for bqguard-0.6.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.