Using an AST to validate AI-generated PostgreSQL before it runs
If an LLM is generating PostgreSQL in your application, there is one moment worth treating separately: after the model returns SQL, but before your code calls db.query() . Prompt rules are useful. They can make the model more likely to produce the sort of query you want. They do not decide which tables the application is allowed to read, whether multiple statements are acceptable, or whether a…
After an LLM generates PostgreSQL code, it should be validated before running to ensure safety and compliance with application rules. sql-guard is a TypeScript package that parses SQL into an abstract syntax tree (AST) and checks it against an explicit policy to reject disallowed queries. Unlike regex checks, AST validation can effectively analyze query structure, including joins, subqueries, aliases, unions, and CTEs.
The policy outlines allowed tables, functions, schemas, and statements. For example, an assistant could only access users and orders tables and could only use count and lower functions. sql-guard rejects queries that violate the policy and provides detailed structured violations and error codes. It should be used alongside other database security measures like parameterized inputs, narrow database roles, row-level security, and column-level permissions. sql-guard is currently a PostgreSQL package for Node.js 18 or later.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.