Metadata-Version: 2.4
Name: bqguard
Version: 0.5.0
Summary: BigQuery-first, metadata-aware SQL & dbt FinOps guardrail (with Snowflake and Databricks AST support).
Author: Ahmed Gomaa
License: MIT
Project-URL: Homepage, https://github.com/Ahmed-Gomaa1/bqguard
Project-URL: Repository, https://github.com/Ahmed-Gomaa1/bqguard
Project-URL: Issues, https://github.com/Ahmed-Gomaa1/bqguard/issues
Project-URL: Documentation, https://github.com/Ahmed-Gomaa1/bqguard/blob/main/docs/ARCHITECTURE.md
Keywords: bigquery,snowflake,databricks,sql,dbt,finops,linter,sqlglot,sarif
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Database
Classifier: Topic :: Software Development :: Quality Assurance
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: sqlglot>=25.0.0
Requires-Dist: click>=8.1.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: pyyaml>=6.0.0
Requires-Dist: colorama>=0.4.6
Requires-Dist: tabulate>=0.9.0
Provides-Extra: bigquery
Requires-Dist: google-cloud-bigquery>=3.20.0; extra == "bigquery"
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-cov>=5.0.0; extra == "dev"
Dynamic: license-file

# bqguard

[![PyPI version](https://img.shields.io/pypi/v/bqguard.svg)](https://pypi.org/project/bqguard/)
[![CI Tests](https://github.com/Ahmed-Gomaa1/bqguard/actions/workflows/ci.yml/badge.svg)](https://github.com/Ahmed-Gomaa1/bqguard/actions/workflows/ci.yml)
[![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)

**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?](#why-bqguard)
- [Real-World Example](#real-world-example)
- [Architecture](#architecture)
- [Installation](#installation)
- [Quickstart](#quickstart)
- [CLI Reference](#cli-reference)
- [Configuration & Offline Metadata](#configuration--offline-metadata)
- [Built-in Rules](#built-in-rules)
- [Dialect Compatibility Matrix](#dialect-compatibility-matrix)
- [CI/CD & Tooling Integration](#cicd--tooling-integration)
- [Local Web Playground](#local-web-playground)
- [How bqguard Compares](#how-bqguard-compares)
- [Known Limitations & Roadmap](#known-limitations--roadmap)
- [Development & Testing](#development--testing)
- [License](#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.yaml` snapshot (or `dbt 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`, and `LATERAL VIEW EXPLODE`.
- **Type-Safe & Timezone-Safe Surgical Auto-Fix (`--fix`):** Patches only the exact token byte spans of offending predicates and CTE `ORDER BY` clauses—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`):

```sql
-- 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:

```diff
--- 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:

```mermaid
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](docs/ARCHITECTURE.md).

---

## Installation

**Requirements:** Python `3.10+`

```bash
# 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:

```bash
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:

```bash
python run_bqguard.py check examples/sql --metadata examples/metadata.yaml
```

---

## Quickstart

```bash
# 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`

```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)

```yaml
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:

```bash
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:

```sql
-- bqguard: ignore=BQ006
SELECT event_id FROM table_a
UNION DISTINCT
SELECT event_id FROM table_b
```

---

## Built-in Rules

| 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 (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`–`BQ007`) | 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:

```yaml
- 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](.github/workflows/bqguard-pr.yml).

### 2. GitHub Code Scanning (SARIF 2.1.0)
Upload SARIF findings directly to GitHub's **Security / Files changed** annotations:

```yaml
- 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`:

```yaml
repos:
  - repo: https://github.com/Ahmed-Gomaa1/bqguard
    rev: v0.4.0
    hooks:
      - id: bqguard
        args: ["--metadata", "metadata.yaml"]
```

---

## Local Web Playground

Run an interactive browser UI with built-in BigQuery, Snowflake, and Databricks presets, live metadata editing, PR Markdown preview, and surgical Auto-Fix diffs:

```bash
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.JOBS` Roadmap):** `bqguard` is a preventive static/dry-run check before execution and does not inspect live runtime execution plans; integrating historical cost feedback from `INFORMATION_SCHEMA.JOBS` is on the roadmap.
- **Databricks `sync-sql` Sizes:** Unity Catalog `information_schema.tables` does not expose table byte sizes directly (pair with `DESCRIBE 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

```bash
# Run the full test suite (40 tests covering AST rules, surgical patching, dbt, git, baseline, SARIF, and Web UI)
pytest -v
```

CI runs automatically via [.github/workflows/ci.yml](.github/workflows/ci.yml) across Python `3.10`, `3.11`, `3.12`, and `3.13`.

---

## License

MIT — see [LICENSE](LICENSE).
