What is a SQL AST
A SQL AST (abstract syntax tree) is the tree a parser builds from a SQL statement: each node is one part of the statement (the statement type, the table, the WHERE condition, each expression) and its children are the parts it contains. A tool that reads the tree, not the text, knows what the query does.
As text, DELETE FROM users WHERE id = 1 and DELETE FROM users differ by twelve characters. As trees they differ where it matters: the first has a where_clause holding an expression, the second has where_clause: null and deletes every row.
That is why Vericto's SQL guardrails decide on the tree: rule VERICTO-001 is literally "a DeleteStmt with no where_clause". With the same rules, the same query always gets the same verdict. Every rule, with its AST predicate and the real CLI output, is on the rule pages.
SQL to AST: a real example
This is the real output of pg_query::parse("DELETE FROM users WHERE id = 1"), serialized to JSON, with the Rust crate pg_query 6.2.1 (the PostgreSQL 17 parser; "version": 170007 is PostgreSQL 17.7):
{
"version": 170007,
"stmts": [
{
"stmt": {
"node": {
"DeleteStmt": {
"relation": {
"catalogname": "",
"schemaname": "",
"relname": "users",
"inh": true,
"relpersistence": "p",
"alias": null,
"location": 12
},
"using_clause": [],
"where_clause": {
"node": {
"AExpr": {
"kind": 1,
"name": [
{
"node": {
"String": {
"sval": "="
}
}
}
],
"lexpr": {
"node": {
"ColumnRef": {
"fields": [
{
"node": {
"String": {
"sval": "id"
}
}
}
],
"location": 24
}
}
},
"rexpr": {
"node": {
"AConst": {
"isnull": false,
"location": 29,
"val": {
"Ival": {
"ival": 1
}
}
}
}
},
"location": 27
}
}
},
"returning_list": [],
"with_clause": null
}
}
},
"stmt_location": 0,
"stmt_len": 0
}
]
}
The same call with DELETE FROM users returns the same DeleteStmt with "where_clause": null. Drawn as a tree:
DeleteStmt
├── relation: RangeVar (relname: "users")
├── using_clause: []
├── where_clause: AExpr (=) ← null in DELETE FROM users
│ ├── lexpr: ColumnRef (id)
│ └── rexpr: AConst (1)
├── returning_list: []
└── with_clause: null
For MySQL, the sqlparser 0.63 tree (MySqlDialect) says the same with other names. An excerpt of its real output ({:#?}); the DELETE without WHERE gives selection: None:
Delete(
Delete {
…
from: WithFromKeyword([TableWithJoins { relation: Table { name: ObjectName([Identifier(Ident { value: "users", … })]), … }, … }]),
using: None,
selection: Some(
BinaryOp {
left: Identifier(Ident { value: "id", quote_style: None, … }),
op: Eq,
right: Value(ValueWithSpan { value: Number("1", false), … }),
},
),
returning: None,
order_by: [],
limit: None,
},
)
Output generated on November 14, 2026 with pg_query 6.2.1 and sqlparser 0.63, the versions vericto-engine 5.0.0 uses. The two parsers have different schemas; Vericto normalizes both into one representation before it evaluates the rules.
Why an AST beats regex for SQL safety
A regex looks at characters. It does not know what a comment, a string or a subquery is. These statements fool a text check such as "contains WHERE", and the Vericto 5.0.0 engine reads them correctly (real verdicts):
| Statement | "Contains WHERE" check | What the AST says (Vericto 5.0.0) |
|---|---|---|
DELETE FROM users -- WHERE id = 1 | Passes | Blocked, VERICTO-001: the WHERE is inside a comment; DeleteStmt > WhereClause = NULL |
UPDATE users SET note = 'WHERE id = 1' | Passes | Blocked, VERICTO-030: the WHERE is part of a string; UpdateStmt > WhereClause = NULL |
DELETE FROM users WHERE 1 = 1 | Passes | Blocked, VERICTO-003: the WHERE exists but is always true; DeleteStmt > WhereClause = ALWAYS_TRUE |
WITH c AS (UPDATE sessions SET status = 'expired' RETURNING id) DELETE FROM audit_log WHERE … | Passes | Blocked, VERICTO-030: the UPDATE without WHERE is inside the CTE (below) |
A more elaborate regex can cover each row of the table, and the next case breaks it again: nested comments, PostgreSQL $$ strings, quoted identifiers, several statements in one text. The parser already handles all of it, because it is the same code the database uses. The full comparison is in Vericto vs. SQL allowlists.
pg_query: PostgreSQL's official parser
pg_query is the Rust binding of libpg_query, a C library that extracts the parser from the PostgreSQL source code (in vericto-engine 5.0.0, the PostgreSQL 17 one). It is the same code the server uses to turn each query into a tree before planning it.
Using the database's own parser gives an important property: Vericto reads the query the way PostgreSQL 17 reads it. If the tree has where_clause: null, PostgreSQL also runs it without a WHERE. The limit is the version: a newer server can accept syntax the PostgreSQL 17 parser does not read, and the proxy warns about it when it connects (parser and database version).
A Rust example, compiled and tested
The parser returns a Protocol Buffer with the full tree; each node is a NodeEnum variant. This example compiles with pg_query 6.2.1 and returns true and false for the two statements at the end. The real engine covers much more (CTEs, subqueries, an always-true WHERE), but the idea is this one: a deterministic walk of the tree.
use pg_query::NodeEnum;
fn has_delete_without_where(sql: &str) -> Result<bool, pg_query::Error> {
let result = pg_query::parse(sql)?;
for raw in &result.protobuf.stmts {
if let Some(NodeEnum::DeleteStmt(delete)) = raw.stmt.as_ref().and_then(|s| s.node.as_ref()) {
// where_clause is None when the statement has no WHERE clause
if delete.where_clause.is_none() {
return Ok(true);
}
}
}
Ok(false)
}
assert!(has_delete_without_where("DELETE FROM users")?);
assert!(!has_delete_without_where("DELETE FROM users WHERE id = $1")?);
sqlparser-rs for MySQL, Oracle, SQL Server, Snowflake and SQLite
For the dialects other than PostgreSQL, Vericto uses sqlparser-rs, a multi-dialect SQL parser written in Rust that is now an Apache DataFusion subproject (apache/datafusion-sqlparser-rs).
The dialect matters because the syntax is not identical. The clearest example: DELETE FROM table LIMIT 10 is valid in MySQL, but not in PostgreSQL. A LIMIT bounds how many rows are deleted, not which ones, so Vericto still blocks a DELETE without WHERE when it has a LIMIT (VERICTO-001). Separately, VERICTO-002 detects DELETE … LIMIT 0, which deletes nothing and usually points to a misconfigured scope. This example also compiles (with sqlparser 0.63) and returns Blocked for DELETE FROM users LIMIT 10:
use sqlparser::ast::Statement;
use sqlparser::dialect::MySqlDialect;
use sqlparser::parser::Parser;
#[derive(Debug)]
enum AnalysisResult {
Allowed,
Blocked { rule: &'static str, node_path: &'static str },
ParseError,
}
fn analyze_mysql_delete(sql: &str) -> AnalysisResult {
let Ok(ast) = Parser::parse_sql(&MySqlDialect {}, sql) else {
return AnalysisResult::ParseError;
};
for stmt in &ast {
if let Statement::Delete(delete) = stmt {
// A LIMIT bounds how many rows are deleted, not which: no WHERE is still a block
if delete.selection.is_none() {
return AnalysisResult::Blocked { rule: "VERICTO-001", node_path: "DeleteStmt > WhereClause = NULL" };
}
}
}
AnalysisResult::Allowed
}
How Vericto walks the tree in depth
The most dangerous queries hide the write in a subquery or a CTE. An allowlist that looks at the first token sees a WITH and misses them. A depth-first walk of the tree does not.
Consider this query:
WITH cleanup AS (
UPDATE sessions SET status = 'expired'
RETURNING id
)
DELETE FROM audit_log
WHERE session_id NOT IN (SELECT id FROM cleanup);
Its tree has two write operations:
- The
UpdateStmtinside the CTE, without aWHERE: it updates every row ofsessions. - The main
DeleteStmt, with aWHERE.
Vericto blocks the whole query because of the UpdateStmt in the CTE. Engine 5.0.0 reports three rules on the same node (WithClause > UpdateStmt > WhereClause = NULL): VERICTO-030 (critical) wins, and VERICTO-042 and VERICTO-031 are reported too. This is the pg_query tree, cut down to the fields that matter:
DeleteStmt
├── relation: audit_log
├── with_clause
│ └── ctes[0]: CommonTableExpr (ctename: "cleanup")
│ └── ctequery: UpdateStmt ← the offending node
│ ├── relation: sessions
│ ├── target_list: [ResTarget (name: "status", val: 'expired')]
│ ├── where_clause: null ← VERICTO-030, VERICTO-042, VERICTO-031
│ └── returning_list: [id]
└── where_clause: BoolExpr (NOT)
└── SubLink (ANY): session_id IN (SELECT id FROM cleanup)
Rules as predicates on the AST
The Vericto engine evaluates each active rule as a predicate on the tree. The standard rules are compiled in Rust; custom rules are defined in YAML as conditions on the AST (for example node_type: DeleteStmt with where_clause: null) and evaluated on the same tree.
A query can violate several rules at once. The engine reports all of them, ordered by resolved action (block, flag, monitor), then severity, then rule code; the verdict is the top one's. In the CTE example all three rules block, and the critical one with the lowest code, VERICTO-030, wins.
Vericto's AST engine, with the 42 rules of the standard catalogue, is open source under AGPL-3.0-only since vericto-engine 5.0.0, at github.com/vericto/engine. Earlier versions keep the licence they were published under (licences). You can read exactly what is evaluated and how.
What AST parsing costs
AST parsing can sound expensive: building a hierarchical tree for every query that goes through the proxy. We measured it. On staging on October 16, 2026, evaluating the rules, with no network, took a p99 of 100 µs or less on OLTP statements; on dedicated EC2 on October 20–21, 2026, the whole proxy, with TLS on both legs, added 0.12 ms at the median on PostgreSQL and about 0.1 ms per statement on MySQL. A larger statement costs more. A measurement, not a guarantee: conditions and method. (Update of October 31, 2026: with vericto-proxy 4.21.0, the same benchmark measured 0.08 ms on PostgreSQL and about 0.07 ms per statement on MySQL.)
There are three reasons that cost is low:
- The parser is in Rust. No garbage-collection pauses, no runtime overhead.
pg_querycalls Postgres's C parser directly.sqlparser-rsis pure Rust. - There is no I/O in the parsing path. The AST is built entirely in memory. No network calls, no disk access, no database queries.
- The audit trail is asynchronous. Recording to the audit trail happens outside the query's critical path: the decision to block or allow does not wait for the event to be written.
Every audit trail event stores the latency of its evaluation (latency_ms), so you can measure the overhead with your own traffic instead of relying on a benchmark.
Limitations of AST parsing
AST parsing is deterministic: with the same rules, the same query always gets the same verdict. That does not make it infallible:
- It does not analyze the data. Vericto does not know whether an UPDATE with a valid WHERE clause will affect 1 row or 500,000. To the rules engine,
UPDATE users SET role = 'admin' WHERE country = 'ES'is syntactically safe (it has a WHERE) even though it may affect many users. - It does not use table statistics. VERICTO-050 (SELECT without LIMIT) flags every top-level SELECT without a LIMIT, whether the table is small or huge, because the engine does not know its size. It is a MEDIUM rule: it flags, it does not block.
- It does not know your schema. Vericto does not connect to your database to read the catalogue: a column that does not exist (
SELECT emial FROM users) is a valid statement to the parser, and the database rejects it. - It does not catch every SQL injection. It detects the classic tautology (
… OR 1=1, VERICTO-090) and the variants that end in a destructive operation. If an injection produces a valid query that only reads another user's data, the tree is that of a legitimate query. Protection against injection comes earlier: parameterized queries and validating the agent's inputs.