Topic: Database-side SQL safety for AI assistants — a single function the AI must pass before execute
The problem AI creates for PostgreSQL
AI assistants and MCP tools generate SQL against Postgres every day: pg_stat_activity, bloat checks, explain plans. The risk is not only bad SELECTs — it is the model (or a leaked service role) reaching for:
DROP/TRUNCATE/ALTERpg_terminate_backendlo_import/pg_read_file/COPY … TODO $$ … $$anonymous blocks
Application guardrails help. A database function that every AI path must call before execute helps even more — one gate, clear errors, same rules as your app sql_safety layer.
That gate is ai_db_guardrails(p_sql).
What it is (and what it is not)
| This function | Not this |
|---|---|
| Pre-execute SQL checker for AI/MCP | Password policy / CREATE ROLE template |
Mirrors app sql_safety.py for Postgres | Row Level Security or pgAudit by itself |
Returns 'OK' or raises | Automatic rewrite of unsafe SQL |
Signature:
ai_db_guardrails(p_sql text) RETURNS text
How AI should use it
AI generates SQL → SELECT ai_db_guardrails(:sql) → if 'OK' → execute → if exception → return message to user / ask model to retry
Examples:
-- Allowed
SELECT ai_db_guardrails('SELECT pid, state FROM pg_stat_activity');
-- OK
SELECT ai_db_guardrails('EXPLAIN SELECT 1');
-- OK
-- Blocked
SELECT ai_db_guardrails('DROP TABLE customers');
-- ERROR: AI DB Guardrails: DDL/DML blocked
SELECT ai_db_guardrails('SELECT pg_terminate_backend(1234)');
-- ERROR: AI DB Guardrails: dangerous function/procedure blocked
SELECT ai_db_guardrails($$DO $$ BEGIN RAISE NOTICE 'x'; END $$;$$);
-- ERROR: AI DB Guardrails: dangerous function/procedure blocked
Call it from MCP Postgres tools, AskDBA runners, and Explorer execute — before psycopg/asyncpg runs the statement.
Rules inside the function (aligned with app SQL Safety)
Allowed
SELECT/WITH(must includeSELECT)SHOW/DESCRIBE/DESC/EXPLAIN/TABLEBEGIN TRANSACTION/BEGIN WORK/BEGIN ISOLATION(transaction starters only)
Blocked
- Leading DDL/DML:
CREATE,ALTER,DROP,TRUNCATE,DELETE,UPDATE,INSERT,MERGE,GRANT,REVOKE, … - Inline
DROP/TRUNCATE - Dangerous calls:
pg_terminate_backend,pg_cancel_backend,pg_reload_conf,pg_read_file/pg_read_binary_file,pg_ls_dir,lo_*,COPY … TO/FROM,DO $$,SET ROLE/SET SESSION AUTHORIZATION,EXEC/CALL/DECLARE - Anonymous
BEGINblocks - Multiple statements (stacked
;)
Same policy story as Oracle’s sys.ai_db_guardrails — dialect-specific dangerous APIs, shared read-only philosophy.
Install
As superuser:
-- =============================================================================-- AI DB Guardrails — PostgreSQL-- Author: Sandeep Reddy Narani-- ONE function for AI / MCP / Explorer: validate SQL before it runs.-- Mirrors app sql_safety.py (read-only, block DDL/DML, dangerous funcs).---- Usage:-- SELECT ai_db_guardrails('SELECT 1'); -- returns OK-- SELECT ai_db_guardrails('DROP TABLE t'); -- raises-- SELECT ai_db_guardrails('SELECT pg_terminate_backend(1)'); -- raises---- Run as superuser. GRANT EXECUTE to AI roles.-- =============================================================================CREATE OR REPLACE FUNCTION ai_db_guardrails(p_sql text)RETURNS textLANGUAGE plpgsqlAS $$DECLARE v text;BEGIN IF p_sql IS NULL OR btrim(p_sql) = '' THEN RAISE EXCEPTION 'AI DB Guardrails: empty SQL'; END IF; v := upper(btrim(regexp_replace(p_sql, '--[^\n]*', ' ', 'g'))); -- Leading DDL / DML IF v ~ '^\s*(CREATE|ALTER|DROP|TRUNCATE|DELETE|UPDATE|INSERT|MERGE|GRANT|REVOKE|REPLACE|RENAME|COMMENT)\b' THEN RAISE EXCEPTION 'AI DB Guardrails: DDL/DML blocked'; END IF; -- Inline DROP / TRUNCATE IF v ~ '\m(DROP|TRUNCATE)\M' THEN RAISE EXCEPTION 'AI DB Guardrails: DROP/TRUNCATE inside SQL blocked'; END IF; -- Dangerous functions / procedural (sql_safety patterns) IF v ~ '\mpg_terminate_backend\s*\(' OR v ~ '\mpg_cancel_backend\s*\(' OR v ~ '\mpg_reload_conf\s*\(' OR v ~ '\mpg_read_(binary_)?file\s*\(' OR v ~ '\mpg_ls_dir\s*\(' OR v ~ '\mlo_\w+\s*\(' OR v ~ '\mcopy\s+\w+\s+(to|from)\s+' OR v ~ '\mdo\s+(\$\$|language|\$)' OR v ~ '\mset\s+(role|session\s+authorization)\b' OR v ~ '\mexec(ute)?\s+\w' OR v ~ '\mcall\s+\w' OR v ~ '\mdeclare\s+\w' THEN RAISE EXCEPTION 'AI DB Guardrails: dangerous function/procedure blocked'; END IF; -- BEGIN (allow BEGIN TRANSACTION / WORK / ISOLATION only) IF v ~ '\mbegin\s+(isolation|transaction|work)\M' THEN NULL; ELSIF v ~ '\mbegin\M' THEN RAISE EXCEPTION 'AI DB Guardrails: anonymous BEGIN blocked'; END IF; -- Read-only starters IF v !~ '^\s*(SELECT|WITH|SHOW|DESCRIBE|DESC|EXPLAIN|TABLE)\b' THEN RAISE EXCEPTION 'AI DB Guardrails: only SELECT/WITH/SHOW/DESCRIBE/EXPLAIN allowed'; END IF; IF v ~ '^\s*WITH\b' AND v !~ '\mSELECT\M' THEN RAISE EXCEPTION 'AI DB Guardrails: WITH must include SELECT'; END IF; -- Stacked statements IF position(';' IN rtrim(rtrim(v), ';')) > 0 THEN RAISE EXCEPTION 'AI DB Guardrails: multiple statements blocked'; END IF; RETURN 'OK';END;$$;COMMENT ON FUNCTION ai_db_guardrails(text) IS'AI DB Guardrails — pre-execute SQL safety for AI/MCP (mirrors app sql_safety)';GRANT EXECUTE ON FUNCTION ai_db_guardrails(text) TO PUBLIC;-- Prefer: GRANT EXECUTE ON FUNCTION ai_db_guardrails(text) TO deeds_ai;DO $$ BEGIN RAISE NOTICE 'Installed ai_db_guardrails(p_sql) → text'; RAISE NOTICE 'AI/MCP should call this before every execute.';END $$;
\i postgres_ai_db_guardrails.sql
Tighten execute in production:
REVOKE EXECUTE ON FUNCTION ai_db_guardrails(text) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION ai_db_guardrails(text) TO deeds_ai;
Why one function helps tremendously
- One contract across products — MCP, AskDBA, Explorer, agents share one check.
- Model-friendly errors — prefix
AI DB Guardrails:is easy to parse and feed back. - Defense in depth — still useful if someone talks to Postgres outside the web app.
- Single place to evolve policy — add a blocked pattern once; every AI path gets it.
- Pairs with app Guardrails — app handles natural language, PII, SSH; this function handles SQL text.
Takeaway
Do not wait for a Postgres “profile” object that does not exist. Install ai_db_guardrails, require AI/MCP to call it before every execute, and refuse anything that is not OK. That is the PostgreSQL half of AI SQL Safety — compact, dialect-aware, and built for automation.
Leave a Reply