Making natural-language SQL safer

When a model writes the SQL, the whole statement is untrusted input. Here is a layered PostgreSQL setup, with read-only roles, timeouts and statement validation, plus the commands to reproduce each rejection.

The standard defence against SQL injection is to keep code and data apart. OWASP's prevention cheat sheet puts it as defining the SQL structure separately and binding values through the database API [1]. A natural-language analytics tool cannot do that. The model's whole job is to write the structure. Every generated statement is, in effect, untrusted code that you have decided to run.

That changes which defences carry the weight. OWASP's cheat sheet places least privilege under hardening for ordinary applications and says that it limits the damage an attacker can cause but does not prevent SQL injection [1]. For generated SQL it becomes the primary control, backed by checks before and limits during execution. The layers below reduce the risk; they do not remove it. Each was tested on one PostgreSQL version, and the article notes what each one does not guarantee.

What can go wrong

FailureExamplePrimary control
Data changeDELETE FROM ordersRole privileges; read-only transaction
Schema changeDROP TABLE, CREATE TABLE in a shared schemaRole privileges; read-only transaction
Resource exhaustionA cross join over two large tables, pg_sleepTimeouts; row limits; function allow-list
Over-exposureReading salary or contact columnsGrants on a reporting schema; views; RLS
Control driftSET statement_timeout = 0, set_config(...)Statement validation; limits set by trusted code
Instruction smugglingA column value saying "ignore your rules"All of the above; the model is not the boundary

The last row is prompt injection. OWASP's 2025 Top 10 for LLM applications lists it first and recommends restricting the model's privileges to the minimum, handling privileged functions in code, and validating output with deterministic checks [2]. Each layer below follows from those three recommendations. The broader architecture is covered in Secure architecture for AI applications.

Layer 1: a role that can only read

The examples below are reproducible. They were run, then re-run in an independent review, on PostgreSQL 16.15 in scratch databases with a three-row test table, reporting.orders. The outputs quoted are from those runs, trimmed to the decisive lines, with psql prompts added, the scratch database name shown as analytics and the test role names shown as in the script. Replace analytics with your database name. The parameters they use are documented in the PostgreSQL 18 manual, with version notes where behaviour differs.

-- As an administrator, connected to the analytics database.
CREATE ROLE reporting_owner NOLOGIN;
CREATE SCHEMA reporting AUTHORIZATION reporting_owner;
-- (reporting_owner creates and loads the reporting tables.)

CREATE ROLE nlq_reader LOGIN
  NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS
  CONNECTION LIMIT 5;
-- Set a password or certificate authentication separately.

-- Remove what every role inherits from PUBLIC.
REVOKE ALL ON DATABASE analytics FROM PUBLIC;   -- removes CONNECT and TEMPORARY
GRANT CONNECT ON DATABASE analytics TO nlq_reader;
REVOKE CREATE ON SCHEMA public FROM PUBLIC;     -- default on new PostgreSQL 15+ databases

-- Read access to the reporting schema only, now and for future tables.
GRANT USAGE ON SCHEMA reporting TO nlq_reader;
GRANT SELECT ON ALL TABLES IN SCHEMA reporting TO nlq_reader;
ALTER DEFAULT PRIVILEGES FOR ROLE reporting_owner IN SCHEMA reporting
  GRANT SELECT ON TABLES TO nlq_reader;

Three lines in that script are easy to miss.

PostgreSQL grants CONNECT and TEMPORARY on every database to PUBLIC by default, and EXECUTE on functions [3]. Revoking the database defaults stops the reader from creating temporary tables. Revoking ALL from PUBLIC also removes CONNECT and TEMPORARY for every other role, so grant them back explicitly to roles that need them before running this on a shared database. Maintenance jobs can depend on it: in the test, a concurrent materialized-view refresh run by the schema owner failed until that role was granted TEMPORARY again.

PostgreSQL 15 removed PUBLIC's CREATE permission on the public schema for new clusters and new databases, but an upgraded cluster or a restored dump keeps the old permissions [4]. The REVOKE makes the script correct on both.

ALTER DEFAULT PRIVILEGES only affects objects created later, and only objects created by the role named in FOR ROLE [5]. If someone other than reporting_owner creates a table in reporting, the reader will not see it, which fails safe. The test confirmed this: a table created in reporting by the administrator returned "permission denied" to the reader.

Avoid granting pg_read_all_data for this purpose. Added in PostgreSQL 14, it gives read access to all tables, views and sequences in every schema [6][7], which is the opposite of a curated surface.

Layer 2: session defaults for that role

