Natural language to SQL autonomous agent with strict read-only security barriers and query explainer in pure PHP (Zero external vendor dependencies).
eidcloud · sql-agent · text-to-sql · ai-agent · database-agent · read-only-sql · php8
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"]
- 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
--jsonstreaming output for microservices and data pipelines.
composer require eidcloud/sql-agentgit clone https://github.com/shadialhasan/eidcloud-sql-agent.git
cd eidcloud-sql-agentThe agent comes with a zero-dependency CLI executable at bin/eidcloud-sql.
php bin/eidcloud-sql ask --db=app.sqlite "Show me top 5 customers with highest orders in last 30 days"php bin/eidcloud-sql ask --db=app.sqlite --json "Show me top 5 customers with highest orders in last 30 days"php bin/eidcloud-sql schema --db=app.sqlitephp bin/eidcloud-sql --help<?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";<?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);<?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");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 |
Run the zero-dependency test suite:
php tests/run_tests.phpRun the quickstart tutorial directly in your browser:
Eng. MHD. Shadi AL-Hasan
- Role: Executive CTO & Enterprise Solutions Architect
- Email: mhd.shadi.alhasan@gmail.com
- Phone / WhatsApp: +963934005922
- Location: Damascus, Syria
- GitHub: shadialhasan
This project is licensed under the MIT License - see the LICENSE file for details.
Copyright (c) 2026 MHD. Shadi AL-Hasan. All rights reserved.