Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Choosing the columns

A query reads models: every column of the table, into the struct. Often you need less, or something else: two columns for a list, a value of a related row, a computed value. This page shows how to choose what is read.

select and rows

#![allow(unused)]
fn main() {
// sample/tests/db.rs
let select = Query::<Journey>::new()
    .select((
        Journey::code(),
        Journey::origin().city(),
        Journey::destination().region().name(),
    ))
    .order_by([Journey::id().asc()])
    .into_select();
let rows: Vec<(String, String, String)> = db.rows(&select).await?;
}
SELECT "t0"."code", "origin"."city" AS "origin__city", "destination__region"."name" AS "destination__region__name"
FROM "timetable_journey" AS "t0"
INNER JOIN "network_station" AS "destination" ON "destination"."id" = "t0"."destination_id"
INNER JOIN "network_region" AS "destination__region" ON "destination__region"."id" = "destination"."region_id"
INNER JOIN "network_station" AS "origin" ON "origin"."id" = "t0"."origin_id"
ORDER BY "t0"."id"
[("J100", "Paris", "Finistère"), ("J200", "Rennes", "Occitanie"),
 ("J300", "Brest", "France"), ("J400", "Paris", "Italia")]

This is Django’s values_list("code", "origin__city", "destination__region__name"). Three steps:

  1. select(…) says what to read: one path or expression, or a tuple of them. The joins the paths need are added, as for a filter.
  2. into_select() turns the query into a Select: a query that no longer gives models, only rows.
  3. db.rows(&select) reads each row as a tuple, of the Rust types you write.

The query keeps its filters, its order and its page: select only changes what is read.

Reading the values

db.rows reads each column as the Rust type at the same place in the tuple. The types must match the SQL types, or the read fails with error deserializing column N:

SQLRead as
biginti64
integeri32
smallinti16
double precisionf64
realf32
text, character varyingString
booleanbool
dateNaiveDate
timestamp with time zoneDateTime<Utc>
jsonbserde_json::Value
an arrayVec<…>
a column that may be NULLOption<…>

Watch out: a path to an integer column is a Path<i64>, whatever the column’s width, so that it compares with any integer. But reading a row uses the SQL type: an integer column (an i32 field) is read as an i32. Station::platforms() is selected into an i32; Station::id() into an i64.

A value that may be NULL is read as an Option. Through a nullable key, even a NOT NULL column may be missing:

#![allow(unused)]
fn main() {
let select = Query::<Journey>::new()
    .select((Journey::code(), Journey::driver().name()))
    .order_by([Journey::id().asc()])
    .into_select();
let rows: Vec<(String, Option<String>)> = db.rows(&select).await?;
// [("J100", Some("Dana Driver")), ("J200", Some("Eli Engine")),
//  ("J300", Some("Dana Driver")), ("J400", None)]
}

One column

A single column is still read as a tuple, of one element:

#![allow(unused)]
fn main() {
let select = Query::<Station>::new().select(Station::code()).into_select();
let rows: Vec<(String,)> = db.rows(&select).await?;
// [("PAR",), ("REN",), …]
let codes: Vec<String> = rows.into_iter().map(|(code,)| code).collect();
}

(Vec<String> does not compile: String is not a row.)

Up to six columns

select takes a tuple of up to six items, and rows reads tuples of up to six. For more, read into a struct of your own that implements FromRow, or split the query.

Naming a value: as_

#![allow(unused)]
fn main() {
Query::<Station>::new().select((Station::code(), (Station::platforms() + 1).as_("more")))
// SELECT "t0"."code", ("t0"."platforms" + $1) AS "more"
}

as_ gives a selected value a name. You rarely need it for rows, which reads by position; the SQL needs it in a union, a CTE or a scalar sub-query that another query reads by name.

Values computed by the database

Anything that is an expression can be selected: arithmetic, SQL functions, aggregates, sub-queries.

#![allow(unused)]
fn main() {
let select = Query::<Train>::new()
    .select((Train::id(), Train::wagons().count()))
    .order_by([Train::id().asc()])
    .into_select();
let rows: Vec<(i64, i64)> = db.rows(&select).await?;
// [(1, 3), (2, 2), (3, 1)]: each train and its number of wagons
}

This is Django’s annotate(n=Count("wagons")).values_list("id", "n"). The next pages show what can be computed.

Reading models with some columns only: all_partial

all_partial reads models, but only the columns you name. The other fields hold their type’s default value:

#![allow(unused)]
fn main() {
let light: Vec<Station> = db
    .all_partial(&Query::<Station>::new().limit(2), &["id", "name"])
    .await?;
// Station { id: 3, name: "Brest", city: "", platforms: 0, … }
}
SELECT "t0"."id", "t0"."name"
FROM "network_station" AS "t0"
LIMIT 2

This is Django’s only("id", "name"), without its trap: Django loads a deferred field silently, with one query per object, when you touch it. rind never does: city is "", and stays so.

That is also the risk: a partial model looks like a whole one. Do not save it (the defaults would overwrite the real values), and do not pass it to code that expects every field. Serializers read partial models, the columns of the fields the client asked for.

Values beside the model’s columns: extra

extra adds a named value to what a query reads, beside the model’s own columns; extra_value refers to it later in the query:

#![allow(unused)]
fn main() {
let scored = Query::<Station>::new()
    .filter(Station::departures().count().ge(1))
    .extra("score", func::int(10));
let score = Query::<Station>::extra_value::<i64>("score");
}

It is mostly for unions, where each branch gives the same name a different value.

Next: Expressions.