Rust

Query

Queries as data, compiled to SQL (MySQL, MariaDB, PostgreSQL, SQLite, ClickHouse) and MongoDB commands; schema builders; a SQL tokenizer, parser, serializer and statement classifier.
Rust 23,578 lines (16,481 code)split
PartCodeCommentsBlankTotalFiles
Rust source16,4815,1071,99023,57847
Rust tests991101105

Comments include doc comments. Rust tests are tests/ and #[cfg(test)] modules.

Install#

The crate lives in the Appwrite repository; depend on it from Git.

Cargo.toml
[dependencies]
utopia-query = { git = "https://github.com/appwrite/appwrite" }

Getting started#

Common tasks with Query, each a complete program you can copy and run.

Queries are data: a filter, an order, a page or a join is a Query you can build in code, receive as JSON from a client, validate, and compile for the database you run. This library turns lists of queries into SQL for MySQL, MariaDB, PostgreSQL, SQLite and ClickHouse, and into MongoDB commands, always with the values as bindings. It also writes DDL, and reads SQL back with a tokenizer, a parser and a classifier.

Build a select

Start a builder for your dialect, name the table, add queries, and build: the statement has the SQL with ? placeholders and the values bound to them, in order.

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

let statement = MySql::new()
    .from("users", "")
    .select(["name", "email"])
    .filter([Query::equal("status", ["active"]), Query::greater_than("age", 18)])
    .sort_asc("name", None)
    .limit(25)
    .build()?;
assert_eq!(
    statement.query,
    "SELECT `name`, `email` FROM `users` WHERE `status` IN (?) AND `age` > ? ORDER BY `name` ASC LIMIT ?"
);
assert_eq!(statement.bindings.len(), 3);

Accept queries from clients

Clients send queries as JSON. Parsing refuses raw SQL unless you allow it, so an untrusted list can only filter, order and page.

Rust
use utopia_query::{Method, Query};

