Rust

ast

Module

The 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\*.

PHPRust
AST\Expression (interface)Expression
AST\Call\FuncFunc
AST\GrammarGrammar
AST\Expression\Aliased, Between, Binary, CaseWhen, Cast, Conditional, Exists, In, Subquery, Unary, WindowAliased, Between, Binary, CaseWhen, Cast, Conditional, Exists, In (with InList), Subquery, Unary, Window
AST\Literal, AST\Placeholder, AST\Raw, AST\StarLiteral, Placeholder, Raw, Star
AST\Reference\Column, AST\Reference\TableColumn, Table
AST\SubquerySource, Table|SubquerySourceSubquerySource, TableSource
AST\JoinClause, AST\OrderByItemJoinClause, OrderByItem
AST\Definition\Cte, AST\Definition\WindowCte, WindowDefinition
AST\Specification\WindowWindowSpecification
AST\Statement\Select (with(): struct update syntax)Select
AST\ParserParser
AST\Serializer, Serializer\MySQL, MariaDB, ClickHouse, PostgreSQL, SQLiteSerializer::new, Serializer::mysql, Serializer::mariadb, Serializer::clickhouse, Serializer::postgresql, Serializer::sqlite
AST\WalkerWalker
AST\Visitor (interface)Visitor
AST\Visitor\ColumnValidator, FilterInjector, TableRenamerColumnValidator, FilterInjector, TableRenamer
Rust
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"
);
PHP
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` = 42

Contents

Structs
AliasedAn expression with an alias: `expression AS alias`.Between`expression [NOT] BETWEEN low AND high`.BinaryA binary operation: `left operator right`.CaseWhenOne `WHEN condition THEN result` of a `CASE`.Cast`CAST(expression AS type)` (or PostgreSQL's `expression::type`).ColumnA column reference: `[schema.][table.]name`.ColumnValidatorRejects columns outside an allow-list, and `*` unless allowed.Conditional`CASE [operand] WHEN ... THEN ... [ELSE ...] END`.CteA common table expression: `name [(columns)] AS (query)`.Exists`[NOT] EXISTS (subquery)`.FilterInjectorAdds a condition to the `WHERE` of statements (`AND`-ed with an existing one).FuncA function call: `NAME([DISTINCT] args) [FILTER (WHERE ...)]`.GrammarThe lexical rules for function names and cast types, which the `Serializer`(super::Serializer) writes verbatim, so a quoted identifier cannot carry SQL into them.In`expression [NOT] IN (list)`.JoinClauseA join: `TYPE source [ON condition]`.LiteralA literal: a string, an integer, a float, a boolean or `NULL`.OrderByItemOne `ORDER BY` item: `expression ASC|DESC [NULLS FIRST|LAST]`.ParserA recursive-descent parser of `SELECT` statements.PlaceholderA bound parameter placeholder, written as is (`?`, `:name`, `$1`).RawSQL written as is.SelectA `SELECT` statement.SerializerWrites 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.Star`*`, `table.*` or `schema.table.*`.SubqueryA scalar subquery: `(SELECT ...)`.SubquerySourceA subquery used as a table: `(SELECT ...) AS alias`.TableA table reference: `[schema.]name [AS alias]`.TableRenamerRenames tables: table references (name and alias) and the table qualifier of columns and `table.*`.UnaryA unary operation: `operator (operand)` when `prefix`, else `operand operator` (`IS NULL`, `IS NOT NULL`).WalkerApplies 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`.WindowA window function call: `function OVER name` or `function OVER (specification)`.WindowDefinitionA named window: `WINDOW name AS (specification)`.WindowSpecificationA window: `[PARTITION BY ...] [ORDER BY ...] [ROWS|RANGE frame]`.
use utopia_query::ast::Aliased;
Rust
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).

Also implements From<Aliased>.
use utopia_query::ast::Between;
Rust
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).

Also implements From<Between>.
use utopia_query::ast::Binary;
Rust
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).

Also implements From<Binary>.
use utopia_query::ast::CaseWhen;
Rust
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).

Also implements From<CaseWhen>.
use utopia_query::ast::Cast;
Rust
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).

Also implements From<Cast>.
use utopia_query::ast::Column;
Rust
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).

Also implements From<Column>.
use utopia_query::ast::ColumnValidator;
Rust
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;
Rust
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).

Also implements From<Conditional>.
use utopia_query::ast::Cte;
Rust
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;
Rust
pub struct Exists {
    pub subquery: Box<Select>,
    pub negated: bool,
}

[NOT] EXISTS (subquery).

PHP: Utopia\Query\AST\Expression\Exists (subquery, negated).

Also implements From<Exists>.
use utopia_query::ast::FilterInjector;
Rust
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;
Rust
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).

Also implements From<Func>.
use utopia_query::ast::Grammar;
Rust
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;
Rust
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).

Also implements From<In>.
use utopia_query::ast::JoinClause;
Rust
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;
Rust
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).

Also implements From<Literal>.
use utopia_query::ast::OrderByItem;
Rust
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;
Rust
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.

Rust
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 == ">"));
PHP
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;
Rust
pub struct Placeholder {
    pub value: String,
}

A bound parameter placeholder, written as is (?, :name, $1).

PHP: Utopia\Query\AST\Placeholder (value).

Also implements From<Placeholder>.
use utopia_query::ast::Raw;
Rust
pub struct Raw {
    pub sql: String,
}

SQL written as is.

PHP: Utopia\Query\AST\Raw (sql).

Also implements From<Raw>.
use utopia_query::ast::Select;
Rust
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;
Rust
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.

Rust
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"#);
PHP
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` = 1
Also implements Default.
use utopia_query::ast::Star;
Rust
pub struct Star {
    pub table: Option<String>,
    pub schema: Option<String>,
}

*, table.* or schema.table.*.

PHP: Utopia\Query\AST\Star (table, schema).

Also implements From<Star>.
use utopia_query::ast::Subquery;
Rust
pub struct Subquery {
    pub query: Box<Select>,
}

A scalar subquery: (SELECT ...).

PHP: Utopia\Query\AST\Expression\Subquery (query).

Also implements From<Subquery>.
use utopia_query::ast::SubquerySource;
Rust
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).

Also implements From<SubquerySource>.
use utopia_query::ast::Table;
Rust
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).

Also implements From<Table>.
use utopia_query::ast::TableRenamer;
Rust
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;
Rust
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).

Also implements From<Unary>.
use utopia_query::ast::Walker;
Rust
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.

Rust
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");
PHP
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` = 1
use utopia_query::ast::Window;
Rust
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).

Also implements From<Window>.
use utopia_query::ast::WindowDefinition;
Rust
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;
Rust
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;
Rust
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.

Also implements 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;
Rust
pub enum InList {
    Values(Vec<Expression>),
    Subquery(Box<Select>),
}

What an IN tests against.

PHP: In::$list, Expression[]|Select.

use utopia_query::ast::TableSource;
Rust
pub enum TableSource {
    Table(Table),
    Subquery(SubquerySource),
}

What a FROM or a join reads: a table or a subquery.

PHP: Table|SubquerySource.

Also implements From<Table>, From<SubquerySource>.
use utopia_query::ast::Visitor;
Rust
pub trait Visitor

Inspects 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.