ALTER ROLE nlq_reader IN DATABASE analytics SET default_transaction_read_only = on;
ALTER ROLE nlq_reader IN DATABASE analytics SET statement_timeout = '5s';
ALTER ROLE nlq_reader IN DATABASE analytics SET lock_timeout = '1s';
ALTER ROLE nlq_reader IN DATABASE analytics SET idle_in_transaction_session_timeout = '15s';
ALTER ROLE nlq_reader IN DATABASE analytics SET search_path = reporting;
-- PostgreSQL 17 and later only (not part of the 16.15 test run):
-- ALTER ROLE nlq_reader IN DATABASE analytics SET transaction_timeout = '10s';

ALTER ROLE ... SET makes a value the session default every time the role logs in, and IN DATABASE scopes it to one database [8]. The defaults are applied only at login: SET ROLE and SET SESSION AUTHORIZATION do not apply them [8]. They protect nothing if the application logs in as a different role and then switches to the reader. statement_timeout aborts any statement that runs longer than the limit. lock_timeout aborts a statement that waits too long for a lock, and is only useful if it is shorter than the statement timeout. The PostgreSQL manual advises against setting statement_timeout or lock_timeout in postgresql.conf because they would affect all sessions [9]. transaction_timeout was added in PostgreSQL 17 [10].

Connected as nlq_reader, the defaults are active and a normal query works:

analytics=> SHOW default_transaction_read_only;   -- on
analytics=> SELECT region, sum(amount_inr) AS revenue_inr
            FROM orders GROUP BY region ORDER BY region;
 region | revenue_inr
--------+-------------
 North  |     3500.00
 South  |      850.50

A write, DDL and a runaway statement are each rejected:

analytics=> INSERT INTO orders VALUES (4, 'East', DATE '2026-03-01', 10.00);
ERROR:  25006: cannot execute INSERT in a read-only transaction

analytics=> CREATE TEMP TABLE scratch (x int);
ERROR:  25006: cannot execute CREATE TABLE in a read-only transaction

analytics=> SELECT * FROM orders FOR UPDATE;
ERROR:  25006: cannot execute SELECT FOR UPDATE in a read-only transaction

analytics=> SELECT pg_sleep(6);
ERROR:  57014: canceling statement due to statement timeout

Why the role matters more than the read-only flag

The PostgreSQL manual describes read-only transactions as "a high-level notion of read-only that does not prevent all writes to disk", and lists the commands it blocks [11]. It is also only a default. default_transaction_read_only is an ordinary setting, and the test continued by turning it off from inside the reader's own session:

analytics=> SET default_transaction_read_only = off;
SET
analytics=> INSERT INTO orders VALUES (4, 'East', DATE '2026-03-01', 10.00);
ERROR:  42501: permission denied for table orders
analytics=> DELETE FROM orders;
ERROR:  42501: permission denied for table orders
analytics=> CREATE TEMP TABLE scratch (x int);
ERROR:  42501: permission denied to create temporary tables in database "analytics"
analytics=> CREATE TABLE public.leak (x int);
ERROR:  42501: permission denied for schema public

The error codes tell the story. With the flag on, PostgreSQL rejected the statements as read-only violations (25006). With the flag off, the grants rejected the same statements as permission failures (42501). The flag is a useful early stop with a clear error, while the grants are what enforce the boundary.

The same test also showed a weakness. In that read-write session, the reader could relax its own limits:

analytics=> SET statement_timeout = 0;
SET
analytics=> ALTER ROLE nlq_reader IN DATABASE analytics SET statement_timeout = 0;
ALTER ROLE
analytics=> ALTER ROLE nlq_reader IN DATABASE analytics SET default_transaction_read_only = off;
ALTER ROLE

Both ALTER ROLE commands persisted. The reader's next login started with no statement timeout and with read-only mode off. This is documented behaviour. The ALTER ROLE reference says that superusers can change anyone's session defaults and that "ordinary roles can only set defaults for themselves" [8]. In other words, a login role with no special attributes can still change its own. Some parameters can only be set this way by a superuser [8]; the test confirmed that the timeouts and the read-only default are not among them.

What the reader could not do was change its own attributes. ALTER ROLE nlq_reader BYPASSRLS and a higher CONNECTION LIMIT were both refused with 42501, with PostgreSQL 16 reporting that only roles with the CREATEROLE attribute and the admin option on the role may alter it.

While the read-only default was on, the self-ALTER ROLE was rejected with 25006. That lasted only until the session ran SET default_transaction_read_only = off, so the flag delays the change and does not prevent it. Limits stored as role defaults are only as strong as the guarantee that the session cannot issue SET, RESET, ALTER ROLE or a function call that changes a setting. That guarantee has to come from the code in front of the database.

What a read-only role does not guarantee

