gudb 0.2.3
AI-native database seatbelt that blocks destructive SQL, tracks latency, and ships Gemini-powered remediation guidance.
Requires Python: >=3.9
Keywords: database, sql, ai, sre, monitoring, safety, gudb, sentinel

# gudb: The Database Seatbelt 🛡️

**gudb** is a high-performance database safety layer designed to prevent production disasters *before* they happen. It acts as a "seatbelt" for your data, intercepting dangerous queries at the driver level with zero-latency heuristics and Senior DRE-level AI advice.

## ✨ Why a Seatbelt?
- **Local-Only by Default**: Zero network calls in local mode - all blocking decisions made locally
- **Zero-Latency Protection**: Local heuristics block `DELETE` or `DROP` without `WHERE` in <1ms
- **Structured Error Messages**: Every blocked query includes ISSUE, IMPACT, and FIX guidance
- **Optional AI Advisory**: Enable hybrid mode for AI-powered query suggestions (opt-in only)
- **Dashboard Integration**: Display dashboard links in error messages for more recommendations
- **Fail-Safe by Design**: If the AI or network is down, the seatbelt stays on
- **Driver-Level Hook**: Drops into your `psycopg2` connection in one line of code
- **Privacy First**: SQL redaction ensures sensitive PII never leaves your network

## 📦 Installation

```bash
pip install gudb
```

To install with framework-specific extras:
```bash
pip install "gudb[fastapi]"
```

## 🚀 Quick Start

### 1. The One-Liner (DB Driver Level)
Wrap your database connection to start guarding immediately.

```python
import psycopg2
from gudb import monitor

# Create your connection
raw_conn = psycopg2.connect("postgres://...")

# --- GUARD IT ---
conn = monitor(raw_conn)
# -----------------

cur = conn.cursor()
cur.execute("DELETE FROM orders;") # 🛑 Raises DisasterBlockedError

# Error output:
# 🛑 [gudb] ACCESS DENIED - DATABASE SEATBELT ACTIVATED
#    ISSUE:  UNCONSTRAINED DATA MODIFICATION
#    IMPACT: This query will wipe or corrupt EVERY ROW in the table.
#    FIX:    Add a WHERE clause to target specific records.
#    📺 For more recommendations, visit: http://localhost:8000/dashboard

# Safe queries with WHERE clauses are allowed:
cur.execute("DELETE FROM orders WHERE id = 123;")  # ✅ Allowed
```

### What You Get Out of the Box

```python
✅ ALLOWED: SELECT * FROM users;
✅ ALLOWED: DELETE FROM users WHERE id = 1;

🛑 BLOCKED: DELETE FROM users;
   → 
🛑 [gudb] ACCESS DENIED - DATABASE SEATBELT ACTIVATED
   ISSUE:  UNCONSTRAINED DATA MODIFICATION
   IMPACT: This query will wipe or corrupt EVERY ROW in the table.
   FIX:    Add a WHERE clause to target specific records.
📈 For more recommendations, visit: http://localhost:8000/dashboard
```

### 2. FastAPI Integration
```python
from fastapi import FastAPI
from gudb.middlewares.fastapi import SafeDBMiddleware

app = FastAPI()
app.add_middleware(SafeDBMiddleware)
```

## ⚙️ Configuration

The SDK operates in **local-only mode by default** (no network calls). Configure via environment variables:

### Basic Configuration (Local-Only)

```bash
# Default: local-only mode, no configuration needed
export GUDB_MODE="local"  # Optional, this is the default

# Add dashboard link to error messages (optional, no network calls)
export GUDB_DASHBOARD_URL="http://localhost:8000/dashboard"
```

### Hybrid Mode (Local + AI Advisory)

```bash
# Enable AI advisory while keeping local heuristics
export GUDB_MODE="hybrid"
export GUDB_API_ENDPOINT="https://your-backend.com/api/evaluate"
export GUDB_DASHBOARD_URL="http://localhost:8000/dashboard"
```

### All Configuration Options

| Variable | Description | Default |
|----------|-------------|---------|
| `GUDB_MODE` | Evaluation mode: `local`, `remote`, or `hybrid` | `local` |
| `GUDB_API_ENDPOINT` | AI evaluation backend URL (required for remote/hybrid) | `None` |
| `GUDB_DASHBOARD_URL` | Dashboard URL for recommendations | `None` |
| `GUDB_ENABLED` | Master switch for the SDK | `True` |
| `GUDB_FAIL_OPEN` | Allow queries if AI is down | `True` |
| `GUDB_REDACT_PII` | Scrub SQL literals before sending to AI | `True` |
| `GUDB_ENABLE_LOCAL_HEURISTICS` | Enable local safety checks | `True` |

### Mode Comparison

| Mode | Network Calls | Local Heuristics | AI Advisory | Best For |
|------|---------------|------------------|-------------|----------|
| `local` (default) | ❌ Never | ✅ Yes | ❌ No | Production safety without dependencies |
| `hybrid` | ✅ Optional | ✅ Yes | ✅ Yes | Production with AI insights |
| `remote` | ✅ Required | ❌ No | ✅ Yes | Development/testing with AI only |

### Example: Structured Error Handling

```python
from gudb import DisasterBlockedError

try:
    cursor.execute("DELETE FROM users")
except DisasterBlockedError as e:
    print(f"Issue: {e.issue}")       # What was detected
    print(f"Impact: {e.impact}")     # Why it's dangerous
    print(f"Fix: {e.fix}")           # How to correct it
    print(f"Query: {e.query}")       # Original query
    
    # AI Advisory (only in hybrid mode)
    if e.ai_advisory:
        print(f"AI Suggestion: {e.ai_advisory}")
    
    # Dashboard link (if configured)
    if e.dashboard_url:
        print(f"Dashboard: {e.dashboard_url}")
```

## 📚 Documentation

- **[Quick Reference](QUICK_REFERENCE.md)** - Cheat sheet for common patterns
- **[Features Guide](FEATURES_GUIDE.md)** - Complete feature documentation
- **[Demo Script](demo_complete_features.py)** - Working examples of all features
- **[Verification Tests](verify_new_features.py)** - Automated feature testing

## 🛠️ Advanced Usage (Extensibility)
You can implement your own AI provider if you want to use a local model or a different API.

```python
from gudb.providers.base import BaseProvider
from gudb import Gudb

class MyCustomProvider(BaseProvider):
    def evaluate(self, query, context):
        if "DROP" in query.upper():
            return {"verdict": "STOP", "issue": "No drops allowed"}
        return {"verdict": "GO"}

# Initialize with custom provider
gudb = Gudb(provider=MyCustomProvider())
```

## 🏗️ Development & Publishing
To test locally:
```bash
pip install -e .[dev]
pytest tests/
```

To publish to PyPI:
```bash
python -m build
twine upload dist/*
```

---
Built with ❤️ by the gudb Team. Ensuring your database sleeps soundly.