# How DBX Ensures AI SQL Safety: Validating Queries Before Execution

> DBX ensures AI SQL safety by validating queries before execution. Learn how DBX enforces read-only defaults, blocks dangerous keywords, and requires WHERE clauses for secure AI data access.

- Repository: [skyler/dbx](https://github.com/t8y2/dbx)
- Tags: deep-dive
- Published: 2026-07-04

---

**DBX validates every AI-generated SQL query through a strict safety evaluator that enforces read-only defaults, blocks dangerous keywords, and requires WHERE clauses on destructive operations before execution.**

The t8y2/dbx repository provides a database exploration platform that leverages AI to generate SQL queries on-the-fly. While this capability accelerates data analysis, the system implements rigorous AI SQL safety measures to prevent accidental data loss or malicious destructive operations. Every generated query passes through a centralized validation layer that applies defense-in-depth security controls before reaching the database engine.

## The Core Safety Architecture

### The evaluateSqlSafety Evaluator

Located in [`packages/node-core/src/sql-safety.ts`](https://github.com/t8y2/dbx/blob/main/packages/node-core/src/sql-safety.ts), the `evaluateSqlSafety` function serves as the primary gatekeeper for AI SQL safety. This function parses incoming SQL statements, splits them into individual operations, strips comments and string literals, and applies a comprehensive set of safety rules. When violations are detected, it returns a `SqlSafetyDecision` object containing `allowed: false` and a human-readable `reason`, ensuring unsafe queries never reach the database.

### Environment-Based Configuration

The `sqlSafetyFromEnv` helper function reads runtime environment variables to configure safety policies. Administrators can relax restrictions using `DBX_MCP_ALLOW_WRITES` to permit modifications or `DBX_MCP_ALLOW_DANGEROUS_SQL` to enable destructive operations like `DROP` and `TRUNCATE`. These settings convert into a `SqlSafetyOptions` object that customizes the evaluator's behavior per session.

## Safety Rules and Enforcement Mechanisms

DBX enforces AI SQL safety through five critical validation layers:

- **Read-only by default**: Only `SELECT`, `SHOW`, `DESCRIBE`, `EXPLAIN`, and `WITH` statements are permitted unless `allowWrites` is explicitly enabled.
- **Dangerous keyword block**: Operations containing `DROP`, `TRUNCATE`, or `ALTER` are rejected unless `allowDangerous` is set to true.
- **WHERE clause enforcement**: When writes are allowed, `UPDATE` and `DELETE` statements must include a `WHERE` clause to prevent accidental full-table modifications.
- **Single-statement limitation**: Only one SQL statement is allowed per execution unless `allowMultipleStatements` is configured.
- **Environment-driven overrides**: Safety policies respect the `DBX_MCP_ALLOW_WRITES` and `DBX_MCP_ALLOW_DANGEROUS_SQL` environment variables for flexible deployment scenarios.

## Integration Points Across the DBX Ecosystem

The AI SQL safety validator operates consistently across all DBX interfaces.

### Desktop UI

In [`apps/desktop/src/composables/useSqlExecution.ts`](https://github.com/t8y2/dbx/blob/main/apps/desktop/src/composables/useSqlExecution.ts), the desktop application calls `evaluateSqlSafety` immediately after receiving AI-generated SQL. If the evaluator returns `allowed: false`, the UI aborts execution and surfaces the `safety.reason` to the user, preventing accidental data corruption through the graphical interface.

### MCP Server

The Model Context Protocol server in [`packages/mcp-server/src/index.ts`](https://github.com/t8y2/dbx/blob/main/packages/mcp-server/src/index.ts) protects AI agents like Claude and Cursor. When agents generate SQL, the server validates it using `evaluateSqlSafety` with options derived from `sqlSafetyFromEnv`. Blocked queries return a `toolError` with code `SQL_BLOCKED`, ensuring autonomous agents cannot execute destructive commands.

### Command Line Interface

The CLI implementation in [`packages/cli/src/cli.ts`](https://github.com/t8y2/dbx/blob/main/packages/cli/src/cli.ts) wraps the safety evaluator around manual and scripted queries. Before executing any user input, the CLI checks `evaluateSqlSafety` and fails with `SQL_BLOCKED` if the query violates safety policies.

## Practical Implementation Examples

Validating AI-generated queries in the desktop UI:

```typescript
import { evaluateSqlSafety, sqlSafetyFromEnv } from '@dbx-app/node-core';

const aiGeneratedSql = "UPDATE users SET role = 'admin' WHERE id = 42";
const safety = evaluateSqlSafety(aiGeneratedSql, sqlSafetyFromEnv());

if (!safety.allowed) {
  throw new Error(`SQL blocked: ${safety.reason}`);
}

```

Guarding AI agents in the MCP server:

```typescript
import { evaluateSqlSafety, sqlSafetyFromEnv } from '@dbx-app/node-core';

const safety = evaluateSqlSafety(sql, { 
  ...sqlSafetyFromEnv(), 
  allowMultipleStatements: true 
});

if (!safety.allowed) {
  return toolError("SQL_BLOCKED", safety.reason ?? "SQL blocked.");
}

```

CLI safety enforcement:

```typescript
// Inside packages/cli/src/cli.ts
const safety = evaluateSqlSafety(sql, safetyOptions);
if (!safety.allowed) {
  fail("SQL_BLOCKED", safety.reason);
}

```

Unit testing the safety logic:

```typescript
import { evaluateSqlSafety } from '../src/sql-safety.js';
import assert from 'node:assert/strict';

const decision = evaluateSqlSafety(
  "update users set disabled = true", 
  { allowWrites: true }
);

assert.equal(decision.allowed, false);
assert.match(decision.reason ?? "", /WHERE/i);

```

## Summary

- **Centralized validation**: All AI-generated SQL passes through `evaluateSqlSafety` in [`packages/node-core/src/sql-safety.ts`](https://github.com/t8y2/dbx/blob/main/packages/node-core/src/sql-safety.ts) before execution.
- **Defense in depth**: Read-only defaults, dangerous keyword blocks, and mandatory WHERE clauses protect against accidental destruction.
- **Environment flexibility**: Administrators control permissions via `DBX_MCP_ALLOW_WRITES` and `DBX_MCP_ALLOW_DANGEROUS_SQL`.
- **Universal coverage**: Safety checks are implemented consistently across the desktop UI, MCP server, and CLI interfaces.
- **Clear failure modes**: Blocked queries return explicit `SQL_BLOCKED` errors with human-readable explanations.

## Frequently Asked Questions

### What happens if an AI generates a DROP TABLE statement in DBX?

Unless the environment variable `DBX_MCP_ALLOW_DANGEROUS_SQL` is set to true, the `evaluateSqlSafety` function in [`packages/node-core/src/sql-safety.ts`](https://github.com/t8y2/dbx/blob/main/packages/node-core/src/sql-safety.ts) detects the `DROP` keyword and returns a `SqlSafetyDecision` with `allowed: false` and a reason citing the dangerous keyword violation. The calling interface (desktop, MCP, or CLI) then surfaces a `SQL_BLOCKED` error without sending the query to the database.

### Can I allow AI-generated UPDATE statements without a WHERE clause?

No, the safety evaluator enforces WHERE clause requirements on `UPDATE` and `DELETE` statements whenever `allowWrites` is enabled. As demonstrated in the unit tests within [`packages/node-core/tests/sql-safety.test.ts`](https://github.com/t8y2/dbx/blob/main/packages/node-core/tests/sql-safety.test.ts), queries like `update users set disabled = true` are rejected with a reason matching `/WHERE/i` unless they include a `WHERE` clause.

### How does DBX handle multiple SQL statements generated by AI?

By default, `evaluateSqlSafety` rejects queries containing multiple statements. The evaluator splits SQL into individual statements and validates the count. Only when `allowMultipleStatements` is set to true in the `SqlSafetyOptions` will the system permit multi-statement execution.

### Where is the safety validation configured for different deployment environments?

The `sqlSafetyFromEnv` function reads `DBX_MCP_ALLOW_WRITES` and `DBX_MCP_ALLOW_DANGEROUS_SQL` environment variables to populate `SqlSafetyOptions`. This configuration is applied at integration points in [`apps/desktop/src/composables/useSqlExecution.ts`](https://github.com/t8y2/dbx/blob/main/apps/desktop/src/composables/useSqlExecution.ts), [`packages/mcp-server/src/index.ts`](https://github.com/t8y2/dbx/blob/main/packages/mcp-server/src/index.ts), and [`packages/cli/src/cli.ts`](https://github.com/t8y2/dbx/blob/main/packages/cli/src/cli.ts), allowing per-environment safety policies without code changes.