A first query
This page shows one complete query, from the code to the SQL to the result, and the ideas every other page builds on: queries are values, paths are typed, and the SQL is always visible. Read it first, even if you know Django well: several habits do not carry over.
The query
#![allow(unused)]
fn main() {
// sample/tests/db.rs
use network_models::Station;
use rind::prelude::*;
let open = Query::<Station>::new()
.filter(Station::status().eq("open"))
.order_by([Station::name().asc()])
.limit(20);
let stations: Vec<Station> = db.all(&open).await?;
let first: Option<Station> = db.first(&open).await?;
let how_many: i64 = db.count(&open).await?;
}
Query::<Station>::new() is every station: Django’s
Station.objects.all(). Each method returns a new query, so open can be
kept and run three times, as here. db.all(&open) sends:
SELECT "t0"."id", "t0"."code", "t0"."name", "t0"."city", "t0"."status", "t0"."platforms",
"t0"."services", "t0"."opened", "t0"."region_id", "t0"."manager_id", "t0"."photo", "t0"."position"
FROM "network_station" AS "t0"
WHERE "t0"."status" = $1
ORDER BY "t0"."name"
LIMIT 20
-- params: [Text("open")]
and answers the stations 3, 6, 1, 2 and 5 (Brest, Milano Centrale, Paris
Montparnasse, Rennes, Toulouse Matabiau). first answers Brest, and
count answers 5.
Three things to notice:
- The table is always aliased
t0. Joined tables get the name of the relation (origin,destination__region), and sub-queriest1,t2. You never write these names, but you will see them in the SQL. - Values are always parameters (
$1), never written into the SQL text. There is no way to inject SQL through a value. - Every column of the model is read, in the order of the struct. Choosing the columns shows how to read fewer.
Queries are values, not lazy objects
A Django QuerySet is lazy: it runs when you iterate it, slice it,
len() it or print it, sometimes when you do not expect it. A rind
Query never runs by itself. It is a plain value that describes SQL.
Nothing reaches the database until you give it to a Db and .await
the answer:
#![allow(unused)]
fn main() {
let q = Query::<Station>::new().filter(Station::city().eq("Paris")); // nothing runs
let q = q.order_by([Station::name().asc()]); // still nothing
let rows = db.all(&q).await?; // one query, here
}
So you always see, in the code, where the database is read, and there is no cache on a query: running it twice sends it twice.
A query can be built in one function and completed in another. This is
how scopes work: Reservation::made_by(user)
returns a query, and the caller adds its own filters.
Seeing the SQL
to_sql() gives the SQL of a query and its parameters, without running
it. It is Django’s print(qs.query), but exact:
#![allow(unused)]
fn main() {
let sql = open.to_sql()?;
println!("{}", sql.text); // the SQL
println!("{:?}", sql.params); // [Text("open")]
}
To see every statement the application sends, with its duration, set
RUST_LOG=rind::sql=debug (Logging).
Paths
The building blocks of every query are paths, functions the model derive writes for each column and each relation:
#![allow(unused)]
fn main() {
Station::status() // a column of the station
Journey::origin().city() // a column of a related row
Journey::destination().region().name() // two relations away
Train::wagons() // a "many" relation
}
A path is typed with the type of its column: Station::status() is a
Path<String>, so Station::status().eq(3) does not compile. A misspelt
column or relation does not compile either. This replaces Django’s
strings ("destination__region__name"), whose mistakes are only found
when the query runs.
What is different from Django
A few habits do not carry over. Each is explained where it matters:
- Nothing is lazy. A query runs where you
.awaitit. - There is no
get().db.first(&q).await?answers anOption; say what “none” means for you (Running). - There is no default ordering. A model has no
Meta.ordering, so a query has no order until you give one (Ordering). - There is no
select_relatednordistinct. The joins follow the paths, and filters through many relations areEXISTS, which never repeat a row (Relations). NULLfollows SQL.eq(None)matches nothing, andne(2)does not match rows where the column isNULL. Useis_null()anddistinct_from(Conditions).- There is no cache on a query, and no hidden query when you touch a field: a model holds its columns, never its related rows.
The whole correspondence between Django’s QuerySet and rind, line by
line, is in the Reference.
Next: Running a query.