Demo, all content is generated
Question

Letting my AI assistant write SQL queries against the production DB, how bad is this?

Open · 961 views · asked by pedro_the_pm · edited

Internal analytics tool for our team of 8. You ask a question in plain English, GPT writes SQL, we run it against our Postgres (Supabase) and show the table. Cursor built it in an afternoon and people love it. The connection uses the postgres user because that's what the connection string in the dashboard had.

My developer friend went pale when I showed him. What's the worst that can happen, and what's the minimum to make it acceptable?

What I’ve tried

Added 'only write SELECT queries' to the prompt. Added a check that the query starts with SELECT.

Comment
Which database user does the tool connect with? That decides how bad this is. postgres_pete · edited
postgres. the one from the connection string. pedro_the_pm · edited
Ok. Writing an answer. postgres_pete · edited

3 answers

postgres_pete · edited

Worst case: SELECT check passes on SELECT 1; DROP TABLE orders; or a CTE with DELETE ... RETURNING, and the postgres user can do anything. Also a 'harmless' query that joins five big tables can lock up your production DB.

Minimum to make it acceptable, enforced by the database, not the prompt:

create role analytics_ro login password '...';
grant usage on schema public to analytics_ro;
grant select on orders, customers, products to analytics_ro; -- only what's needed
alter role analytics_ro set default_transaction_read_only = on;
alter role analytics_ro set statement_timeout = '10s';

Connect the tool with that role. Leave out tables with sensitive data (auth, payments) or expose views that hide columns.

Better still: point it at a read replica so a heavy query can't slow down your app.

Comment
Did the role + timeout today. Replica is on the Pro plan so that's a later conversation. pedro_the_pm · edited
default_transaction_read_only is a good default, but note a user can still SET it off in their session. The grants are what actually protect you. Only grant SELECT. olu_backend · edited
olu_backend · edited

Pete covers the database side. On the AI side: log every generated query with who asked. When someone gets a wrong number in a meeting, you want to see the SQL.

Comment
lena_ops · edited

Different approach worth considering: instead of free SQL, give the model a set of predefined query tools (revenue_by_month(from, to), top_products(n)). Less magic, but no surprises, and 90% of the questions people ask are the same ten.

Comment
That's honestly what the team asks 90% of the time. Might do both: tools first, free SQL on the read-only role as fallback. pedro_the_pm · edited