Utopia 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.
This library is maintained by the Appwrite team.
Getting started
[]
= { = "https://github.com/appwrite/appwrite" }
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.
use Query;
use MySql;
let statement = new
.from
.select
.filter
.sort_asc
.limit
.build?;
assert_eq!;
assert_eq!;
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.
use ;
let query = parse?;
assert_eq!;
assert!;
Scope every query to a tenant
A hook adds its condition to every statement a builder compiles, so tenancy cannot be forgotten.
use MySql;
use Tenant;
let statement = new.from.add_hook?.build?;
assert_eq!;
Create a table
A schema writes the DDL of the dialect: describe the table, then create it.
use ;
let mut users = new.table;
users.id;
users.string;
assert_eq!;
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.
use Type;
use ;
assert_eq!;
assert_eq!;
Contributing
Development happens in appwrite/appwrite, where this crate lives at crates/utopia/query. Run these commands from a checkout of it. The contributing guide covers each step.
Test
Compare with PHP
Replay the results PHP recorded for every case against Rust, without PHP:
COMPAT_LIB=query
Run every case on both runtimes, fuzz both with generated inputs, then run the whole conversion check. These need the dev stack (docker compose up -d):
Benchmark
This times every benchmark on PHP and on a release build of Rust, both in containers on the dev stack. It fails if Rust is slower. Add --write to record the run in tests/compat/query/bench.json. Run it on a quiet machine, one library at a time.
License
BSD-3-Clause. See LICENSE.