Skip to main content

A secure SQL execution engine with risk analysis and reversible snapshot support.

Project description

🛡️ DB Safe Layer

AI-generated SQL must pass through a Safe Execution Layer before execution.

Database safety is no longer a human review task.
LLM agents, automation scripts, and internal tools can generate SQL—but execution remains the real risk.

DB Safe Layer is a lightweight SQL firewall that intercepts every statement before it reaches your database and performs:
• SQL structural analysis
• Dry-run impact estimation
• Risk classification
• Optional snapshot creation
• Gated execution
• Full audit + deterministic replay

Just drop it in front of your database—no infra changes.

“Like having a tireless DBA reviewing every command.”

🚧 Why this is needed

Teams across analytics, data engineering, healthcare, finance, and consulting report the same problem:
• LLMs sometimes generate hallucinated or destructive SQL
• Developers rely on manual review (slow + error-prone)
• Operations lack audit logs and replayability
• Even staging databases get damaged accidentally

DB Safe Layer provides a deterministic safety boundary before SQL touches any real data.

🔁 Execution Pipeline (Deterministic)

User SQL Input
        │
        ▼
   precheck(sql)
        │
        ▼
   dry_run(sql)
        │
        ▼
  estimated_rows
        │
        ▼
analyze_risk(sql, rows)
        │
        ├── LOW → execute(sql)
        │
        └── MEDIUM/HIGH → ask user yes/no
                        │
                        ├── no → abort
                        │
                        └── yes → snapshot() → execute(sql)
                                        │
                                        ▼
                                write audit.json
                                        │
                                        ▼
                                return result

Every step is recorded.
Every run can be replayed deterministically.

✨ Features

🧠 1. Structural Risk Analysis

Using SQLGlot AST parsing—not regex.
Detects:
• DROP / TRUNCATE / ALTER
• DELETE / UPDATE without WHERE
• Cross-table mutations
• Write operations on protected tables

Produces standardized risk levels: LOW / MEDIUM / HIGH / CRITICAL.

🔮 2. Dry-Run (Non-Destructive Impact Estimation)

Before running a write query:

DELETE → SELECT COUNT(*)
UPDATE → SELECT COUNT(*)
INSERT → SELECT COUNT(*) FROM VALUES(...)

Allows users to see:

“This will update 3,214 rows. Proceed?”

📸 3. Automatic Snapshot

For high-risk operations, DB Safe Layer creates a snapshot:
• SQLite → file copy
• PostgreSQL → CREATE TABLE AS snapshot / txid

Snapshots are references, and backups—fast and reversible.

📝 4. Full Audit + Replay

Every run logs:
• SQL
• Parsed AST
• Risk level
• Dry-run result
• Snapshot reference
• Execution decision
• Final result

Replay re-executes only read-only steps, without touching the database.

📂 Structure

db-safe-layer/
│
├── app.py                 # Example runner
├── db/
│   ├── config.py          # DB configuration
│   ├── database.py        # Engine/session management
│   └── snapshot.py        # Snapshot creation
│
├── execution/
│   └── executor.py        # Precheck → Dry-run → Risk → Execution
│
├── utils/
│   ├── risk_policy.py     # Risk classifier
│   └── sqlglot_helper.py  # SQL AST parsing + rewriting
│
├── audit/
│   ├── log_manager.py     # Write audit logs
│   └── replay.py          # Deterministic replay
│
└── requirements.txt

SQL → Precheck → Dry-Run → Risk analyse → Approval → Snapshot → Execution DAG → Audit + Replay

Stack

  • SQLGlot:SQL AST、dry-run(SELECT COUNT(*) FROM (...)
  • SQLAlchemy

🚀Quick Start

Installation

Clone project

Bash

git clone https://github.com/interact-space/database-safe-layer.git

Install

Bash

python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate
pip install -r requirements.txt

Configure Copy .env.example -> .env and configure the database connection:

Quick Start

✅ Python API

python

from db_safe_ayer import safe_exec, rollback_to
#module SQL check
safe_exec(SQL)
#module rollback to specified snapshot id
rollback_to()

✅ CLI

bash
#SQL check
safe-layer <SQL>
#rollback to specified snapshot id
safe-db-rollback 

💬 Join the Discussion

If you have any ideas, suggestions, or questions while using this project, feel free to open an Issue and share your thoughts! Whether it’s a feature request, bug report, improvement proposal, or general discussion, we truly welcome your participation.

👉 Start the conversation here: Issues Your feedback helps make this project better — thank you for your support! 🙌

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

db_safe_layer-0.1.0.tar.gz (24.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

db_safe_layer-0.1.0-py3-none-any.whl (25.4 kB view details)

Uploaded Python 3

File details

Details for the file db_safe_layer-0.1.0.tar.gz.

File metadata

  • Download URL: db_safe_layer-0.1.0.tar.gz
  • Upload date:
  • Size: 24.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.1

File hashes

Hashes for db_safe_layer-0.1.0.tar.gz
Algorithm Hash digest
SHA256 283349e17d065e03e26cbbb137eec75ebc2248c02da45f68e1adb2ed994c2042
MD5 f4f7b7c7105925146d535ed7bab86492
BLAKE2b-256 dfb3f9e6de23503d34be11b692f492b112bb0dc9c5755dcaf8c0c2fe6088eee9

See more details on using hashes here.

File details

Details for the file db_safe_layer-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: db_safe_layer-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 25.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.1

File hashes

Hashes for db_safe_layer-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 252983e575664472a9b37e51cbb8947ea14bc6a7353f3f60ea722aabedd9f85a
MD5 258b533acc0a7cc05b2695b2a171de0c
BLAKE2b-256 69efe9bf74dc12c143d32465eb4af64b2bc2a78600e6cf9ed6d5cd1409b64aa7

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page