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).llm_reader that physically cannot write: default_transaction_read_only = on, statement_timeout = 5s, and no privileges on public.llm_api with views that expose only safe columns — the model never sees emails, card data, or soft-deleted rows.INSERT, DROP, and cross-tenant reads fail with a specific error.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.sqlDetails and checks are in the steps below.

psql on PATH; on Windows use the same commands inside WSL or psql.exe from the PostgreSQL client package.<admin_user>), because creating roles and revoking schema privileges requires ownership or superuser rights.<db-host>, <db_name>, <admin_user>, <app_user> (your application's existing role), <strong-password>.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.
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
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: 200Why 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.

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.
Problem. The model keeps naming tables it cannot read.
ERROR: permission denied for table customerspg_dump or a hand-written list, while the role only sees llm_api. The model is guessing from stale context.information_schema query from Step 2, rebuild the prompt, and restart the service: systemctl restart <your-text-to-sql-service>. Confirm the new card has no public. entries.Problem. Your application migrations start failing after the role split.
ERROR: cannot execute CREATE TABLE in a read-only transactiondefault_transaction_read_only = on now applies to the migration job too.ALTER ROLE <app_user> SET default_transaction_read_only = off; and leave llm_reader untouched.Problem. Tenant filtering returns no rows or raises an error.
ERROR: unrecognized configuration parameter "app.tenant_id"current_setting is called without the missing_ok argument on a version that does not support it.SET LOCAL app.tenant_id = '<tenant-id>'; inside the same transaction, and verify with SELECT current_setting('app.tenant_id', true);. Check the documentation for your version's current_setting signature.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.
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.
Status: practical guide. Some statements come from vendors; verify in your environment.
Time to complete: 45 minutes Difficulty: Intermediate
Machine data: Citation Map JSON · JSON-LD · Semantic Embeddings — separate stage.
| Entity | Type | Role |
|---|---|---|
| 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 или разделах гайда |
No independent confirmation is provided; source claims and editorial conclusions are separated below.
| Source | Type | Role |
|---|---|---|
| No external links | — | — |
Cite as: AI Release. Как ограничить доступ LLM к базе данных при Text-to-SQL: настройка схемы, ролей и прав. ai-release.org.