← All guides AI Release
RU Subscribe to @ai_releaseorg

How to restrict LLM access to database tables in Text-to-SQL: schema filtering, roles and permissions

Updated: 02.12.2026 · AI Release · @ai_releaseorg
How to restrict LLM access to database tables in Text-to-SQL: schema filtering, roles and permissions

TL;DR

What you will get

Quick start

export PGHOST=<db-host> PGPORT=5432 PGDATABASE=<db_name> PGUSER=<admin_user>
psql -v ON_ERROR_STOP=1 -f 01_llm_role.sql
psql -v ON_ERROR_STOP=1 -f 02_llm_views.sql
psql -v ON_ERROR_STOP=1 -f 03_llm_grants.sql
psql "postgresql://llm_reader:<strong-password>@<db-host>:5432/<db_name>" -f 04_verify.sql

Details and checks are in the steps below.

Requirements and setup

Illustration: Requirements and setup
Illustration: Requirements and setup

If you are still wiring the model to your systems, the connection pattern is described in Step-by-step guide: how to connect an LLM to your wiki, database, and test management system for QA.

Step 1. Create the restricted login role

What to do: create 01_llm_role.sql and run it as the admin user. This creates a login role with no administrative attributes and pins session settings at the role level.

BEGIN;
CREATE ROLE llm_reader LOGIN PASSWORD '<strong-password>'
  NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT;
ALTER ROLE llm_reader SET default_transaction_read_only = on;
ALTER ROLE llm_reader SET statement_timeout = '5s';
ALTER ROLE llm_reader SET idle_in_transaction_session_timeout = '30s';
ALTER ROLE llm_reader SET search_path = llm_api;
COMMIT;

Why: NOSUPERUSER NOCREATEDB NOCREATEROLE removes every escalation path — the role cannot create objects or grant itself rights. default_transaction_read_only = on makes every transaction read-only at the server level, so even if the model generates UPDATE orders SET ..., PostgreSQL rejects it before touching a row. statement_timeout protects the database from a runaway generated JOIN.

Example: after the script, \du llm_reader shows the role with attribute list Cannot login removed but no Superuser, Create role, or Create DB flags.

How to check:

psql "postgresql://llm_reader:<strong-password>@<db-host>:5432/<db_name>" \
  -c "SELECT current_user, current_setting('default_transaction_read_only') AS ro;"

Expected output:

 current_user | ro
--------------+----
 llm_reader   | on

Step 2. Build a read-only schema layer and grant least privilege

Illustration: Step 2. Build a read-only schema layer and grant least privilege
Illustration: Step 2. Build a read-only schema layer and grant least privilege

What to do: create schema llm_api with views instead of base tables, then revoke the default public access. Views are the mask: the model sees llm_api.orders with four columns, not public.orders with thirty.

BEGIN;
CREATE SCHEMA IF NOT EXISTS llm_api;

CREATE OR REPLACE VIEW llm_api.orders AS
SELECT id, created_at, status, total_cents
FROM public.orders
WHERE deleted_at IS NULL;

CREATE OR REPLACE VIEW llm_api.tickets AS
SELECT id, created_at, subject, status, tenant_id
FROM public.tickets;

REVOKE ALL ON SCHEMA llm_api FROM PUBLIC;
GRANT USAGE ON SCHEMA llm_api TO llm_reader;
GRANT SELECT ON ALL TABLES IN SCHEMA llm_api TO llm_reader;
ALTER DEFAULT PRIVILEGES IN SCHEMA llm_api GRANT SELECT ON TABLES TO llm_reader;
COMMIT;

Then close the base tables and the public schema:

BEGIN;
REVOKE ALL ON SCHEMA public FROM PUBLIC;
GRANT USAGE ON SCHEMA public TO <app_user>;
REVOKE ALL ON ALL TABLES IN SCHEMA public FROM llm_reader;
COMMIT;

Why: REVOKE ALL ON SCHEMA public FROM PUBLIC removes the default USAGE that lets any role see object names. After that, llm_reader can only reach llm_api, so a hallucinated SELECT * FROM public.customers fails instead of leaking data. ALTER DEFAULT PRIVILEGES makes future views readable without repeating GRANT.

