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

> AI Release · @ai_releaseorg · https://ai-release.org/guides/kak-ogranichit-dostup-llm-k-baze-dannyh-pri-text-to-sql_en.html

## TL;DR

- Time to complete: 45 minutes
- Difficulty: Intermediate
- 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).

## What you will get

- A PostgreSQL login role `llm_reader` that physically cannot write: `default_transaction_read_only = on`, `statement_timeout = 5s`, and no privileges on `public`.
- A dedicated schema `llm_api` with views that expose only safe columns — the model never sees emails, card data, or soft-deleted rows.
- A verified connection string for the LLM plus a negative-test script that proves `INSERT`, `DROP`, and cross-tenant reads fail with a specific error.

## Quick start

```bash
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](https://ai-release.org/guides/img/kak-ogranichit-dostup-llm-k-baze-dannyh-pri-text-to-sql-en-1.jpg?v=1796200617)


- 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 chatbot) whose DSN you can edit — the connection string is the only place the model gets its credentials.
- Placeholders to replace: `<db-host>`, `<db_name>`, `<admin_user>`, `<app_user>` (your application's existing role), `<strong-password>`.
- Decide what the model may read. Write the list down before touching SQL: tables, columns, and whether multi-tenant rows must be filtered.

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](https://ai-release.org/guides/poshagovoe-rukovodstvo-kak-podklyuchit-neyroset-k-wiki.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide).

## 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.

```sql
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:**

```bash
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](https://ai-release.org/guides/img/kak-ogranichit-dostup-llm-k-baze-dannyh-pri-text-to-sql-en-2.jpg?v=1796200622)


**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.

```sql
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:

```sql
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:

```sql
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:

```yaml
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:

```sql
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](https://ai-release.org/guides/img/kak-ogranichit-dostup-llm-k-baze-dannyh-pri-text-to-sql-en-3.jpg?v=1796200626)


**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.

```sql
-- 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:

```bash
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.**
- Error: `ERROR: permission denied for table customers`
- Cause: the schema card in the prompt was built from a full `pg_dump` or a hand-written list, while the role only sees `llm_api`. The model is guessing from stale context.
- Solution: regenerate the card with the `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: `ERROR: cannot execute CREATE TABLE in a read-only transaction`
- Cause: the app and the LLM share one DSN, so `default_transaction_read_only = on` now applies to the migration job too.
- Solution: keep two DSNs. Restore write access for the app role only: `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: `ERROR: unrecognized configuration parameter "app.tenant_id"`
- Cause: the service opens a pooled connection without setting the session variable, or `current_setting` is called without the `missing_ok` argument on a version that does not support it.
- Solution: set the variable per request with `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.

## 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](https://ai-release.org/guides/kak-zapustit-ii-model-lokalno-na-android-prilozheniya-i.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide).
