Rust

builder

Module

Query builders: compile Query lists, and the builder's own clauses, into statements for each dialect.

A Builder is generic over its Dialect; the dialects are type aliases (MySql, ...). Features only some dialects have are traits in [feature]: a builder has their methods when its dialect implements them.

Contents

15 submodules, and what the module defines itself.

use utopia_query::builder::AstDialect;
Rust
pub enum AstDialect

Which AST serializer a builder converts with (toAst/fromAst).

use utopia_query::builder::AnyBuilder;
Rust
pub trait AnyBuilder: Send + Sync

Any builder, as other builders and schemas take one (a subquery, a union member, a view's query).

Implemented byBuilder

builder::api

Own page

The public API every builder has: selects, aggregates, joins, unions, CTEs, inserts, updates, deletes, hooks and window functions.

builder::ast

Own page

A builder as a syntax tree and back: Builder::to_ast and Builder::from_ast.

builder::case

Own page

[CaseExpression]: CASE WHEN ... THEN ... ELSE ... END, built clause by clause and compiled with bindings by a builder.

use utopia_query::builder::case::CaseExpression;
Rust
pub struct CaseExpression

A CASE expression: WHEN clauses in order, an optional ELSE and an alias.

Rust
use utopia_query::builder::{CaseExpression, MySql, Operator};

let mut case = CaseExpression::new();
case.when("status", Operator::Equal, "active", 1).else_(0).alias("is_active");
let statement = MySql::new().from("users", "").select_case(case).build()?;
assert_eq!(statement.query, "SELECT CASE WHEN `status` = ? THEN ? ELSE ? END AS `is_active` FROM `users`");
use utopia_query::builder::case::WhenClause;
Rust
pub struct WhenClause

One WHEN ... THEN ... clause.

builder::clickhouse

Own page

ClickHouse: ClickHouse, its bulk-insert Formats and FormattedInsertStatement, and the ASOF join AsofOperator.

ClickHouse extends the base builder directly (not the SQL dialects): it adds PREWHERE, FINAL, SAMPLE, ARRAY JOIN, ASOF JOIN, LIMIT ... BY, WITH FILL, SETTINGS, the -If conditional aggregates, the approximate aggregates (quantile, uniq, topK, ...), mutations (ALTER TABLE ... UPDATE / DELETE), FORMAT inserts and named, typed placeholders ({param0:Int64}).

use utopia_query::builder::clickhouse::ClickHouseDialect;
Rust
pub struct ClickHouseDialect

The ClickHouse dialect and its own state.

use utopia_query::builder::clickhouse::FormattedInsertStatement;
Rust
pub struct FormattedInsertStatement

An INSERT INTO table [(columns)] FORMAT name envelope (no bindings), with the format, the columns and, from Builder::bulk_insert, the serialized rows to send with it.

It is a Statement (it derefs to one) with three more fields.

Also implements Deref.
use utopia_query::builder::clickhouse::DeleteMode;
Rust
pub enum DeleteMode

Which DELETE form Builder::delete emits.

Rust
pub type ClickHouse = Builder<ClickHouseDialect>

A ClickHouse builder.

Rust
use utopia_query::Query;
use utopia_query::builder::ClickHouse;

let statement = ClickHouse::new()
    .from("events", "")
    .final_()
    .sample(0.1)?
    .prewhere([Query::equal("type", ["click"])])
    .filter([Query::greater_than("count", 5)])
    .build()?;
assert_eq!(
    statement.query,
    "SELECT * FROM `events` FINAL SAMPLE 0.1 PREWHERE `type` IN (?) WHERE `count` > ?"
);

builder::core

Own page
use utopia_query::builder::core::Builder;
Rust
pub struct Builder<D: Dialect>

A query builder for one dialect: from a table, with queries (filters, ordering, pagination, aggregates, joins) and the builder's own clauses (subqueries, raw SQL, window functions, CTEs, unions), compiled by Builder::build into a Statement; also inserts, updates, deletes and upserts.

The dialects are type aliases: MySql and the others. Features only some dialects have are traits in feature.

Also implements Clone, Default.
use utopia_query::builder::core::Core;
Rust
pub struct Core

Undocumented.

use utopia_query::builder::core::ExistsSubquery;
Rust
pub struct ExistsSubquery

[NOT] EXISTS (subquery).

use utopia_query::builder::core::ExplainOptions;
Rust
pub struct ExplainOptions

The options of EXPLAIN beyond ANALYZE, for the dialects that have them.

use utopia_query::builder::core::LateralJoin;
Rust
pub struct LateralJoin

[LEFT] JOIN LATERAL (subquery) AS alias ON true.

use utopia_query::builder::core::SubSelect;
Rust
pub struct SubSelect

A builder used as a source: FROM (subquery) AS alias, a select-list subquery.

use utopia_query::builder::core::WhereInSubquery;
Rust
pub struct WhereInSubquery

Undocumented.

use utopia_query::builder::core::Dialect;
Rust
pub trait Dialect: Clone + Default + Send + Sync + Sized + 'static

Undocumented.

Rust
pub type AfterBuild = Arc<dyn Fn(Statement) -> Result<Statement> + Send + Sync>

A callback run on every built statement, returning the statement to use.

Rust
pub type BeforeBuild<D> = Arc<dyn Fn(&mut Builder<D>) -> Result<()> + Send + Sync>

A callback run at the start of every build, with the builder.

builder::feature

Own page

What only some dialects can do: each feature is a trait a dialect implements, and Builder has the feature's methods for the dialects that implement it (so MySql::new().hint(...) compiles and a ClickHouse builder has prewhere, while a MongoDB builder has neither).

use utopia_query::builder::feature::BitwiseAggregates;
Rust
pub trait BitwiseAggregates: Dialect

BIT_AND, BIT_OR, BIT_XOR.

use utopia_query::builder::feature::ConditionalAggregates;
Rust
pub trait ConditionalAggregates: Dialect

COUNT(CASE WHEN ... THEN 1 END) and the other conditional aggregates.

use utopia_query::builder::feature::CrossJoins;
Rust
pub trait CrossJoins: Dialect

CROSS JOIN and NATURAL JOIN.

use utopia_query::builder::feature::Cube;
Rust
pub trait Cube: Dialect

GROUP BY CUBE(...) / WITH CUBE.

use utopia_query::builder::feature::FullOuterJoins;
Rust
pub trait FullOuterJoins: Dialect

FULL OUTER JOIN.

use utopia_query::builder::feature::FullTextSearch;
Rust
pub trait FullTextSearch: Dialect

Full-text search.

Implemented byMongoDbDialect
use utopia_query::builder::feature::Hints;
Rust
pub trait Hints: Dialect

Optimizer hints.

use utopia_query::builder::feature::InsertOrIgnore;
Rust
pub trait InsertOrIgnore: Dialect

Undocumented.

use utopia_query::builder::feature::Json;
Rust
pub trait Json: Dialect

JSON filters and JSON column updates.

use utopia_query::builder::feature::LateralJoins;
Rust
pub trait LateralJoins: Dialect

JOIN LATERAL (subquery).

use utopia_query::builder::feature::Locking;
Rust
pub trait Locking: Dialect

FOR UPDATE, FOR SHARE and their SKIP LOCKED / NOWAIT forms.

use utopia_query::builder::feature::NegatedFullTextSearch;
Rust
pub trait NegatedFullTextSearch: Dialect

Undocumented.

use utopia_query::builder::feature::RawSql;
Rust
pub trait RawSql: Dialect

Raw SQL in select, where, group, having and order clauses, casts, CASE expressions and raw assignments.

use utopia_query::builder::feature::Returning;
Rust
pub trait Returning: Dialect

RETURNING after inserts, updates and deletes.

use utopia_query::builder::feature::Rollup;
Rust
pub trait Rollup: Dialect

GROUP BY ... WITH ROLLUP / ROLLUP(...).

use utopia_query::builder::feature::Sequences;
Rust
pub trait Sequences: Dialect

And currVal() of sequences.

use utopia_query::builder::feature::Spatial;
Rust
pub trait Spatial: Dialect

Spatial filters.

use utopia_query::builder::feature::StatisticalAggregates;
Rust
pub trait StatisticalAggregates: Dialect

STDDEV, VARIANCE and their population/sample forms.

use utopia_query::builder::feature::StringAggregates;
Rust
pub trait StringAggregates: Dialect

GROUP_CONCAT / STRING_AGG, JSON_ARRAYAGG, JSON_OBJECTAGG.

use utopia_query::builder::feature::TableSampling;
Rust
pub trait TableSampling: Dialect

TABLESAMPLE / SAMPLE.

use utopia_query::builder::feature::Totals;
Rust
pub trait Totals: Dialect

WITH TOTALS (ClickHouse).

Implemented byClickHouseDialect
use utopia_query::builder::feature::Transactions;
Rust
pub trait Transactions: Dialect

BEGIN, COMMIT, ROLLBACK and savepoints.

use utopia_query::builder::feature::Upsert;
Rust
pub trait Upsert: Dialect

Undocumented.

use utopia_query::builder::feature::UpsertSelect;
Rust
pub trait UpsertSelect: Dialect

Undocumented.

builder::join

Own page

[JoinBuilder]: the conditions of a join built with a closure.

use utopia_query::builder::join::JoinBuilder;
Rust
pub struct JoinBuilder

The conditions of one join: column comparisons (on) and conditions with bindings (where, raw SQL).

builder::mariadb

Own page

MariaDB: MariaDb, MySQL with RETURNING, sequences, its own geometry constructor and ST_DISTANCE_SPHERE for distances in meters.

use utopia_query::builder::mariadb::MariaDbDialect;
Rust
pub struct MariaDbDialect

The MariaDB dialect: MySQL's state.

Rust
pub type MariaDb = Builder<MariaDbDialect>

A MariaDB builder.

Rust
use utopia_query::Query;
use utopia_query::builder::MariaDb;

let statement = MariaDb::new()
    .from("users", "")
    .filter([Query::equal("id", [1])])
    .returning(["id"])
    .delete()?;
assert_eq!(statement.query, "DELETE FROM `users` WHERE `id` IN (?) RETURNING `id`");

builder::mongodb

Own page

MongoDB: MongoDb, a builder that compiles to MongoDB operation documents (JSON) instead of SQL.

A select compiles to a find (filter, projection, sort, skip, limit) or, when it needs stages a find cannot express (grouping, joins, window functions, unions, subqueries, search, pipeline stages), to an aggregate pipeline. Writes compile to insertMany, updateMany, updateOne (upserts) and deleteMany. Values are bound as ? strings in the document, in order, as with the SQL builders.

use utopia_query::builder::mongodb::MongoDbDialect;
Rust
pub struct MongoDbDialect

The MongoDB dialect, and its own state: update operators, pipeline stages, search stages and the index hint.

use utopia_query::builder::mongodb::UpdateOperation;
Rust
pub struct UpdateOperation

An update operator with its fields (field => value).

use utopia_query::builder::mongodb::IndexHint;
Rust
pub enum IndexHint

The index a query must use: a name, or a key pattern ({"name": 1}).

Also implements From.
Rust
pub type MongoDb = Builder<MongoDbDialect>

A MongoDB builder: compiles to operation documents (JSON).

Rust
use utopia_query::Query;
use utopia_query::builder::MongoDb;

let statement = MongoDb::new()
    .from("users", "")
    .select(["name"])
    .filter([Query::greater_than("age", 18)])
    .sort_desc("age", None)
    .limit(10)
    .build()?;
assert_eq!(
    statement.query,
    r#"{"collection":"users","operation":"find","filter":{"age":{"$gt":"?"}},"projection":{"name":1,"_id":0},"sort":{"age":-1},"limit":10}"#
);
assert_eq!(statement.bindings, vec![18.into()]);

builder::mysql

Own page

MySQL: MySql, and the behaviour MariaDB shares (MySqlFamily).

use utopia_query::builder::mysql::MySqlDialect;
Rust
pub struct MySqlDialect

The MySQL dialect.

use utopia_query::builder::mysql::MySqlState;
Rust
pub struct MySqlState

MySQL's own state: the join of a multi-table update or delete.

use utopia_query::builder::mysql::MySqlFamily;
Rust
pub trait MySqlFamily: SqlDialect

What MySQL and MariaDB share: their state, and the geometry constructor.

Rust
pub type MySql = Builder<MySqlDialect>

A MySQL builder.

Rust
use utopia_query::Query;
use utopia_query::builder::MySql;

let statement = MySql::new().from("t", "").filter([Query::equal("status", ["active", "pending"])]).build()?;
assert_eq!(statement.query, "SELECT * FROM `t` WHERE `status` IN (?, ?)");

builder::mysql::json_sets

Own page

MySQL's JSON column updates, shared with MariaDB.

builder::postgresql

Own page

PostgreSQL: PostgreSql, with DISTINCT ON, MERGE, UPDATE ... FROM, DELETE ... USING, RETURNING, pgvector ordering, JSONB filters and updates, FILTER (WHERE ...) aggregates and ordered-set aggregates.

use utopia_query::builder::postgresql::DeleteUsing;
Rust
pub struct DeleteUsing

The table of DELETE ... USING, with an extra condition.

use utopia_query::builder::postgresql::MergeTarget;
Rust
pub struct MergeTarget

The target, source and condition of a MERGE.

use utopia_query::builder::postgresql::PostgreSqlDialect;
Rust
pub struct PostgreSqlDialect

The PostgreSQL dialect and its own state.

use utopia_query::builder::postgresql::UpdateFrom;
Rust
pub struct UpdateFrom

The table joined by UPDATE ... FROM, with an extra condition.

Rust
pub type PostgreSql = Builder<PostgreSqlDialect>

A PostgreSQL builder.

Rust
use utopia_query::Query;
use utopia_query::builder::PostgreSql;

let statement = PostgreSql::new()
    .from("users", "")
    .distinct_on(["email"])
    .filter([Query::starts_with("name", "Al")])
    .build()?;
assert_eq!(statement.query, r#"SELECT DISTINCT ON ("email") * FROM "users" WHERE "name" ILIKE ?"#);

builder::sql

Own page

What the SQL dialects (MySQL, MariaDB, PostgreSQL, SQLite) share beyond the base builder: full-text search, spatial, JSON and array filters, and the upsert conflict clause.

use utopia_query::builder::sql::SqlDialect;
Rust
pub trait SqlDialect: Dialect

The hooks a SQL dialect implements: how it compiles search, spatial and JSON predicates, and its conflict clause.

use utopia_query::builder::sql::geometry_to_wkt;
Rust
pub fn geometry_to_wkt(geometry: &Array) -> Result<String>

Undocumented.

builder::sqlite

Own page

SQLite: Sqlite, with INSERT OR IGNORE, ON CONFLICT ... excluded, json_each JSON filters and updates, and no regex, full-text or spatial filters.

use utopia_query::builder::sqlite::SqliteDialect;
Rust
pub struct SqliteDialect

The SQLite dialect.

Rust
pub type Sqlite = Builder<SqliteDialect>

A SQLite builder.

Rust
use utopia_query::Query;
use utopia_query::builder::Sqlite;

let statement = Sqlite::new().from("users", "").filter([Query::regex("name", "^a")]).build();
assert_eq!(statement.unwrap_err().to_string(), "REGEXP is not natively supported in SQLite.");

let statement = Sqlite::new().from("users", "").sort_random().limit(5).build()?;
assert_eq!(statement.query, "SELECT * FROM `users` ORDER BY RANDOM() LIMIT ?");

builder::types

Own page

The values builders produce and keep: statements, conditions, join and window definitions.

use utopia_query::builder::types::Binding;
Rust
pub struct Binding

A binding captured while compiling: the value and the column it was compared to, when known (ClickHouse types named parameters by column).

use utopia_query::builder::types::ColumnPredicate;
Rust
pub struct ColumnPredicate

left operator right, both columns.

use utopia_query::builder::types::Condition;
Rust
pub struct Condition

A SQL fragment with its bindings.

use utopia_query::builder::types::CteClause;
Rust
pub struct CteClause

A common table expression, compiled.

use utopia_query::builder::types::JoinOn;
Rust
pub struct JoinOn

A column-to-column condition of a join built with a JoinBuilder.

use utopia_query::builder::types::MergeClause;
Rust
pub struct MergeClause

A MERGE action and its bindings.

use utopia_query::builder::types::SpatialDistanceFilter;
Rust
pub struct SpatialDistanceFilter

The geometry, distance and unit of a distance* query.

use utopia_query::builder::types::Statement;
Rust
pub struct Statement

A compiled statement: the SQL (or MongoDB command JSON) with ? placeholders and the values bound to them, in order.

Also implements Debug, PartialEq.
use utopia_query::builder::types::UnionClause;
Rust
pub struct UnionClause

A compiled member of a compound select.

use utopia_query::builder::types::WindowDefinition;
Rust
pub struct WindowDefinition

A named window: WINDOW name AS (...).

use utopia_query::builder::types::WindowFrame;
Rust
pub struct WindowFrame

A window frame: ROWS UNBOUNDED PRECEDING, RANGE BETWEEN ... AND ....

use utopia_query::builder::types::WindowSelect;
Rust
pub struct WindowSelect

A window function in the select list.

Rust
pub type Executor = Arc<dyn Fn(&Statement) -> Result<Value> + Send + Sync>

What runs a statement: given it, returns its rows (an array) or an affected-row count (an integer).