builder
ModuleQuery 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;pub enum AstDialectWhich AST serializer a builder converts with (toAst/fromAst).
use utopia_query::builder::AnyBuilder;pub trait AnyBuilder: Send + SyncAny builder, as other builders and schemas take one (a subquery, a union member, a view's query).
builder::api
Own pageThe public API every builder has: selects, aggregates, joins, unions, CTEs, inserts, updates, deletes, hooks and window functions.
builder::ast
Own pageA 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;pub struct CaseExpressionA CASE expression: WHEN clauses in order, an optional ELSE and an alias.
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;pub struct WhenClauseOne WHEN ... THEN ... clause.
builder::clickhouse
Own pageClickHouse: 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;pub struct ClickHouseDialectThe ClickHouse dialect and its own state.
use utopia_query::builder::clickhouse::FormattedInsertStatement;pub struct FormattedInsertStatementAn 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.
Deref.use utopia_query::builder::clickhouse::DeleteMode;pub enum DeleteModeWhich DELETE form Builder::delete emits.
pub type ClickHouse = Builder<ClickHouseDialect>A ClickHouse builder.
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 pageuse utopia_query::builder::core::Builder;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.
Clone, Default.use utopia_query::builder::core::Core;pub struct CoreUndocumented.
use utopia_query::builder::core::ExistsSubquery;pub struct ExistsSubquery[NOT] EXISTS (subquery).
use utopia_query::builder::core::ExplainOptions;pub struct ExplainOptionsThe options of EXPLAIN beyond ANALYZE, for the dialects that have them.
use utopia_query::builder::core::LateralJoin;pub struct LateralJoin[LEFT] JOIN LATERAL (subquery) AS alias ON true.
use utopia_query::builder::core::SubSelect;pub struct SubSelectA builder used as a source: FROM (subquery) AS alias, a select-list
subquery.
use utopia_query::builder::core::WhereInSubquery;pub struct WhereInSubqueryUndocumented.
use utopia_query::builder::core::Dialect;pub trait Dialect: Clone + Default + Send + Sync + Sized + 'staticUndocumented.
pub type AfterBuild = Arc<dyn Fn(Statement) -> Result<Statement> + Send + Sync>A callback run on every built statement, returning the statement to use.
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 pageWhat 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;pub trait BitwiseAggregates: DialectBIT_AND, BIT_OR, BIT_XOR.
use utopia_query::builder::feature::ConditionalAggregates;pub trait ConditionalAggregates: DialectCOUNT(CASE WHEN ... THEN 1 END) and the other conditional aggregates.
use utopia_query::builder::feature::CrossJoins;pub trait CrossJoins: DialectCROSS JOIN and NATURAL JOIN.
use utopia_query::builder::feature::Cube;pub trait Cube: DialectGROUP BY CUBE(...) / WITH CUBE.
use utopia_query::builder::feature::FullOuterJoins;pub trait FullOuterJoins: DialectFULL OUTER JOIN.
use utopia_query::builder::feature::FullTextSearch;pub trait FullTextSearch: DialectFull-text search.
use utopia_query::builder::feature::Hints;pub trait Hints: DialectOptimizer hints.
use utopia_query::builder::feature::InsertOrIgnore;pub trait InsertOrIgnore: DialectUndocumented.
use utopia_query::builder::feature::Json;pub trait Json: DialectJSON filters and JSON column updates.
use utopia_query::builder::feature::LateralJoins;pub trait LateralJoins: DialectJOIN LATERAL (subquery).
use utopia_query::builder::feature::Locking;pub trait Locking: DialectFOR UPDATE, FOR SHARE and their SKIP LOCKED / NOWAIT forms.
use utopia_query::builder::feature::NegatedFullTextSearch;pub trait NegatedFullTextSearch: DialectUndocumented.
use utopia_query::builder::feature::RawSql;pub trait RawSql: DialectRaw SQL in select, where, group, having and order clauses, casts, CASE
expressions and raw assignments.
use utopia_query::builder::feature::Returning;pub trait Returning: DialectRETURNING after inserts, updates and deletes.
use utopia_query::builder::feature::Rollup;pub trait Rollup: DialectGROUP BY ... WITH ROLLUP / ROLLUP(...).
use utopia_query::builder::feature::Sequences;pub trait Sequences: DialectAnd currVal() of sequences.
use utopia_query::builder::feature::Spatial;pub trait Spatial: DialectSpatial filters.
use utopia_query::builder::feature::StatisticalAggregates;pub trait StatisticalAggregates: DialectSTDDEV, VARIANCE and their population/sample forms.
use utopia_query::builder::feature::StringAggregates;pub trait StringAggregates: DialectGROUP_CONCAT / STRING_AGG, JSON_ARRAYAGG, JSON_OBJECTAGG.
use utopia_query::builder::feature::TableSampling;pub trait TableSampling: DialectTABLESAMPLE / SAMPLE.
use utopia_query::builder::feature::Totals;pub trait Totals: DialectWITH TOTALS (ClickHouse).
use utopia_query::builder::feature::Transactions;pub trait Transactions: DialectBEGIN, COMMIT, ROLLBACK and savepoints.
use utopia_query::builder::feature::Upsert;pub trait Upsert: DialectUndocumented.
use utopia_query::builder::feature::UpsertSelect;pub trait UpsertSelect: DialectUndocumented.
builder::join
Own page[JoinBuilder]: the conditions of a join built with a closure.
use utopia_query::builder::join::JoinBuilder;pub struct JoinBuilderThe conditions of one join: column comparisons (on) and conditions
with bindings (where, raw SQL).
builder::mariadb
Own pageMariaDB: MariaDb, MySQL with RETURNING, sequences, its own geometry
constructor and ST_DISTANCE_SPHERE for distances in meters.
use utopia_query::builder::mariadb::MariaDbDialect;pub struct MariaDbDialectThe MariaDB dialect: MySQL's state.
pub type MariaDb = Builder<MariaDbDialect>A MariaDB builder.
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 pageMongoDB: 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;pub struct MongoDbDialectThe MongoDB dialect, and its own state: update operators, pipeline stages, search stages and the index hint.
use utopia_query::builder::mongodb::UpdateOperation;pub struct UpdateOperationAn update operator with its fields (field => value).
use utopia_query::builder::mongodb::IndexHint;pub enum IndexHintThe index a query must use: a name, or a key pattern ({"name": 1}).
From.pub type MongoDb = Builder<MongoDbDialect>A MongoDB builder: compiles to operation documents (JSON).
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 pageMySQL: MySql, and the behaviour MariaDB shares (MySqlFamily).
use utopia_query::builder::mysql::MySqlDialect;pub struct MySqlDialectThe MySQL dialect.
use utopia_query::builder::mysql::MySqlState;pub struct MySqlStateMySQL's own state: the join of a multi-table update or delete.
use utopia_query::builder::mysql::MySqlFamily;pub trait MySqlFamily: SqlDialectWhat MySQL and MariaDB share: their state, and the geometry constructor.
pub type MySql = Builder<MySqlDialect>A MySQL builder.
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 pageMySQL's JSON column updates, shared with MariaDB.
builder::postgresql
Own pagePostgreSQL: 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;pub struct DeleteUsingThe table of DELETE ... USING, with an extra condition.
use utopia_query::builder::postgresql::MergeTarget;pub struct MergeTargetThe target, source and condition of a MERGE.
use utopia_query::builder::postgresql::PostgreSqlDialect;pub struct PostgreSqlDialectThe PostgreSQL dialect and its own state.
use utopia_query::builder::postgresql::UpdateFrom;pub struct UpdateFromThe table joined by UPDATE ... FROM, with an extra condition.
pub type PostgreSql = Builder<PostgreSqlDialect>A PostgreSQL builder.
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 pageWhat 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;pub trait SqlDialect: DialectThe 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;pub fn geometry_to_wkt(geometry: &Array) -> Result<String>Undocumented.
builder::sqlite
Own pageSQLite: 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;pub struct SqliteDialectThe SQLite dialect.
pub type Sqlite = Builder<SqliteDialect>A SQLite builder.
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 pageThe values builders produce and keep: statements, conditions, join and window definitions.
use utopia_query::builder::types::Binding;pub struct BindingA 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;pub struct ColumnPredicateleft operator right, both columns.
use utopia_query::builder::types::Condition;pub struct ConditionA SQL fragment with its bindings.
use utopia_query::builder::types::CteClause;pub struct CteClauseA common table expression, compiled.
use utopia_query::builder::types::JoinOn;pub struct JoinOnA column-to-column condition of a join built with a JoinBuilder.
use utopia_query::builder::types::MergeClause;pub struct MergeClauseA MERGE action and its bindings.
use utopia_query::builder::types::SpatialDistanceFilter;pub struct SpatialDistanceFilterThe geometry, distance and unit of a distance* query.
use utopia_query::builder::types::Statement;pub struct StatementA compiled statement: the SQL (or MongoDB command JSON) with ?
placeholders and the values bound to them, in order.
Debug, PartialEq.use utopia_query::builder::types::UnionClause;pub struct UnionClauseA compiled member of a compound select.
use utopia_query::builder::types::WindowDefinition;pub struct WindowDefinitionA named window: WINDOW name AS (...).
use utopia_query::builder::types::WindowFrame;pub struct WindowFrameA window frame: ROWS UNBOUNDED PRECEDING, RANGE BETWEEN ... AND ....
use utopia_query::builder::types::WindowSelect;pub struct WindowSelectA window function in the select list.
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).