ast
ModuleThe SQL syntax tree: a parser from tokens, serializers per dialect, a walker and visitors that rewrite trees.
Parser reads the tokens of a Tokenizer
into a Select; Walker applies a Visitor to every node
(validating columns, injecting a filter, renaming tables); Serializer
writes the tree back as SQL. Nodes are plain values with public fields:
Expression is the enum of every expression node.
PHP: Utopia\Query\AST\*.
| PHP | Rust |
|---|---|
AST\Expression (interface) | Expression |
AST\Call\Func | Func |
AST\Grammar | Grammar |
AST\Expression\Aliased, Between, Binary, CaseWhen, Cast, Conditional, Exists, In, Subquery, Unary, Window | Aliased, Between, Binary, CaseWhen, Cast, Conditional, Exists, In (with InList), Subquery, Unary, Window |
AST\Literal, AST\Placeholder, AST\Raw, AST\Star | Literal, Placeholder, Raw, Star |
AST\Reference\Column, AST\Reference\Table | Column, Table |
AST\SubquerySource, Table|SubquerySource | SubquerySource, TableSource |
AST\JoinClause, AST\OrderByItem | JoinClause, OrderByItem |
AST\Definition\Cte, AST\Definition\Window | Cte, WindowDefinition |
AST\Specification\Window | WindowSpecification |
AST\Statement\Select (with(): struct update syntax) | Select |
AST\Parser | Parser |
AST\Serializer, Serializer\MySQL, MariaDB, ClickHouse, PostgreSQL, SQLite | Serializer::new, Serializer::mysql, Serializer::mariadb, Serializer::clickhouse, Serializer::postgresql, Serializer::sqlite |
AST\Walker | Walker |
AST\Visitor (interface) | Visitor |
AST\Visitor\ColumnValidator, FilterInjector, TableRenamer | ColumnValidator, FilterInjector, TableRenamer |
use utopia_query::ast::{Binary, Column, FilterInjector, Literal, Parser, Serializer, Visitor};
let select = Parser::new().parse_sql("SELECT * FROM orders WHERE total > 100")?;
let mut tenant = FilterInjector::new(Binary::new(Column::new("tenant_id"), "=", Literal::new(42)));
let select = tenant.visit_select(select)?;
assert_eq!(
Serializer::new().serialize(&select)?,
"SELECT * FROM `orders` WHERE `total` > 100 AND `tenant_id` = 42"
);use Utopia\Query\AST\Expression\Binary;
use Utopia\Query\AST\Literal;
use Utopia\Query\AST\Parser;
use Utopia\Query\AST\Reference\Column;
use Utopia\Query\AST\Serializer;
use Utopia\Query\AST\Visitor\FilterInjector;
use Utopia\Query\Tokenizer\Tokenizer;
$select = (new Parser())->parse(Tokenizer::filter((new Tokenizer())->tokenize('SELECT * FROM orders WHERE total > 100')));
$select = (new FilterInjector(new Binary(new Column('tenant_id'), '=', new Literal(42))))->visitSelect($select);
echo (new Serializer())->serialize($select), "\n"; // SELECT * FROM `orders` WHERE `total` > 100 AND `tenant_id` = 42Contents
use utopia_query::ast::Aliased;pub struct Aliased {
pub expression: Box<Expression>,
pub alias: String,
}An expression with an alias: expression AS alias.
PHP: Utopia\Query\AST\Expression\Aliased (expression, alias).
From<Aliased>.use utopia_query::ast::Between;pub struct Between {
pub expression: Box<Expression>,
pub low: Box<Expression>,
pub high: Box<Expression>,
pub negated: bool,
}expression [NOT] BETWEEN low AND high.
PHP: Utopia\Query\AST\Expression\Between (expression, low, high, negated).
From<Between>.use utopia_query::ast::Binary;pub struct Binary {
pub left: Box<Expression>,
pub operator: String,
pub right: Box<Expression>,
pub escape: Option<Box<Expression>>,
}A binary operation: left operator right.
PHP: Utopia\Query\AST\Expression\Binary (left, operator, right).
From<Binary>.use utopia_query::ast::CaseWhen;pub struct CaseWhen {
pub condition: Box<Expression>,
pub result: Box<Expression>,
}One WHEN condition THEN result of a CASE.
PHP: Utopia\Query\AST\Expression\CaseWhen (condition, result).
From<CaseWhen>.use utopia_query::ast::Cast;pub struct Cast {
pub expression: Box<Expression>,
pub data_type: String,
}CAST(expression AS type) (or PostgreSQL's expression::type).
PHP: Utopia\Query\AST\Expression\Cast (expression, type).
From<Cast>.use utopia_query::ast::Column;pub struct Column {
pub name: String,
pub table: Option<String>,
pub schema: Option<String>,
}A column reference: [schema.][table.]name.
PHP: Utopia\Query\AST\Reference\Column (name, table, schema).
From<Column>.use utopia_query::ast::ColumnValidator;pub struct ColumnValidator {
// private fields
}Rejects columns outside an allow-list, and * unless allowed.
PHP: Utopia\Query\AST\Visitor\ColumnValidator.
use utopia_query::ast::Conditional;pub struct Conditional {
pub operand: Option<Box<Expression>>,
pub whens: Vec<CaseWhen>,
pub else_result: Option<Box<Expression>>,
}CASE [operand] WHEN ... THEN ... [ELSE ...] END.
PHP: Utopia\Query\AST\Expression\Conditional (operand, whens, else).
From<Conditional>.use utopia_query::ast::Cte;pub struct Cte {
pub name: String,
pub query: Select,
pub columns: Vec<String>,
pub recursive: bool,
}A common table expression: name [(columns)] AS (query).
PHP: Utopia\Query\AST\Definition\Cte (name, query, columns, recursive).
use utopia_query::ast::Exists;pub struct Exists {
pub subquery: Box<Select>,
pub negated: bool,
}[NOT] EXISTS (subquery).
PHP: Utopia\Query\AST\Expression\Exists (subquery, negated).
From<Exists>.use utopia_query::ast::FilterInjector;pub struct FilterInjector {
// private fields
}Adds a condition to the WHERE of statements (AND-ed with an existing one).
Walked, it applies to every statement, subqueries included; to change
only the outer one, call Visitor::visit_select on it directly.
PHP: Utopia\Query\AST\Visitor\FilterInjector.
use utopia_query::ast::Func;pub struct Func {
pub name: String,
pub arguments: Vec<Expression>,
pub distinct: bool,
pub filter: Option<Box<Expression>>,
}A function call: NAME([DISTINCT] args) [FILTER (WHERE ...)].
PHP: Utopia\Query\AST\Call\Func (name, arguments, distinct, filter).
From<Func>.use utopia_query::ast::Grammar;pub struct Grammar;The lexical rules for function names and cast types, which the
Serializer writes verbatim, so a quoted identifier
cannot carry SQL into them.
PHP: Utopia\Query\AST\Grammar.
use utopia_query::ast::In;pub struct In {
pub expression: Box<Expression>,
pub list: InList,
pub negated: bool,
}expression [NOT] IN (list).
PHP: Utopia\Query\AST\Expression\In (expression, list, negated).
From<In>.use utopia_query::ast::JoinClause;pub struct JoinClause {
pub kind: String,
pub table: TableSource,
pub condition: Option<Expression>,
}A join: TYPE source [ON condition].
PHP: Utopia\Query\AST\JoinClause (type, table, condition).
use utopia_query::ast::Literal;pub struct Literal {
pub value: Value,
}A literal: a string, an integer, a float, a boolean or NULL.
PHP: Utopia\Query\AST\Literal (value, string|int|float|bool|null).
From<Literal>.use utopia_query::ast::OrderByItem;pub struct OrderByItem {
pub expression: Expression,
pub direction: OrderDirection,
pub nulls: Option<NullsPosition>,
}One ORDER BY item: expression ASC|DESC [NULLS FIRST|LAST].
PHP: Utopia\Query\AST\OrderByItem (expression, direction, nulls).
use utopia_query::ast::Parser;pub struct Parser {
// private fields
}A recursive-descent parser of SELECT statements.
Reads filtered tokens (no whitespace or comments, ending with
TokenType::Eof, as Tokenizer::filter returns them) and builds a
Select that a Walker can rewrite and a
Serializer write back. Not to be confused with the
classifier, which only reads a statement's leading
keyword.
PHP: Utopia\Query\AST\Parser.
use utopia_query::ast::{Expression, Parser};
use utopia_query::tokenizer::Tokenizer;
let tokens = Tokenizer::filter(Tokenizer::new().tokenize("SELECT name FROM users WHERE age > 18")?);
let select = Parser::new().parse(&tokens)?;
assert!(matches!(select.where_clause, Some(Expression::Binary(ref b)) if b.operator == ">"));use Utopia\Query\AST\Parser;
use Utopia\Query\Tokenizer\Tokenizer;
$tokens = Tokenizer::filter((new Tokenizer())->tokenize('SELECT name FROM users WHERE age > 18'));
$select = (new Parser())->parse($tokens);
echo $select->where->operator, "\n"; // >use utopia_query::ast::Placeholder;pub struct Placeholder {
pub value: String,
}A bound parameter placeholder, written as is (?, :name, $1).
PHP: Utopia\Query\AST\Placeholder (value).
From<Placeholder>.use utopia_query::ast::Raw;pub struct Raw {
pub sql: String,
}SQL written as is.
PHP: Utopia\Query\AST\Raw (sql).
From<Raw>.use utopia_query::ast::Select;pub struct Select {
pub columns: Vec<Expression>,
pub from: Option<TableSource>,
pub joins: Vec<JoinClause>,
pub where_clause: Option<Expression>,
pub group_by: Vec<Expression>,
pub having: Option<Expression>,
pub order_by: Vec<OrderByItem>,
pub limit: Option<Expression>,
pub offset: Option<Expression>,
pub distinct: bool,
pub ctes: Vec<Cte>,
pub windows: Vec<WindowDefinition>,
}A SELECT statement.
The PHP class is immutable and copies itself with with(); here the
fields are public, so a changed copy is struct update syntax
(Select { where_clause: Some(condition), ..select }).
PHP: Utopia\Query\AST\Statement\Select (columns, from, joins,
where, groupBy, having, orderBy, limit, offset, distinct,
ctes, windows), and Select::with().
use utopia_query::ast::Serializer;pub struct Serializer {
// private fields
}Writes a syntax tree as SQL, quoting identifiers the way one dialect does: backticks (MySQL, MariaDB, ClickHouse, and the base serializer) or double quotes (PostgreSQL, SQLite), with the quote doubled inside.
PHP: Utopia\Query\AST\Serializer and its dialect subclasses.
use utopia_query::ast::{Parser, Serializer};
let select = Parser::new().parse_sql("select id, name from users where id = 1")?;
assert_eq!(Serializer::new().serialize(&select)?, "SELECT `id`, `name` FROM `users` WHERE `id` = 1");
assert_eq!(Serializer::postgresql().serialize(&select)?, r#"SELECT "id", "name" FROM "users" WHERE "id" = 1"#);use Utopia\Query\AST\Parser;
use Utopia\Query\AST\Serializer;
use Utopia\Query\Tokenizer\Tokenizer;
$select = (new Parser())->parse(Tokenizer::filter((new Tokenizer())->tokenize('select id, name from users where id = 1')));
echo (new Serializer())->serialize($select), "\n"; // SELECT `id`, `name` FROM `users` WHERE `id` = 1Default.use utopia_query::ast::Star;pub struct Star {
pub table: Option<String>,
pub schema: Option<String>,
}*, table.* or schema.table.*.
PHP: Utopia\Query\AST\Star (table, schema).
From<Star>.use utopia_query::ast::Subquery;pub struct Subquery {
pub query: Box<Select>,
}A scalar subquery: (SELECT ...).
PHP: Utopia\Query\AST\Expression\Subquery (query).
From<Subquery>.use utopia_query::ast::SubquerySource;pub struct SubquerySource {
pub query: Box<Select>,
pub alias: String,
}A subquery used as a table: (SELECT ...) AS alias.
PHP: Utopia\Query\AST\SubquerySource (query, alias).
From<SubquerySource>.use utopia_query::ast::Table;pub struct Table {
pub name: String,
pub alias: Option<String>,
pub schema: Option<String>,
}A table reference: [schema.]name [AS alias].
PHP: Utopia\Query\AST\Reference\Table (name, alias, schema).
From<Table>.use utopia_query::ast::TableRenamer;pub struct TableRenamer {
// private fields
}Renames tables: table references (name and alias) and the table
qualifier of columns and table.*.
PHP: Utopia\Query\AST\Visitor\TableRenamer.
use utopia_query::ast::Unary;pub struct Unary {
pub operator: String,
pub operand: Box<Expression>,
pub prefix: bool,
}A unary operation: operator (operand) when prefix, else
operand operator (IS NULL, IS NOT NULL).
PHP: Utopia\Query\AST\Expression\Unary (operator, operand, prefix).
From<Unary>.use utopia_query::ast::Walker;pub struct Walker;Applies a Visitor to every node of a statement, bottom-up: the
children of a node first, then the node. Statements nested in
subqueries, IN, EXISTS, derived tables and CTEs are walked the same
way, and each gets Visitor::visit_select.
Order within a statement: columns, FROM, joins (table, then
condition), WHERE, GROUP BY, HAVING, ORDER BY, LIMIT,
OFFSET, CTEs, WINDOW definitions.
PHP: Utopia\Query\AST\Walker.
use std::collections::HashMap;
use utopia_query::ast::{Parser, Serializer, TableRenamer, Walker};
let select = Parser::new().parse_sql("SELECT u.id FROM users u WHERE u.active = 1")?;
let mut renamer = TableRenamer::new(HashMap::from([("users".to_owned(), "accounts".to_owned())]));
let select = Walker::new().walk(select, &mut renamer)?;
assert_eq!(Serializer::new().serialize(&select)?, "SELECT `u`.`id` FROM `accounts` AS `u` WHERE `u`.`active` = 1");use Utopia\Query\AST\Parser;
use Utopia\Query\AST\Serializer;
use Utopia\Query\AST\Visitor\TableRenamer;
use Utopia\Query\AST\Walker;
use Utopia\Query\Tokenizer\Tokenizer;
$select = (new Parser())->parse(Tokenizer::filter((new Tokenizer())->tokenize('SELECT u.id FROM users u WHERE u.active = 1')));
$select = (new Walker())->walk($select, new TableRenamer(['users' => 'accounts']));
echo (new Serializer())->serialize($select), "\n"; // SELECT `u`.`id` FROM `accounts` AS `u` WHERE `u`.`active` = 1use utopia_query::ast::Window;pub struct Window {
pub function: Box<Expression>,
pub window_name: Option<String>,
pub specification: Option<Box<WindowSpecification>>,
}A window function call: function OVER name or function OVER (specification).
PHP: Utopia\Query\AST\Expression\Window (function, windowName, specification).
From<Window>.use utopia_query::ast::WindowDefinition;pub struct WindowDefinition {
pub name: String,
pub specification: WindowSpecification,
}A named window: WINDOW name AS (specification).
PHP: Utopia\Query\AST\Definition\Window (name, specification).
use utopia_query::ast::WindowSpecification;pub struct WindowSpecification {
pub partition_by: Vec<Expression>,
pub order_by: Vec<OrderByItem>,
pub frame_type: Option<String>,
pub frame_start: Option<String>,
pub frame_end: Option<String>,
}A window: [PARTITION BY ...] [ORDER BY ...] [ROWS|RANGE frame].
PHP: Utopia\Query\AST\Specification\Window (partitionBy, orderBy,
frameType, frameStart, frameEnd).
use utopia_query::ast::Expression;pub enum Expression {
Func(Func),
Aliased(Aliased),
Between(Between),
Binary(Binary),
CaseWhen(CaseWhen),
Cast(Cast),
Conditional(Conditional),
Exists(Exists),
In(In),
Subquery(Subquery),
Unary(Unary),
Window(Window),
Literal(Literal),
Placeholder(Placeholder),
Raw(Raw),
Column(Column),
Star(Star),
}An expression: a column, a literal, an operation, a function call, a subquery.
PHP: the Utopia\Query\AST\Expression interface; each variant is one of
its implementations.
From<Func>, From<Aliased>, From<Between>, From<Binary>, From<CaseWhen>, From<Cast>, From<Conditional>, From<Exists>, From<In>, From<Subquery>, From<Unary>, From<Window>, From<Literal>, From<Placeholder>, From<Raw>, From<Column>, From<Star>.use utopia_query::ast::InList;pub enum InList {
Values(Vec<Expression>),
Subquery(Box<Select>),
}What an IN tests against.
PHP: In::$list, Expression[]|Select.
use utopia_query::ast::TableSource;pub enum TableSource {
Table(Table),
Subquery(SubquerySource),
}What a FROM or a join reads: a table or a subquery.
PHP: Table|SubquerySource.
From<Table>, From<SubquerySource>.use utopia_query::ast::Visitor;pub trait VisitorInspects or rewrites the nodes a Walker visits: each method gets a
node (its children already walked) and returns it, or its replacement.
The defaults keep every node.
PHP: the Utopia\Query\AST\Visitor interface.