bqguard 0.4.0__tar.gz

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.
Files changed (49) hide show
  1. bqguard-0.4.0/LICENSE +21 -0
  2. bqguard-0.4.0/PKG-INFO +434 -0
  3. bqguard-0.4.0/README.md +396 -0
  4. bqguard-0.4.0/pyproject.toml +57 -0
  5. bqguard-0.4.0/setup.cfg +4 -0
  6. bqguard-0.4.0/src/bqguard/__init__.py +4 -0
  7. bqguard-0.4.0/src/bqguard/__main__.py +6 -0
  8. bqguard-0.4.0/src/bqguard/baseline.py +132 -0
  9. bqguard-0.4.0/src/bqguard/cli.py +388 -0
  10. bqguard-0.4.0/src/bqguard/config.py +89 -0
  11. bqguard-0.4.0/src/bqguard/engine/__init__.py +18 -0
  12. bqguard-0.4.0/src/bqguard/engine/fixer.py +425 -0
  13. bqguard-0.4.0/src/bqguard/engine/parser.py +228 -0
  14. bqguard-0.4.0/src/bqguard/engine/patching.py +245 -0
  15. bqguard-0.4.0/src/bqguard/engine/runner.py +159 -0
  16. bqguard-0.4.0/src/bqguard/estimators/__init__.py +5 -0
  17. bqguard-0.4.0/src/bqguard/estimators/bigquery_dryrun.py +85 -0
  18. bqguard-0.4.0/src/bqguard/loaders/__init__.py +28 -0
  19. bqguard-0.4.0/src/bqguard/loaders/dbt_loader.py +175 -0
  20. bqguard-0.4.0/src/bqguard/loaders/git_loader.py +125 -0
  21. bqguard-0.4.0/src/bqguard/loaders/metadata_loader.py +155 -0
  22. bqguard-0.4.0/src/bqguard/loaders/sql_loader.py +65 -0
  23. bqguard-0.4.0/src/bqguard/models.py +247 -0
  24. bqguard-0.4.0/src/bqguard/reporters/__init__.py +8 -0
  25. bqguard-0.4.0/src/bqguard/reporters/json_reporter.py +23 -0
  26. bqguard-0.4.0/src/bqguard/reporters/markdown.py +84 -0
  27. bqguard-0.4.0/src/bqguard/reporters/sarif.py +96 -0
  28. bqguard-0.4.0/src/bqguard/reporters/terminal.py +92 -0
  29. bqguard-0.4.0/src/bqguard/rules/__init__.py +21 -0
  30. bqguard-0.4.0/src/bqguard/rules/base.py +76 -0
  31. bqguard-0.4.0/src/bqguard/rules/builtin.py +664 -0
  32. bqguard-0.4.0/src/bqguard/rules/helpers.py +135 -0
  33. bqguard-0.4.0/src/bqguard/rules/specs.py +74 -0
  34. bqguard-0.4.0/src/bqguard/service.py +220 -0
  35. bqguard-0.4.0/src/bqguard/web/__init__.py +5 -0
  36. bqguard-0.4.0/src/bqguard/web/server.py +234 -0
  37. bqguard-0.4.0/src/bqguard/web/static/index.html +237 -0
  38. bqguard-0.4.0/src/bqguard.egg-info/PKG-INFO +434 -0
  39. bqguard-0.4.0/src/bqguard.egg-info/SOURCES.txt +47 -0
  40. bqguard-0.4.0/src/bqguard.egg-info/dependency_links.txt +1 -0
  41. bqguard-0.4.0/src/bqguard.egg-info/entry_points.txt +2 -0
  42. bqguard-0.4.0/src/bqguard.egg-info/requires.txt +13 -0
  43. bqguard-0.4.0/src/bqguard.egg-info/top_level.txt +1 -0
  44. bqguard-0.4.0/tests/test_loaders_and_cli.py +116 -0
  45. bqguard-0.4.0/tests/test_refactor_v3.py +224 -0
  46. bqguard-0.4.0/tests/test_rules.py +287 -0
  47. bqguard-0.4.0/tests/test_v2_features.py +222 -0
  48. bqguard-0.4.0/tests/test_v4_trust_features.py +252 -0
  49. bqguard-0.4.0/tests/test_web_ui.py +84 -0