let query = Query::parse(r#"{"method":"lessThan","attribute":"price","values":[100]}"#, false)?;
assert_eq!(query.method(), Method::LessThan);
assert!(Query::parse(r#"{"method":"raw","attribute":"1 = 1"}"#, false).is_err());

Scope every query to a tenant

A hook adds its condition to every statement a builder compiles, so tenancy cannot be forgotten.

Rust
use utopia_query::builder::MySql;
use utopia_query::hook::Tenant;

let statement = MySql::new().from("docs", "").add_hook(Tenant::new(["7"], "tenant_id")?)?.build()?;
assert_eq!(statement.query, "SELECT * FROM `docs` WHERE tenant_id IN (?)");

Create a table

A schema writes the DDL of the dialect: describe the table, then create it.

Rust
use utopia_query::schema::{MySql, Schema};

let mut users = MySql::new().table("users");
users.id("id");
users.string("email", 255);
assert_eq!(
    users.create()?.query,
    "CREATE TABLE `users` (`id` BIGINT UNSIGNED AUTO_INCREMENT NOT NULL, `email` VARCHAR(255) NOT NULL, PRIMARY KEY (`id`))"
);

Tell reads from writes

A classifier says whether a statement reads, writes or controls a transaction, to route it to a replica or the primary. classify reads a raw wire protocol message; classify_sql reads the SQL text.

Rust
use utopia_query::Type;
use utopia_query::classifier::{MySql, Sql};

assert_eq!(MySql.classify_sql(b"SELECT * FROM users"), Type::Read);
assert_eq!(MySql.classify_sql(b"UPDATE users SET name = 'a'"), Type::Write);

Reference#

Queries as data, and everything that turns them into statements.

A Query is one filter, order, page, selection, aggregate, join or union, as data: built in code (Query::equal(...)) or parsed from the JSON clients send (Query::parse). Builders compile lists of queries into statements for MySQL, MariaDB, PostgreSQL, SQLite, ClickHouse and MongoDB (builder), with parameter bindings, joins, aggregates, window functions, upserts and dialect features. Schema builders write DDL (schema). A SQL tokenizer (tokenizer), parser and serializer (ast) and a statement classifier (classifier) read SQL back.

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

let statement = MySql::new()
    .from("users", "")
    .select(["name", "email"])
    .filter([Query::equal("status", ["active"]), Query::greater_than("age", 18)])
    .limit(25)
    .build()?;
assert_eq!(statement.query, "SELECT `name`, `email` FROM `users` WHERE `status` IN (?) AND `age` > ? LIMIT ?");

Modules#

Each module groups one concept of the library. Internal ones hold items the crate re-exports at its root.

ast0 items
The SQL syntax tree: a parser from tokens, serializers per dialect, a walker and visitors that rewrite trees.
ast::nodeinternal
The nodes of the syntax tree.
ast::parserinternal
`Parser`: tokens to a `Select`.
ast::serializerinternal
`Serializer`: a `Select` back to SQL.
ast::walkerinternal
`Walker` and `Visitor`: rewriting a tree, and the visitors the library ships.
builder::apiinternal
The public API every builder has: selects, aggregates, joins, unions, CTEs, inserts, updates, deletes, hooks and window functions.
builder::astinternal
A builder as a syntax tree and back: `Builder::to_ast` and `Builder::from_ast`.
builder::caseinternal
`CaseExpression`: `CASE WHEN ... THEN ... ELSE ... END`, built clause by clause and compiled with bindings by a builder.
builder::clickhouseinternal
ClickHouse: `ClickHouse`, its bulk-insert `Format`s and `FormattedInsertStatement`, and the ASOF join `AsofOperator`.
builder::coreinternal
Undocumented.
builder::feature24 items
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).
builder::joininternal
`JoinBuilder`: the conditions of a join built with a closure.
builder::mariadbinternal
MariaDB: `MariaDb`, MySQL with `RETURNING`, sequences, its own geometry constructor and `ST_DISTANCE_SPHERE` for distances in meters.
builder2 items
Query builders: compile `Query`(crate::Query) lists, and the builder's own clauses, into statements for each dialect.
builder::mongodbinternal
MongoDB: `MongoDb`, a builder that compiles to MongoDB operation documents (JSON) instead of SQL.
builder::mysqlinternal
MySQL: `MySql`, and the behaviour MariaDB shares (`MySqlFamily`).
builder::mysql::json_setsinternal
MySQL's JSON column updates, shared with MariaDB.
builder::postgresqlinternal
PostgreSQL: `PostgreSql`, with `DISTINCT ON`, `MERGE`, `UPDATE ... FROM`, `DELETE ... USING`, `RETURNING`, pgvector ordering, JSONB filters and updates, `FILTER (WHERE ...)` aggregates and ordered-set aggregates.
builder::sqlinternal
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.
builder::sqliteinternal
SQLite: `Sqlite`, with `INSERT OR IGNORE`, `ON CONFLICT ... excluded`, `json_each` JSON filters and updates, and no regex, full-text or spatial filters.
builder::typesinternal
The values builders produce and keep: statements, conditions, join and window definitions.
classifier1 items
Statement classifiers: whether a wire protocol message reads, writes or controls a transaction, so a proxy can route it to a replica or the primary.
classifier::mongodbinternal
The MongoDB `OP_MSG` classifier.
classifier::mysqlinternal
The MySQL client protocol classifier.
classifier::postgresqlinternal
The PostgreSQL frontend protocol classifier.
classifier::sqlinternal
The SQL classification shared by the SQL wire protocols.
enumsinternal
Small enumerations shared across the library.
errorinternal
`Error`: why a query could not be parsed, validated or compiled.
hook9 items
Hooks: code a builder runs while compiling, to scope every query (`Filter`, `JoinFilter`) or map attribute names to columns (`Attribute`). `Tenant` and `Map` are the hooks the library ships.
methodinternal
`Method`: what a `Query`(crate::Query) does.
queryinternal
`Query`: one filter, order, page, selection, aggregate, join or union, as data; parsing it from JSON and grouping a list of them.
quoteinternal
Identifier quoting: `` `users`.`id` `` for MySQL, `"users"."id"` for PostgreSQL.
schema::baseinternal
Undocumented.
schema::clickhouseinternal
`ClickHouse`: the ClickHouse schema.
schema::column11 items
`Column`: a column of a table blueprint, with the modifiers its dialect supports.
schema::enumsinternal
The schema enumerations: column and index types, foreign-key actions, partitioning, triggers, procedure parameters and ClickHouse engines.
schema::feature17 items
What a schema can do beyond tables and indexes: each trait is one capability a dialect may implement (foreign keys, procedures, triggers, views, partitions, ...), so callers can require it in a bound.
schema::indexinternal
The value parts of a table blueprint: indexes, check constraints and column renames, and the options of a standalone `CREATE INDEX`.
schema1 items
Schema builders: DDL for tables, columns, indexes, views, procedures and triggers, per dialect.
schema::mongodbinternal
`MongoDb`: the MongoDB schema, whose statements are JSON commands.
schema::mysqlinternal
`MySql`: the MySQL / MariaDB schema.
schema::namesinternal
Undocumented.
schema::postgresqlinternal
`PostgreSql`: the PostgreSQL schema.
schema::sqliteinternal
`Sqlite`: the SQLite schema.
schema::table11 items
`Table`: a fluent table blueprint, compiled by its schema into `CREATE TABLE`, `ALTER TABLE` and the other table statements; and `ForeignKey`, a foreign key declared on it.
tokenizer3 items
SQL tokenizers: SQL text to `Token`s, per dialect.
valueinternal
Undocumented.

API#

What utopia_query exports at its root.