今日已更新 35 条资讯 | 累计 37284 条内容
关于我们

Using an AST to validate AI-generated PostgreSQL before it runs

Nur Zaman 2026年08月25日 17:35 4 次阅读 来源:Dev.to

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 function call should run. I have been working on sql-guard , a TypeScript package for that gap. It parses PostgreSQL into an abstract syntax tree (AST), checks the tree against an explicit policy, and rejects anything it cannot validate confidently. Why I did not want to check SQL with regex SQL is structured. A query may have joins, subqueries, aliases, unions, and common table expressions (CTEs). Checking raw text can catch an obvious keyword, but it cannot reliably answer what the query actually does. For example: SELECT * FROM public . users ; SELECT 1 ; DELETE FROM public . users ; WITH removed AS ( DELETE FROM public . users RETURNING id ) SELECT * FROM removed ; All three examples contain SELECT , but they are not equivalent. The second has two statements. The third uses a data-modifying CTE. A validator needs to understand the query structure rather than look for a few strings. An AST makes that possible. It lets the validator inspect statement types, source tables, function calls, and nested expressions. It also means an alias or CTE name cannot conceal the base table being read. The policy is the important part sql-guard is built around allowlists. You state what a particular feature may use, and the validator checks the generated SQL against that list. Here is a small policy for an assistant that can look at users and orders: import { validate } from ' sql-guard ' ; const policy = { allowedTables : [ ' public.users ' , ' public.orders ' ], allowedFunctions : [ ' count ' , ' lower ' ], }; const result = validate ( ' SELECT lower(u.email) FROM public.users AS u ' , po

本文内容来源于互联网,版权归原作者所有
查看原文