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

Running a query

A Db runs queries. It is a pool of connections to PostgreSQL, or one transaction (Transactions). In a request, it is ctx.db; in a command, a job or a test, you are given one.

Every method of Db is async, and answers a Result: the error is a rind::db::Error, which ? turns into an ApiError inside a resource.

Reading models: all

#![allow(unused)]
fn main() {
let stations: Vec<Station> = db.all(&Query::<Station>::new()).await?;
}

all reads every row of the query as models. This is iterating a Django queryset, list(Station.objects.all()). An empty result is an empty Vec, not an error.

One row: first

#![allow(unused)]
fn main() {
let paris: Option<Station> = db
    .first(&Query::<Station>::new().filter(Station::code().eq("PAR")))
    .await?;
}

first adds LIMIT 1 to the query and answers the row, if there is one.

It adds nothing else:

SELECT "t0"."id", … FROM "network_station" AS "t0" LIMIT 1

Unlike Django’s first(), it does not order by the primary key when the query has no order. Without an order, PostgreSQL answers any row. Give the query an order_by when “first” must mean something.

There is no get()

Django’s get() raises DoesNotExist when there is no row and MultipleObjectsReturned when there are several. rind has no such method: write what you mean.

#![allow(unused)]
fn main() {
// The station with this code, or a 404 in a resource:
let station = db.first(&q).await?.ok_or(ApiError::NotFound)?;

// The station with this code, or an error of your own:
let station = db.first(&q).await?.ok_or_else(|| MyError::NoStation(code.clone()))?;
}

When the filter is on a unique column (a key, a code), there cannot be several rows, and first is exactly get.

Counting: count

#![allow(unused)]
fn main() {
let open: i64 = db.count(&Query::<Station>::new().filter(Station::status().eq("open"))).await?;
// 5
}

count sends SELECT COUNT(*) with the query’s filters. It leaves out the query’s order and its page (limit, offset), so it counts every row the filters keep:

#![allow(unused)]
fn main() {
let q = Query::<Station>::new()
    .filter(Station::status().eq("open"))
    .order_by([Station::name().asc()])
    .limit(2);
db.count(&q).await?;   // 5, not 2
}
SELECT COUNT(*)
FROM "network_station" AS "t0"
WHERE "t0"."status" = $1

This is what a paginated list needs: the total, beside one page. For a grouped query, count answers the number of groups.

Rows of your own shape: rows

A query that chooses its columns with select is read with rows, as tuples:

#![allow(unused)]
fn main() {
let select = Query::<Journey>::new()
    .select((Journey::code(), Journey::origin().city()))
    .order_by([Journey::id().asc()])
    .into_select();
let rows: Vec<(String, String)> = db.rows(&select).await?;
// [("J100", "Paris"), ("J200", "Rennes"), ("J300", "Brest"), ("J400", "Paris")]
}

Choosing the columns explains select and into_select, and how each SQL type is read.

Models with some columns only: all_partial

#![allow(unused)]
fn main() {
let light: Vec<Station> = db
    .all_partial(&Query::<Station>::new().limit(2), &["id", "name"])
    .await?;
}

reads only id and name; the other fields hold their type’s default ("", 0, None). See Choosing the columns.

What can go wrong

ErrorWhen
Error::Database(…)PostgreSQL refused the statement (a constraint, a missing extension, a type it cannot compare), or a column could not be read as its Rust type
Error::Query(…)rind refused to build the SQL, before sending anything: an update without a filter, is_null through a many relation. The message says what to write instead
Error::NotFound(…)an object write (save, refresh) found no row
Error::Referenced { .. }a deletion that follows keys was refused by a restrict relation
Error::ReadOnly(…), Error::WrongDatabase { .. }a write sent to a replica; a model sent to another database than its own (Databases)
Error::Pool(…), Error::Config(…)no connection could be had; a transaction begun inside another

In a resource, ? turns them into an ApiError: NotFound is a 404, Referenced a 400 that names what points to the row, an invalid regular expression sent by a client a 400, and anything else a 500, whose details go to the log, not to the client. The writes a resource does itself (create, update, delete) turn a refused constraint into a 400.

In a request

Inside a resource’s code (a filter method, a hook, an action), the database is ctx.db:

#![allow(unused)]
fn main() {
#[action(GET)]
pub async fn count(ctx: &Ctx) -> Result<i64, ApiError> {
    Ok(ctx.db.count(&Query::<Station>::new()).await?)
}
}

During a write, ctx.db is the write’s transaction: what you read sees what the write has done so far, and what you write is kept or dropped with it. With replicas, a GET may read from a replica; rind chooses.

Next: Conditions.