A dedicated role with SELECT grants and a read-only default is a strong boundary against changing data. It is not a complete one. In the test, the reader's session could still:

  • change its own timeouts and read-only default, for the current session and for later logins;
  • call set_config inside a SELECT and change statement_timeout, even within a read-only transaction;
  • take an advisory lock with pg_advisory_lock, which needed no grant beyond the defaults;
  • see the names, columns and comments of a table it could not read, through the system catalogues.

Timeouts bound how long a statement runs, not how much CPU or memory it uses while it runs. The manual also notes that read-only mode "does not prevent all writes to disk" [11].

Layer 3: validate the statement before it reaches the database

A regular expression for words like DELETE blocks harmless string literals and misses writes inside a common table expression. A parser that produces a syntax tree is the right tool. These are the checks worth making, in order:

  1. Parse with a parser for the PostgreSQL dialect. Reject anything that does not parse.
  2. Require exactly one statement, and require it to be a SELECT. This removes stacked statements and SET.
  3. Walk the whole tree and reject any write, DDL, transaction control, COPY, SELECT ... INTO, locking clause or session command, wherever it appears. A data-modifying CTE such as WITH d AS (DELETE ...) SELECT ... is a SELECT at the top and a DELETE underneath.
  4. Allow only listed functions. pg_sleep, set_config, file and network functions, and administrative functions should never reach execution. PostgreSQL grants EXECUTE on functions to PUBLIC by default [3], so an allow-list is simpler than tracking every function's grants.
  5. Resolve every table reference and reject any outside the schema the tool is meant to read.
  6. Reject recursive CTEs unless you have a reason to allow them.

The executor then sets its own limits in the same transaction as the query, so they do not depend on role defaults surviving:

BEGIN TRANSACTION READ ONLY;
SET LOCAL statement_timeout = '5s';
SET LOCAL lock_timeout = '1s';
SELECT * FROM ( /* validated query */ ) AS q LIMIT 501;
COMMIT;

SET LOCAL lasts only until the end of the current transaction, whether it commits or not [15]. Only trusted code issues those commands. Wrapping the query and fetching one row more than the display limit tells the application whether the result was truncated, so it can say so. In the test run, SET LOCAL statement_timeout = '2s' inside a read-only transaction cancelled a three-second pg_sleep with 57014.

The function allow-list matters even with these limits in place. In the test, SELECT set_config('statement_timeout', '0', false) passed a "single SELECT" rule, ran inside this read-only transaction, and left the connection with no statement timeout after COMMIT. With false as the third argument, the new value applies for the rest of the session, not only the transaction [16]. If connections go back to a pool, reset each one before reuse: DISCARD ALL returns a session to its initial state, including RESET ALL [17].

DataMantri, Daivota's analytics product, generates, validates and runs read-only SQL on PostgreSQL to answer plain-language questions, and has been verified on PostgreSQL with a demo dataset. Design decisions visible in Daivota's own product code are the subject of Engineering lessons from building AI-native products.

Layer 4: cost and size before and after

Timeouts stop runaway queries after they start. A pre-flight check can stop some before. Plain EXPLAIN plans a statement without running it and reports estimated cost and rows. EXPLAIN ANALYZE does run it, and the manual warns that side effects happen as usual [12]. Only plain EXPLAIN belongs in a pre-flight check, and your validator should reject EXPLAIN ANALYZE from the model like any other non-SELECT.

Estimated cost is in arbitrary units set by the planner's cost parameters, not seconds [14], so any threshold is a design judgement that needs tuning on your own data. It is most useful for catching obvious mistakes such as a missing join condition.

After execution, cap rows and response size in the application, and say clearly when a result was truncated.

Layer 5: limit what can be read at all

Everything above prevents writes and runaway work. None of it stops a permitted SELECT from returning a column the user should not see. That is decided by what the role can read. Grants limit what a query returns, not what the catalogue shows: in the test, the reader could list the columns of a table it had no SELECT on and read that table's comment. The manual states that any user connected to a database can see all comments in it [18].

  • Publish a reporting schema with only the columns needed for analysis, using tables or views.
  • Leave contact details, identifiers and free-text fields out of it unless a question needs them.
  • Where different users must see different rows, use row-level security. With RLS enabled and no policy, PostgreSQL denies all rows, but superusers, BYPASSRLS roles and, by default, table owners bypass it [13]. The NOBYPASSRLS attribute on nlq_reader matters here.

Tenant-level patterns are covered in Tenant isolation patterns for multi-tenant SaaS. How the reporting layer and its descriptions improve accuracy, as opposed to safety, is in From PostgreSQL to conversational analytics.

A checklist

CheckReason
Dedicated login role, no elevated attributesSuperuser and BYPASSRLS defeat every other layer
CONNECT and TEMPORARY revoked from PUBLICDefaults allow temporary tables
CREATE on public revokedUpgraded databases keep the pre-15 default
SELECT on one reporting schema onlyOver-exposure is decided by grants
Read-only default and timeouts on the roleEarly, clear errors; the session can still undo them
SET LOCAL limits in each executor transactionSession defaults can be changed by the session
Parser-based validation, one SELECT, full tree walkCatches CTE writes, stacked statements, SET
Function and table allow-listsBlocks pg_sleep, set_config, other tables
Application logs in as the reader, not via SET ROLERole defaults apply only at login
DISCARD ALL before a pooled connection is reusedClears settings a query may have changed
Plain EXPLAIN only; row and size capsCheap pre-flight; bounded responses
Periodic check of pg_db_role_setting for the roleDetects changed defaults

Prepared with AI-assisted research and drafting.

Sources

  1. [1] OWASP Cheat Sheet Series Team, "SQL Injection Prevention Cheat Sheet", OWASP Cheat Sheet Series, n.d. https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html
  2. [2] OWASP GenAI Security Project, "LLM01:2025 Prompt Injection", OWASP Top 10 for LLM Applications, 2025. https://genai.owasp.org/llmrisk/llm01-prompt-injection/
  3. [3] PostgreSQL Global Development Group, "Privileges", PostgreSQL 18 documentation (version 18.6), n.d., accessed 3 November 2026. https://www.postgresql.org/docs/current/ddl-priv.html
  4. [4] PostgreSQL Global Development Group, "Release 15", PostgreSQL release notes, 2022. https://www.postgresql.org/docs/release/15.0/
  5. [5] PostgreSQL Global Development Group, "ALTER DEFAULT PRIVILEGES", PostgreSQL 18 documentation (version 18.6), n.d., accessed 3 November 2026. https://www.postgresql.org/docs/current/sql-alterdefaultprivileges.html
  6. [6] PostgreSQL Global Development Group, "Predefined Roles", PostgreSQL 18 documentation (version 18.6), n.d., accessed 3 November 2026. https://www.postgresql.org/docs/current/predefined-roles.html
  7. [7] PostgreSQL Global Development Group, "Release 14", PostgreSQL release notes, 2021. https://www.postgresql.org/docs/release/14.0/
  8. [8] PostgreSQL Global Development Group, "ALTER ROLE", PostgreSQL 18 documentation (version 18.6), n.d., accessed 3 November 2026. https://www.postgresql.org/docs/current/sql-alterrole.html
  9. [9] PostgreSQL Global Development Group, "Client Connection Defaults", PostgreSQL 18 documentation (version 18.6), n.d., accessed 3 November 2026. https://www.postgresql.org/docs/current/runtime-config-client.html
  10. [10] PostgreSQL Global Development Group, "Release 17", PostgreSQL release notes, 2024. https://www.postgresql.org/docs/release/17.0/
  11. [11] PostgreSQL Global Development Group, "SET TRANSACTION", PostgreSQL 18 documentation (version 18.6), n.d., accessed 3 November 2026. https://www.postgresql.org/docs/current/sql-set-transaction.html
  12. [12] PostgreSQL Global Development Group, "EXPLAIN", PostgreSQL 18 documentation (version 18.6), n.d., accessed 3 November 2026. https://www.postgresql.org/docs/current/sql-explain.html
  13. [13] PostgreSQL Global Development Group, "Row Security Policies", PostgreSQL 18 documentation (version 18.6), n.d., accessed 3 November 2026. https://www.postgresql.org/docs/current/ddl-rowsecurity.html
  14. [14] PostgreSQL Global Development Group, "Using EXPLAIN", PostgreSQL 18 documentation (version 18.6), n.d., accessed 3 November 2026. https://www.postgresql.org/docs/current/using-explain.html
  15. [15] PostgreSQL Global Development Group, "SET", PostgreSQL 18 documentation (version 18.6), n.d., accessed 3 November 2026. https://www.postgresql.org/docs/current/sql-set.html
  16. [16] PostgreSQL Global Development Group, "System Administration Functions" (set_config), PostgreSQL 18 documentation (version 18.6), n.d., accessed 3 November 2026. https://www.postgresql.org/docs/current/functions-admin.html
  17. [17] PostgreSQL Global Development Group, "DISCARD", PostgreSQL 18 documentation (version 18.6), n.d., accessed 3 November 2026. https://www.postgresql.org/docs/current/sql-discard.html
  18. [18] PostgreSQL Global Development Group, "COMMENT", PostgreSQL 18 documentation (version 18.6), n.d., accessed 3 November 2026. https://www.postgresql.org/docs/current/sql-comment.html