WHAT IS TEXT-TO-SQL?
The Enterprise Databases module lets you connect your PostgreSQL, MySQL, or SQL Server databases to the NeuralAI platform and query them in natural language. The AI converts your question into a safe SQL query (SELECT only), validates it against an anti-injection rule system, and returns ready-to-execute code.
Flow architecture
Connect DB
Host, port, credentials
Sync Schema
Tables and columns cached
Link API Key
db_connection scope
NL Question
AI generates SELECT SQL
Validate & Execute
Anti-injection + token
📋 Prerequisites
- A PostgreSQL, MySQL, or SQL Server database accessible from the Internet (public IP or whitelisting).
- SSL/TLS enabled on the database (recommended for all, mandatory for Neon and cloud services).
- A NeuralAI API key with the db_connection scope enabled.
- Sufficient tokens in your balance (2 tokens per generated query).
Security: multi-layer defense model
The system implements 5 independent layers of protection. Even if one layer is compromised, the subsequent layers would block the attack. This is the defense-in-depth principle.
Layer 1 — Encrypted credentials
Database passwords are stored encrypted (AES-256) in the NeuralAI database. No employee can read them in plaintext.
Layer 2 — Mandatory scope
Each connection MUST have an associated API key with the db_connection scope. Without this scope, SQL generation is rejected outright.
Layer 3 — Restrictive system prompt
The LLM receives strict instructions: generate ONLY SELECT queries, never INSERT/UPDATE/DELETE/DROP. If the request implies writes, it returns a structured error.
Layer 4 — Deterministic SQL validator
After generation, a non-AI (deterministic code) validator inspects the SQL: checks it starts with SELECT, blocks 18+ destructive keywords, detects statement chaining (semicolons), and forbids access to system schemas (information_schema, pg_catalog, etc.).
Layer 5 — Per-query billing
Each generated query costs 2 tokens, deducted only after success. This disincentivizes abuse and makes every operation traceable and auditable.
Table & column-level security
Beyond the 5 defense-in-depth layers, you can granularly control which tables and columns are visible to the AI. From each connection's card, the shield icon 🛡️ opens the security management panel where you can hide entire tables or individual sensitive columns.
Exclude entire tables
Excluded tables (excluded_tables) are stripped from the schema before the AI generates the SQL query. The AI will never see the table name, its columns, or its data. Ideal for internal configuration tables, system logs, or irrelevant data.
Exclude sensitive columns
Excluded columns (excluded_columns) are removed per-table. The AI sees the table but not the hidden columns, and cannot select them or read their values. Ideal for passwords, tax IDs, emails, credit card numbers, or other personal data (PII).
How exclusions work in the flow
Practical exclusion examples
- →users table → exclude columns: password_hash, reset_token, api_secret — the AI can count users but not see credentials
- →payments table → exclude entire table — the AI doesn't even know it exists, protecting complete financial data
- →customers table → exclude columns: fiscal_code, vat_number, iban — the AI can analyze purchases but not fiscal data
Exclusions apply to ALL AI queries: direct Text-to-SQL (generateSqlQuery), API Playground with use_db, and Knowledge Base + Database (buildKnowledgeBase). Changing exclusions immediately updates the connection card without needing to re-sync the schema.
When to sync the schema (and when NOT to)
✅ SYNC WHEN
- • You add a new table to the database
- • You add or remove columns from an existing table
- • You change a column's data type
- • You create or drop indexes or constraints (foreign keys)
❌ DO NOT SYNC FOR
- • Inserting new rows/records (data INSERT)
- • Updating existing values (data UPDATE)
- • Deleting rows (data DELETE)
- • Changes to table content without altering structure
Sync reads only metadata (table names, columns, types) via information_schema. It never accesses actual data in tables. It is safe and does not impact database performance.
API usage (developers)
SQL generation happens via the generateSqlQuery backend function. It's accessible from the web interface or directly via API with the Base44 SDK.
// Genera SQL da linguaggio naturale
const response = await fetch("${BASE_URL}/functions/generateSqlQuery", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({Response schema
{
"success": true,
"sql": "SELECT product_name, SUM(quantity) as total FROM vendite JOIN prodotti ON vendite.product_id = prodotti.id WHERE created_at >= DATE_TRUNC('month', NOW()) GROUP BY product_name ORDER BY total DESC LIMIT 10",
"is_safe": true,
"violations": [],successbooleanTrue if generation succeeded
sqlstring|nullGenerated SQL query (null if requires_write)
is_safebooleanTrue if the validator approves the query
violationsstring[]List of detected violations (empty = ok)
requires_writebooleanTrue if the question requires INSERT/UPDATE/DELETE
tokens_balancenumberRemaining token balance after deduction
Error handling
needs_api_keyThe connection has no associated API key with db_connection scope.needs_schema_syncThe schema has not been synced or contains no tables.insufficient_tokensInsufficient token balance (2 required, < 2 available).Best practices for engineers and developers
- Use a dedicated READ-ONLY database user for the connection. Even though the validator blocks writes, the principle of least privilege is fundamental.
- Create a separate API key with only the db_connection scope for each project or environment (dev/staging/prod). Do not reuse the same key for different purposes.
- Configure allowed_domains on the API key to restrict which domains can use it (e.g., only your production domain).
- Monitor token consumption via the manageApiKeys endpoint (action: get_balance) and set up auto-renew if needed.
- NEVER expose database credentials in frontend code. Always use a backend proxy that keeps secrets in environment variables.