Skip to content

About

Natural language to SQL autonomous agent with strict read-only security barriers and query explainer in pure PHP

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

Repository files navigation

🇸🇦 العربية | 🇬🇧 English

🤖 eidcloud-sql-agent

Latest Version PHP Version License: MIT Open In Colab

Natural language to SQL autonomous agent with strict read-only security barriers and query explainer in pure PHP (Zero external vendor dependencies).


📑 Topics

eidcloud · sql-agent · text-to-sql · ai-agent · database-agent · read-only-sql · php8


🏛️ Architecture & Workflow

flowchart TD
    UserQuery["User Natural Language Query"] --> AgentFacade["SqlAgent Facade"]
    SchemaSource[("Database (SQLite / MySQL)")] --> SchemaLoader["SchemaLoader (Dynamic Introspection)"]
    SchemaLoader --> ContextWindow["Prompt Context Window"]
    
    UserQuery --> QueryGen["QueryGenerator (Heuristic / Pluggable LLM)"]
    ContextWindow --> QueryGen
    
    QueryGen --> SQLQuery["Generated SQL Query"]
    SQLQuery --> SafetyBarrier{"SafetyBarrier (AST & Regex)"}
    
    SafetyBarrier -- "Contains Mutating Keywords (DROP, UPDATE, INSERT, ATTACH...)" --> Blocked["❌ SafetyViolationException (Blocked)"]
    SafetyBarrier -- "Strict Read-Only (SELECT / WITH / EXPLAIN)" --> Sandbox["SandboxExecutor (Timeout & Row Limits)"]
    
    SchemaSource --> Sandbox
    Sandbox --> RawData["Tabular Records & Execution Metrics"]
    RawData --> Explainer["ResultExplainer (Statistical Insights & Markdown)"]
    Explainer --> Output["Structured Output / CLI / JSON"]
Loading

⚡ Core Capabilities

  • Zero External Dependencies: Pure PHP 8.2+ codebase utilizing standard PDO and built-in reflection.
  • Dynamic Schema Ingestion: Introspects tables, columns, data types, primary keys, and foreign key relationships on the fly for SQLite and MySQL.
  • AST & Regex SQL Safety Barrier: Hard-stops mutating statements (INSERT, UPDATE, DELETE, DROP, ALTER, TRUNCATE, GRANT, REVOKE, ATTACH, SELECT INTO, stacked queries).
  • Read-Only Execution Sandbox: Enforces driver-level read-only flags (PRAGMA query_only = ON;, TRANSACTION READ ONLY), strict execution limits, row-count ceilings, and latency profiling.
  • Explainable Insights: Summarizes results with min/max/average metrics for numeric fields, execution timing, and formatted markdown tables.
  • Pluggable LLM Drivers: Works out-of-the-box with built-in heuristic pattern translation, or plugs seamlessly into OpenAI, Anthropic, Gemini, or local Ollama instances.
  • Dual-Mode CLI: Human-readable terminal output and --json streaming output for microservices and data pipelines.

🚀 Installation

Via Composer

composer require eidcloud/sql-agent

Manual / Git Clone

git clone https://github.com/shadialhasan/eidcloud-sql-agent.git
cd eidcloud-sql-agent

💻 CLI Usage

The agent comes with a zero-dependency CLI executable at bin/eidcloud-sql.

1. Inquire Using Natural Language

php bin/eidcloud-sql ask --db=app.sqlite "Show me top 5 customers with highest orders in last 30 days"

2. Output as Structured JSON

php bin/eidcloud-sql ask --db=app.sqlite --json "Show me top 5 customers with highest orders in last 30 days"

3. Inspect Schema Overview

php bin/eidcloud-sql schema --db=app.sqlite

4. CLI Help

php bin/eidcloud-sql --help

🛠️ Programmatic PHP API

Basic Usage with SQLite

<?php

use EidCloud\SqlAgent\SqlAgent;

require_once __DIR__ . '/vendor/autoload.php';

$pdo = new PDO('sqlite:ecommerce.sqlite');
$agent = new SqlAgent($pdo);

// Ask a natural language question
$response = $agent->ask("Show me top 5 customers with highest orders in last 30 days");

echo "Generated SQL:\n" . $response['sql'] . "\n\n";
echo "Rows Returned: " . $response['row_count'] . "\n";
echo "Execution Time: " . $response['execution_time_ms'] . " ms\n\n";
echo "Explanation:\n" . $response['explanation'] . "\n";

Connecting to MySQL

<?php

use EidCloud\SqlAgent\SqlAgent;

$pdo = new PDO('mysql:host=127.0.0.1;dbname=production;charset=utf8mb4', 'readonly_user', 'password');
$agent = new SqlAgent($pdo);

$response = $agent->ask("Count active subscriptions created in the last 7 days");
print_r($response);

Connecting an External LLM (e.g. OpenAI / Anthropic / Gemini)

<?php

use EidCloud\SqlAgent\SqlAgent;

$pdo = new PDO('sqlite:app.sqlite');

$llmCallback = function (string $prompt, string $schemaContext): string {
    // Invoke your preferred LLM SDK or HTTP client:
    // e.g., $client->chat()->create([...])
    return "SELECT * FROM orders ORDER BY amount DESC LIMIT 5;";
};

$agent = new SqlAgent($pdo, $llmCallback);
$response = $agent->ask("Show 5 largest orders");

🛡️ Security & Read-Only Guarantee

The SafetyBarrier validates query structure before any SQL reaches the database engine:

Check Behavior
Statement Root Must start with SELECT, WITH, or EXPLAIN
Mutating Verbs Blocks INSERT, UPDATE, DELETE, DROP, ALTER, TRUNCATE, CREATE, REPLACE
Privilege Escalation Blocks GRANT, REVOKE, SHUTDOWN, KILL
File / Output Exploits Blocks ATTACH, LOAD_FILE, INTO OUTFILE, INTO DUMPFILE, SELECT ... INTO
Stacked Injections Blocks stacked statements containing unescaped ; chaining
Resource Sandboxing Enforces maximum row limit (default: 1,000) and query timeouts

🧪 Testing

Run the zero-dependency test suite:

php tests/run_tests.php

📓 Interactive Google Colab Notebook

Run the quickstart tutorial directly in your browser: Open In Colab


👤 Author & Maintainer

Eng. MHD. Shadi AL-Hasan


📄 License

This project is licensed under the MIT License - see the LICENSE file for details.
Copyright (c) 2026 MHD. Shadi AL-Hasan. All rights reserved.

About

Natural language to SQL autonomous agent with strict read-only security barriers and query explainer in pure PHP

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages