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.

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"
);

Contents

4 submodules.

ast::node

Own page

The nodes of the syntax tree.

use utopia_query::ast::node::Aliased;
Rust
pub struct Aliased

An expression with an alias: expression AS alias.

use utopia_query::ast::node::Between;
Rust
pub struct Between

expression [NOT] BETWEEN low AND high.

use utopia_query::ast::node::Binary;
Rust
pub struct Binary

A binary operation: left operator right.

use utopia_query::ast::node::CaseWhen;
Rust
pub struct CaseWhen

One WHEN condition THEN result of a CASE.

use utopia_query::ast::node::Cast;
Rust
pub struct Cast

CAST(expression AS type) (or PostgreSQL's expression::type).

use utopia_query::ast::node::Column;
Rust
pub struct Column

A column reference: [schema.][table.]name.

use utopia_query::ast::node::Conditional;
Rust
pub struct Conditional

CASE [operand] WHEN ... THEN ... [ELSE ...] END.

use utopia_query::ast::node::Cte;
Rust
pub struct Cte

A common table expression: name [(columns)] AS (query).

use utopia_query::ast::node::Exists;
Rust
pub struct Exists

[NOT] EXISTS (subquery).

use utopia_query::ast::node::Func;
Rust
pub struct Func

A function call: NAME([DISTINCT] args) [FILTER (WHERE ...)].

use utopia_query::ast::node::In;
Rust
pub struct In

Undocumented.

use utopia_query::ast::node::JoinClause;
Rust
pub struct JoinClause

A join: TYPE source [ON condition].

use utopia_query::ast::node::Literal;
Rust
pub struct Literal

A literal: a string, an integer, a float, a boolean or NULL.

use utopia_query::ast::node::OrderByItem;
Rust
pub struct OrderByItem

One ORDER BY item: expression ASC|DESC [NULLS FIRST|LAST].

use utopia_query::ast::node::Placeholder;
Rust
pub struct Placeholder

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

use utopia_query::ast::node::Raw;
Rust
pub struct Raw

SQL written as is.

use utopia_query::ast::node::Select;
Rust
pub struct Select

A SELECT statement.

use utopia_query::ast::node::Star;
Rust
pub struct Star

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

use utopia_query::ast::node::Subquery;
Rust
pub struct Subquery

A scalar subquery: (SELECT ...).

use utopia_query::ast::node::SubquerySource;
Rust
pub struct SubquerySource

A subquery used as a table: (SELECT ...) AS alias.

use utopia_query::ast::node::Table;
Rust
pub struct Table

A table reference: [schema.]name [AS alias].

use utopia_query::ast::node::Unary;
Rust
pub struct Unary

A unary operation: operator (operand) when prefix, else operand operator (IS NULL, IS NOT NULL).

use utopia_query::ast::node::Window;
Rust
pub struct Window

A window function call: function OVER name or function OVER (specification).

use utopia_query::ast::node::WindowDefinition;
Rust
pub struct WindowDefinition

A named window: WINDOW name AS (specification).

use utopia_query::ast::node::WindowSpecification;
Rust
pub struct WindowSpecification

A window: [PARTITION BY ...] [ORDER BY ...] [ROWS|RANGE frame].

use utopia_query::ast::node::Expression;
Rust
pub enum Expression

An expression: a column, a literal, an operation, a function call, a subquery.

use utopia_query::ast::node::InList;
Rust
pub enum InList

What an IN tests against.

use utopia_query::ast::node::TableSource;
Rust
pub enum TableSource

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

Also implements From.

ast::parser

Own page

[Parser]: tokens to a Select.

use utopia_query::ast::parser::Parser;
Rust
pub struct Parser

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.

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 == ">"));

ast::serializer

Own page

[Serializer]: a Select back to SQL.

use utopia_query::ast::serializer::Serializer;
Rust
pub struct Serializer

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.

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"#);
Also implements Default.

ast::walker

Own page

Walker and [Visitor]: rewriting a tree, and the visitors the library ships.

use utopia_query::ast::walker::ColumnValidator;
Rust
pub struct ColumnValidator

Rejects columns outside an allow-list, and * unless allowed.

use utopia_query::ast::walker::FilterInjector;
Rust
pub struct FilterInjector

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.

use utopia_query::ast::walker::TableRenamer;
Rust
pub struct TableRenamer

Renames tables: table references (name and alias) and the table qualifier of columns and table.*.

use utopia_query::ast::walker::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.

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");
use utopia_query::ast::walker::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.