bqguard-0.4.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 bqguard contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
bqguard-0.4.0/PKG-INFO ADDED
@@ -0,0 +1,434 @@
1
+ Metadata-Version: 2.4
2
+ Name: bqguard
3
+ Version: 0.4.0
4
+ Summary: BigQuery-first, metadata-aware SQL & dbt FinOps guardrail (with Snowflake and Databricks AST support).
5
+ Author: Ahmed Gomaa
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/Ahmed-Gomaa1/bqguard
8
+ Project-URL: Repository, https://github.com/Ahmed-Gomaa1/bqguard
9
+ Project-URL: Issues, https://github.com/Ahmed-Gomaa1/bqguard/issues
10
+ Project-URL: Documentation, https://github.com/Ahmed-Gomaa1/bqguard/blob/main/docs/ARCHITECTURE.md
11
+ Keywords: bigquery,snowflake,databricks,sql,dbt,finops,linter,sqlglot,sarif
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Database
22
+ Classifier: Topic :: Software Development :: Quality Assurance
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: sqlglot>=25.0.0
27
+ Requires-Dist: click>=8.1.0
28
+ Requires-Dist: pydantic>=2.0.0
29
+ Requires-Dist: pyyaml>=6.0.0
30
+ Requires-Dist: colorama>=0.4.6
31
+ Requires-Dist: tabulate>=0.9.0
32
+ Provides-Extra: bigquery
33
+ Requires-Dist: google-cloud-bigquery>=3.20.0; extra == "bigquery"
34
+ Provides-Extra: dev
35
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
36
+ Requires-Dist: pytest-cov>=5.0.0; extra == "dev"
37
+ Dynamic: license-file
38
+
39
+ # bqguard
40
+
41
+ [![CI Tests](https://github.com/Ahmed-Gomaa1/bqguard/actions/workflows/ci.yml/badge.svg)](https://github.com/Ahmed-Gomaa1/bqguard/actions/workflows/ci.yml)
42
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/)
43
+ [![Version](https://img.shields.io/badge/version-0.4.0-informational.svg)](pyproject.toml)
44
+ [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
45
+
46
+ **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.
47
+
48
+ `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.
49
+
50
+ ---
51
+
52
+ ## Table of Contents
53
+
54
+ - [Why bqguard?](#why-bqguard)
55
+ - [Real-World Example](#real-world-example)
56
+ - [Architecture](#architecture)
57
+ - [Installation](#installation)
58
+ - [Quickstart](#quickstart)
59
+ - [CLI Reference](#cli-reference)
60
+ - [Configuration & Offline Metadata](#configuration--offline-metadata)
61
+ - [Built-in Rules](#built-in-rules)
62
+ - [Dialect Compatibility Matrix](#dialect-compatibility-matrix)
63
+ - [CI/CD & Tooling Integration](#cicd--tooling-integration)
64
+ - [Local Web Playground](#local-web-playground)
65
+ - [How bqguard Compares](#how-bqguard-compares)
66
+ - [Known Limitations & Roadmap](#known-limitations--roadmap)
67
+ - [Development & Testing](#development--testing)
68
+ - [License](#license)
69
+
70
+ ---
71
+
72
+ ## Why bqguard?
73
+
74
+ 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.
75
+
76
+ `bqguard` bridges that gap at Pull Request time:
77
+
78
+ - **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`).
79
+ - **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`.
80
+ - **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`).
81
+ - **Incremental Adoption via Baselines (`--baseline`):** Snapshot legacy findings with line-independent fingerprints so existing repositories can block **new** cost regressions on day one.
82
+ - **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).
83
+
84
+ ---
85
+
86
+ ## Real-World Example
87
+
88
+ 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`):
89
+
90
+ ```sql
91
+ -- examples/sql/bad_hourly_checkouts.sql
92
+ WITH sorted_events AS (
93
+ SELECT
94
+ e.*,
95
+ c.country_name
96
+ FROM `prod.analytics.user_events` e
97
+ JOIN `prod.analytics.dim_countries` c
98
+ ON e.country_code = c.code
99
+ WHERE EXTRACT(YEAR FROM e.event_timestamp) = 2026
100
+ AND e.event_name LIKE '%checkout'
101
+ ORDER BY e.event_timestamp DESC
102
+ )
103
+ SELECT
104
+ event_id,
105
+ user_id,
106
+ event_timestamp,
107
+ country_name
108
+ FROM sorted_events
109
+ UNION DISTINCT
110
+ SELECT
111
+ event_id,
112
+ user_id,
113
+ event_timestamp,
114
+ country_name
115
+ FROM `prod.analytics.legacy_checkouts`
116
+ ```
117
+
118
+ 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.
119
+
120
+ 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:
121
+
122
+ ```diff
123
+ --- a/examples/sql/bad_hourly_checkouts.sql
124
+ +++ b/examples/sql/bad_hourly_checkouts.sql
125
+ @@ -4,9 +4,8 @@
126
+ FROM `prod.analytics.user_events` e
127
+ JOIN `prod.analytics.dim_countries` c
128
+ ON e.country_code = c.code
129
+ - WHERE EXTRACT(YEAR FROM e.event_timestamp) = 2026
130
+ + WHERE e.event_timestamp >= '2026-01-01' AND e.event_timestamp < '2027-01-01'
131
+ AND e.event_name LIKE '%checkout'
132
+ - ORDER BY e.event_timestamp DESC
133
+ )
134
+ SELECT
135
+ event_id,
136
+ ```
137
+
138
+ ---
139
+
140
+ ## Architecture
141
+
142
+ `bqguard` uses a layered architecture where both the CLI and local Web UI delegate to a single application service layer:
143
+
144
+ ```mermaid
145
+ flowchart LR
146
+ CLI["CLI (cli.py)"] --> SVC["Service Layer (service.py)"]
147
+ WEB["Web UI (web/server.py + static/index.html)"] --> SVC
148
+
149
+ SVC --> LOADERS["Loaders: sql / dbt / git / metadata"]
150
+ SVC --> ENGINE["Engine: parser / runner / fixer + patching"]
151
+ SVC --> BASELINE["Baseline Fingerprinting (baseline.py)"]
152
+
153
+ ENGINE --> RULES["Rules: specs / helpers / builtin"]
154
+ ENGINE --> EST["Estimators: bigquery_dryrun"]
155
+
156
+ SVC --> REP["Reporters: terminal / markdown / json / sarif"]
157
+ ```
158
+
159
+ For full module responsibilities and design rationale, see [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
160
+
161
+ ---
162
+
163
+ ## Installation
164
+
165
+ **Requirements:** Python `3.10+`
166
+
167
+ ```bash
168
+ # Clone the repository
169
+ git clone https://github.com/Ahmed-Gomaa1/bqguard.git
170
+ cd bqguard
171
+
172
+ # Standard editable install
173
+ pip install -e .
174
+
175
+ # Optional: enable live BigQuery Dry Run cost estimation (--dry-run)
176
+ pip install -e ".[bigquery]"
177
+
178
+ # Optional: install test dependencies
179
+ pip install -e ".[dev]"
180
+ ```
181
+
182
+ **No-install option:** You can also run directly from the repository root without installing:
183
+
184
+ ```bash
185
+ python run_bqguard.py check examples/sql --metadata examples/metadata.yaml
186
+ ```
187
+
188
+ ---
189
+
190
+ ## Quickstart
191
+
192
+ ```bash
193
+ # 1. Scaffold starter bqguard.yaml and metadata.yaml in your project
194
+ bqguard init
195
+
196
+ # 2. Check SQL files against your offline metadata snapshot
197
+ bqguard check examples/sql --metadata examples/metadata.yaml
198
+
199
+ # 3. Preview surgical auto-fixes (unified diff, no files modified)
200
+ bqguard check examples/sql/bad_hourly_checkouts.sql --metadata examples/metadata.yaml --fix-dry-run
201
+
202
+ # 4. Apply surgical auto-fixes in place
203
+ bqguard check path/to/query.sql --metadata metadata.yaml --fix
204
+
205
+ # 5. Check a compiled dbt project and generate a GitHub PR Markdown report
206
+ bqguard check --dbt-dir examples/dbt_project --format markdown
207
+
208
+ # 6. Snapshot existing violations into a baseline, then fail only on NEW violations
209
+ bqguard baseline examples/sql --metadata examples/metadata.yaml -o .bqguard-baseline.json
210
+ bqguard check examples/sql --metadata examples/metadata.yaml --baseline .bqguard-baseline.json
211
+
212
+ # 7. Launch the local interactive Web Playground
213
+ bqguard ui --port 8765
214
+ ```
215
+
216
+ ---
217
+
218
+ ## CLI Reference
219
+
220
+ | Command | Description |
221
+ | :--- | :--- |
222
+ | `bqguard check [PATHS...]` | Analyze raw `.sql` files and/or compiled `dbt` models for cost & performance violations. |
223
+ | `bqguard baseline [PATHS...]` | Snapshot current violations into a line-independent JSON baseline file. |
224
+ | `bqguard sync-sql --dataset <NAME>` | Print a safe, read-only `INFORMATION_SCHEMA` query to refresh `metadata.yaml`. |
225
+ | `bqguard init` | Create starter `bqguard.yaml` and `metadata.yaml` files. |
226
+ | `bqguard rules` | List all built-in rules (`BQ001`–`BQ008`) and mark `[auto-fix]` capabilities. |
227
+ | `bqguard ui` | Launch the local interactive SQL playground bound to `127.0.0.1`. |
228
+
229
+ ### Key `bqguard check` Options
230
+
231
+ | Option | Default | Description |
232
+ | :--- | :---: | :--- |
233
+ | `-c, --config <PATH>` | auto-detect | Path to `bqguard.yaml` (auto-discovers `bqguard.yaml` / `.bqguard.yaml`). |
234
+ | `-d, --dialect <NAME>` | `bigquery` | Target warehouse dialect: `bigquery`, `snowflake`, or `databricks`. |
235
+ | `-m, --metadata <PATH>` | from config | Path to offline table metadata YAML/JSON snapshot. |
236
+ | `--dbt-dir <PATH>` | — | Path to a compiled `dbt` project root (or `target/` directory). |
237
+ | `--dbt-model <NAME>` | all | Restrict dbt analysis to specific model name(s) (repeatable). |
238
+ | `--changed-only` | `false` | Inspect only `.sql` files / dbt models modified in git. |
239
+ | `--base-ref <REF>` | — | Git base ref for PR diffs (e.g., `origin/main`). Implies `--changed-only`. |
240
+ | `--baseline <PATH>` | — | Suppress legacy findings recorded in a baseline JSON file. |
241
+ | `--fix` / `--fix-dry-run` | `false` | Apply or preview safe surgical AST fixes (`BQ003`, `BQ005`). |
242
+ | `--dry-run` | `false` | Run free BigQuery Dry Run API to estimate exact GB scanned & USD cost (`BQ008`). |
243
+ | `--max-cost-usd <FLOAT>` | `5.0` | Override maximum allowed USD cost per query in `--dry-run` mode. |
244
+ | `--max-gb <FLOAT>` | — | Override maximum allowed GB scanned per query in `--dry-run` mode. |
245
+ | `--fail-on <LEVEL>` | `error` | Exit non-zero on `error` (default) or `warning`. |
246
+ | `-f, --format <FMT>` | `terminal` | Output format: `terminal`, `markdown`, `json`, or `sarif`. |
247
+ | `-o, --output <PATH>` | stdout | Write formatted report to a file (e.g., `bqguard.sarif` or `pr-comment.md`). |
248
+
249
+ ---
250
+
251
+ ## Configuration & Offline Metadata
252
+
253
+ ### `bqguard.yaml`
254
+
255
+ ```yaml
256
+ dialect: bigquery # bigquery | snowflake | databricks
257
+ min_table_size_gb: 1.0 # Tables smaller than this are skipped by high-cost rules
258
+ max_metadata_age_days: 30 # Warn when metadata snapshot exceeds this age
259
+ fail_on_stale_metadata: false
260
+ fail_on: error # error | warning
261
+ metadata_path: metadata.yaml # Resolved relative to this config file's directory
262
+
263
+ rules:
264
+ BQ001: error
265
+ BQ002: error
266
+ BQ003: error
267
+ BQ004: error
268
+ BQ005: warning
269
+ BQ006: warning
270
+ BQ007: warning
271
+ BQ008: error
272
+
273
+ cost:
274
+ price_per_tb_usd: 6.25
275
+ max_cost_usd: 5.0
276
+ warn_cost_usd: 1.0
277
+ # max_gb_scanned: 500
278
+ ```
279
+
280
+ ### `metadata.yaml` (Offline Metadata Snapshot)
281
+
282
+ ```yaml
283
+ generated_at: "2026-12-03"
284
+ tables:
285
+ - name: prod.analytics.user_events
286
+ size_gb: 4500.0
287
+ row_count: 18500000000
288
+ partition_column: event_timestamp
289
+ partition_type: DAY
290
+ partition_data_type: TIMESTAMP # DATE | DATETIME | TIMESTAMP (used for type-safe --fix)
291
+ cluster_columns:
292
+ - country_code
293
+ - event_name
294
+ require_partition_filter: true
295
+
296
+ - name: prod.analytics.dim_countries
297
+ size_gb: 0.002
298
+ row_count: 249
299
+ ```
300
+
301
+ Refresh your snapshot nightly without giving CI runners production access:
302
+
303
+ ```bash
304
+ bqguard sync-sql --dataset prod.analytics --dialect bigquery
305
+ bqguard sync-sql --dataset PROD_DW.ANALYTICS --dialect snowflake
306
+ bqguard sync-sql --dataset main.lakehouse --dialect databricks
307
+ ```
308
+
309
+ ### Inline Rule Suppression
310
+
311
+ Suppress an intentional pattern on the same line or the line immediately above:
312
+
313
+ ```sql
314
+ -- bqguard: ignore=BQ006
315
+ SELECT event_id FROM table_a
316
+ UNION DISTINCT
317
+ SELECT event_id FROM table_b
318
+ ```
319
+
320
+ ---
321
+
322
+ ## Built-in Rules
323
+
324
+ | Rule | Name | Default | Auto-Fix | Description & False-Positive Safeguards |
325
+ | :--- | :--- | :---: | :---: | :--- |
326
+ | **`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. |
327
+ | **`BQ002`** | `missing-partition-filter` | `error` | — | Flags queries reading large partitioned tables without a `WHERE` filter on the partition column (ignores `JOIN ON`-only references). |
328
+ | **`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. |
329
+ | **`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`). |
330
+ | **`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`). |
331
+ | **`BQ006`** | `union-distinct-cost` | `warning` | — | Flags `UNION DISTINCT` (BigQuery) / `UNION` (Snowflake, Databricks) where `UNION ALL` avoids expensive distributed deduplication. |
332
+ | **`BQ007`** | `leading-wildcard-like` | `warning` | — | Flags leading wildcard `LIKE '%...'` patterns on clustered or large (`>= 100 GB`) table columns. |
333
+ | **`BQ008`** | `cost-threshold-exceeded` | `error` | — | Flags queries whose free BigQuery Dry Run estimate exceeds `max_cost_usd`, `max_gb_scanned`, or `warn_cost_usd`. |
334
+
335
+ ---
336
+
337
+ ## Dialect Compatibility Matrix
338
+
339
+ `bqguard` is **BigQuery-first**, with static AST rule and auto-fix support for Snowflake and Databricks SQL:
340
+
341
+ | Capability | BigQuery | Snowflake | Databricks SQL |
342
+ | :--- | :---: | :---: | :---: |
343
+ | Static AST rules (`BQ001`–`BQ007`) | Full | Full | Full |
344
+ | Idiomatic array/table expansion allowed | `UNNEST` | `LATERAL FLATTEN` | `LATERAL VIEW EXPLODE` |
345
+ | Surgical Auto-Fix (`BQ003`, `BQ005`) | Full | Full (`TO_DATE`, `YEAR`) | Full (`YEAR`, `DATE`) |
346
+ | Offline Metadata Snapshot + Freshness TTL | Full | Full | Full |
347
+ | `sync-sql` metadata export query | Full | Sizes + `clustering_key` | Table list (pair with `DESCRIBE DETAIL`) |
348
+ | Live Dry Run byte/USD cost check (`BQ008`) | Full (free API) | — | — |
349
+
350
+ ---
351
+
352
+ ## CI/CD & Tooling Integration
353
+
354
+ ### 1. GitHub Pull Request Comment
355
+ A ready-to-use workflow is included in [.github/workflows/bqguard-pr.yml](.github/workflows/bqguard-pr.yml) — it runs `bqguard check --changed-only --base-ref origin/${{ github.base_ref }} --format markdown` and creates or updates a single PR comment.
356
+
357
+ ### 2. GitHub Code Scanning (SARIF 2.1.0)
358
+ Upload SARIF findings directly to GitHub's **Security / Files changed** annotations:
359
+
360
+ ```yaml
361
+ - name: Run bqguard (SARIF)
362
+ continue-on-error: true
363
+ run: |
364
+ bqguard check --changed-only --base-ref "origin/${{ github.base_ref }}" \
365
+ --metadata metadata.yaml \
366
+ --format sarif \
367
+ --output bqguard.sarif
368
+
369
+ - name: Upload SARIF to GitHub Code Scanning
370
+ uses: github/codeql-action/upload-sarif@v3
371
+ with:
372
+ sarif_file: bqguard.sarif
373
+ ```
374
+
375
+ ### 3. `pre-commit` Hook
376
+ Add to your repository's `.pre-commit-config.yaml`:
377
+
378
+ ```yaml
379
+ repos:
380
+ - repo: https://github.com/Ahmed-Gomaa1/bqguard
381
+ rev: v0.4.0
382
+ hooks:
383
+ - id: bqguard
384
+ args: ["--metadata", "metadata.yaml"]
385
+ ```
386
+
387
+ ---
388
+
389
+ ## Local Web Playground
390
+
391
+ Run an interactive browser UI with built-in BigQuery, Snowflake, and Databricks presets, live metadata editing, PR Markdown preview, and surgical Auto-Fix diffs:
392
+
393
+ ```bash
394
+ bqguard ui --port 8765
395
+ ```
396
+
397
+ **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`.
398
+
399
+ ---
400
+
401
+ ## How bqguard Compares
402
+
403
+ | Tool | Primary Focus | Metadata-Aware Table Sizes | Offline CI (No Prod Creds) | Surgical Cost Auto-Fix | Dry-Run Cost Gate |
404
+ | :--- | :--- | :---: | :---: | :---: | :---: |
405
+ | **SQLFluff** | SQL formatting & style linting | No | Yes | Style only | No |
406
+ | **dbt-checkpoint** | dbt schema, docs & test hygiene | No | Yes | No | No |
407
+ | **bqguard** | **Warehouse cost & pruning guardrails** | **Yes (`metadata.yaml` / `catalog.json`)** | **Yes** | **Yes (`BQ003`, `BQ005`)** | **Yes (BigQuery)** |
408
+
409
+ ---
410
+
411
+ ## Known Limitations & Roadmap
412
+
413
+ - **CTE Column Lineage in `BQ002` (Roadmap Priority):** Global partition-filter checks across outer CTEs match by column name rather than full table-qualified column lineage.
414
+ - **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.
415
+ - **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.
416
+ - **Databricks `sync-sql` Sizes:** Unity Catalog `information_schema.tables` does not expose table byte sizes directly (pair with `DESCRIBE DETAIL <table>`).
417
+ - **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.
418
+
419
+ ---
420
+
421
+ ## Development & Testing
422
+
423
+ ```bash
424
+ # Run the full test suite (40 tests covering AST rules, surgical patching, dbt, git, baseline, SARIF, and Web UI)
425
+ pytest -v
426
+ ```
427
+
428
+ CI runs automatically via [.github/workflows/ci.yml](.github/workflows/ci.yml) across Python `3.10`, `3.11`, `3.12`, and `3.13`.
429
+
430
+ ---
431
+
432
+ ## License
433
+
434
+ MIT — see [LICENSE](LICENSE).