Caution: before revoking from PUBLIC, confirm every existing role has explicit grants, or run this in a maintenance window. Default PUBLIC privileges differ between PostgreSQL versions — check the documentation for yours.

Multi-tenant rows: if one database serves several customers, enable row-level security on the base table and filter by a session variable your service sets per request:

ALTER TABLE public.tickets ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON public.tickets
  USING (tenant_id = current_setting('app.tenant_id', true)::int);

The true second argument makes current_setting return NULL instead of raising an error when the variable is unset — check the documentation for your version's support.

Point the model at the views: update the DSN in your Text-to-SQL service config:

database:
  dsn: "postgresql://llm_reader:<strong-password>@<db-host>:5432/<db_name>"
  options: "-c search_path=llm_api"
  max_rows: 200

Why this works: the model's schema card must be generated from what the role can actually read, otherwise the prompt advertises tables that will fail. Generate it from the catalog, not from a dump:

SELECT table_name, column_name, data_type
FROM information_schema.columns
WHERE table_schema = 'llm_api'
  AND has_column_privilege('llm_reader', table_schema||'.'||table_name, column_name, 'SELECT')
ORDER BY table_name, ordinal_position;

How to check: \dt llm_api.* as llm_reader lists orders and tickets; \dt public.* returns Did not find any relations.

Step 3. Run negative and positive tests

Illustration: Step 3. Run negative and positive tests
Illustration: Step 3. Run negative and positive tests

What to do: create 04_verify.sql and run it under the llm_reader DSN. Every write must fail; every allowed read must return rows.

-- 1. identity
SELECT current_user;
-- 2. allowed read
SELECT count(*) FROM llm_api.orders;
-- 3. blocked read
SELECT count(*) FROM public.customers;
-- 4. blocked write
INSERT INTO llm_api.orders (id) VALUES (1);
-- 5. timeout guard
SELECT pg_sleep(10);

Why: a permission setup is only proven by failures. Tests 3–5 must all raise errors; if test 4 succeeds, the role is not read-only and the whole configuration is void.

Example of a passing run: test 1 returns llm_reader, test 2 returns a number such as 18432, test 3 raises ERROR: permission denied for table customers, test 4 raises ERROR: cannot execute INSERT in a read-only transaction, test 5 raises ERROR: canceling statement due to statement timeout after about 5 seconds.

How to check: the exit code and the error lines. Wrap the run so every expected error is asserted, not eyeballed:

psql "postgresql://llm_reader:<strong-password>@<db-host>:5432/<db_name>" \
  -c "INSERT INTO llm_api.orders (id) VALUES (1);" 2>&1 | grep -q "read-only transaction" \
  && echo "PASS: writes blocked" || echo "FAIL: role can write"

Then ask the assistant a real question — "how many orders were created this week?" — and confirm the generated SQL contains only llm_api tables and ends with a LIMIT.

Troubleshooting

Problem. The model keeps naming tables it cannot read.

Problem. Your application migrations start failing after the role split.

Problem. Tenant filtering returns no rows or raises an error.

Summary and next steps

You now have a llm_reader role that cannot write, cannot see public, and times out after 5 seconds, plus a view layer that hides sensitive columns. Next, add column-level grants with GRANT SELECT (id, status) ON public.customers TO llm_reader; for any table you must expose without its PII columns.

FAQ

Does a read-only role stop the model from hallucinating table names?

No. It stops the damage: a hallucinated table fails with permission denied instead of returning rows. Keep the schema card generated from information_schema so the model sees only real, readable objects.

Can the model query production directly if the role is read-only?

Read-only protects data, not availability. A generated cartesian join can still saturate CPU, which is why statement_timeout = 5s and a row cap (max_rows: 200) belong in the setup. Prefer a replica when one is available.

How do I hide a single column such as email or a card number?

Two options: exclude it from the view (simplest), or grant column-level access — GRANT SELECT (id, created_at, status) ON public.customers TO llm_reader;. Column grants and table grants combine, so revoke the table-level SELECT first.

Can I avoid giving the model database access at all?

Yes — run the model locally and paste an export instead of connecting a live DSN. On-device options are covered in How to Run an AI Model Locally on Android: Apps and Setup.

🤖 AI summary

AI Release Knowledge Layer
Machine-readable description · Version 1.0

Status: practical guide. Some statements come from vendors; verify in your environment.

1. Summary

Time to complete: 45 minutes Difficulty: Intermediate

Inside: direct answers, key facts, entities, context, reliability, unknowns and sources.

Machine data: Citation Map JSON · JSON-LD · Semantic Embeddings — separate stage.

Full Knowledge Layer: sections 2–8

2. Direct answers

What is required?
Linux or macOS shell with psql on PATH; on Windows use the same commands inside WSL or psql.exe from the PostgreSQL client package.; Admin access to the target database (<admin_user>), because creating roles and revoking schema privileges requires ownership or superuser rights.; A TEXT-to-SQL service (agent or… → details (AR-GUIDE-KAKOGRANIC-003)
How to do it?
Step 1. Create the restricted login role → Step 2. Build a read-only schema layer and grant least privilege → Step 3. Run negative and positive tests → details (AR-GUIDE-KAKOGRANIC-004)
Which topics does it cover?
text-to-sql, доступ LLM к базе данных, schema filtering, права доступа SQL для ИИ, безопасность text-to-sql → details (AR-GUIDE-KAKOGRANIC-002)
What are the key points?
Time to complete: 45 minutes Difficulty: Intermediate → details (AR-GUIDE-KAKOGRANIC-007)

3. Key facts

  1. Time to complete: 45 minutes — evidence; status: заявление источника.
  2. Difficulty: Intermediate — evidence; status: заявление источника.
  3. You need: PostgreSQL with psql client access (version — check the documentation for your build), an admin role with CREATEROLE and GRANT rights, and a Text-to-SQL service where you can change the database connection string (DSN). — evidence; status: заявление источника.
  4. Linux or macOS shell with psql on PATH; on Windows use the same commands inside WSL or psql.exe from the PostgreSQL client package. — evidence; status: заявление источника.
  5. Admin access to the target database (<admin_user>), because creating roles and revoking schema privileges requires ownership or superuser rights. — evidence; status: заявление источника.
  6. A TEXT-to-SQL service (agent or chatbot) whose DSN you can edit — the connection string is the only place the model gets its credentials. — evidence; status: заявление источника.

4. Entities

EntityTypeRole
text-to-sqlтема/инструментупоминается в заголовке, TL;DR или разделах гайда
доступ LLM к базе данныхтема/инструментупоминается в заголовке, TL;DR или разделах гайда
schema filteringтема/инструментупоминается в заголовке, TL;DR или разделах гайда
права доступа SQL для ИИтема/инструментупоминается в заголовке, TL;DR или разделах гайда
безопасность text-to-sqlтема/инструментупоминается в заголовке, TL;DR или разделах гайда
Windowsплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
Linuxплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
macOSплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда

5. Context

  • Guide — describes → How to restrict LLM access to database tables in Text-to-SQL: schema filtering, roles and permissions (AR-GUIDE-KAKOGRANIC-001).
  • Guide — includes step → Step 1. Create the restricted login role (AR-GUIDE-KAKOGRANIC-001).

6. Reliability

Confirmed

No independent confirmation is provided; source claims and editorial conclusions are separated below.

Source claims

  • Product features, versions, prices and limits come from vendors and the guide.
  • Commands and steps are recommendations, not guaranteed results.

AI Release analysis

  • Structure, comparison and selection criteria are editorial.
  • The guide does not replace an independent audit or legal advice.

7. Unknowns

  • Current versions, prices and limits.
  • Independent benchmarks and quality checks.
  • Terms of use and data policy.

8. Sources

SourceTypeRole
No external links——

Cite as: AI Release. Как ограничить доступ LLM к базе данных при Text-to-SQL: настройка схемы, ролей и прав. ai-release.org.