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

Expressions

An expression is a value the database computes: from the columns of the row, from constants, from SQL functions. It is what Django’s F(), Value(), Func() and Coalesce() are for. An expression is used like a path: it compares in a condition, orders, is selected, and is written by an update.

Arithmetic

+, -, * and / work on number paths and expressions, with a value, a column or another expression on the right. A - before a path negates it.

#![allow(unused)]
fn main() {
let select = Query::<Station>::new()
    .select((
        Station::code(),
        Station::platforms() + 1,
        Station::platforms() * 2,
        Station::platforms() / 3,
        -Station::id(),
    ))
    .order_by([Station::id().asc()])
    .limit(3)
    .into_select();
let rows: Vec<(String, i32, i32, i32, i64)> = db.rows(&select).await?;
}
SELECT "t0"."code", ("t0"."platforms" + $1), ("t0"."platforms" * $2), ("t0"."platforms" / $3), -("t0"."id")
FROM "network_station" AS "t0"
ORDER BY "t0"."id"
LIMIT 3
-- params: [Int(1), Int(2), Int(3)]
[("PAR", 29, 56, 9, -1), ("REN", 11, 20, 3, -2), ("BRE", 7, 12, 2, -3)]

A few things to know:

  • Each operation is in parentheses in the SQL, so the order of the operations is the order of your Rust code.
  • Integer division truncates, as in SQL: 28 / 3 is 9. For a fraction, compute on a float column, or cast with a template.
  • The SQL type follows PostgreSQL’s rules, not the path’s: platforms is an integer, so platforms + 1 is an integer, read as an i32 (see Reading the values).

An expression compares like a path:

#![allow(unused)]
fn main() {
Query::<Station>::new().filter((Station::platforms() * 2).gt(30))
// WHERE ("t0"."platforms" * $1) > $2             → 1, 6
}

and two columns of the row combine:

#![allow(unused)]
fn main() {
Query::<Journey>::new().filter(Journey::arrives_at().gt(Journey::departs_at()))
}

The most common use is an update that computes the new value from the old one, so that two updates at the same time are both counted (Writing rows):

#![allow(unused)]
fn main() {
Update::<Station>::new().set(Station::platforms(), Station::platforms() + 1)
}

A path as an expression: .expr()

Some functions take an expression, not a path (a scalar sub-query, a template). .expr() turns a path into one:

#![allow(unused)]
fn main() {
Stop::station_id().expr()
Region::name().expr()
}

SQL functions: rind::query::func

#![allow(unused)]
fn main() {
use rind::query::func;
}
FunctionSQLDjango
func::coalesce(a, b)COALESCE(a, b)Coalesce
func::now()NOW(), the time of the transactionNow()
func::int(5)CAST($1 AS bigint)Value(5)
func::text("a")CAST($1 AS text)Value("a")
func::call::<T, _>("name", arg)name(arg): any one-argument functionFunc(arg, function="name")
func::count(), sum, avg, min, max, std_devaggregates of a queryCount, Sum… (Aggregates)

On a text path, .upper() and .unaccent() are expressions too (Lookups); on a JSON path, .json_text(key); on a text array, .as_text().

coalesce: a value instead of NULL

#![allow(unused)]
fn main() {
let select = Query::<Station>::new()
    .select((Station::code(), func::coalesce(Station::opened(), NaiveDate::from_ymd_opt(2000, 1, 1).unwrap())))
    .order_by([Station::id().asc()])
    .into_select();
let rows: Vec<(String, NaiveDate)> = db.rows(&select).await?;
}
SELECT "t0"."code", COALESCE("t0"."opened", $1)
-- params: [Date(2000-01-01)]
[("PAR", 1840-09-10), ("REN", 1857-04-26), ("BRE", 2000-01-01),
 ("QUI", 2000-01-01), ("TLS", 2000-01-01), ("MIL", 1931-07-01)]

The result is no longer nullable, so it is read without Option.

now: the current time

#![allow(unused)]
fn main() {
Query::<Journey>::new().filter(Journey::departs_at().gt(func::now()))
// WHERE "t0"."departs_at" > NOW()
}

NOW() is the time the transaction began: every statement of a transaction sees the same now. It is generic over the time type it is compared with (DateTime<Utc> here).

Constants: int and text

#![allow(unused)]
fn main() {
Query::<Station>::new().select((func::int(5), func::text("a"), func::now::<DateTime<Utc>>()))
// SELECT CAST($1 AS bigint), CAST($2 AS text), NOW()
}

A constant with its SQL type, for where a value must be an expression: a selected value, a union’s extra value, one side of coalesce.

Any function of one argument: call

#![allow(unused)]
fn main() {
let select = Query::<Station>::new()
    .select((Station::code(), func::call::<i32, String>("length", Station::name())))
    .order_by([Station::id().asc()])
    .limit(2)
    .into_select();
let rows: Vec<(String, i32)> = db.rows(&select).await?;
// SELECT "t0"."code", length("t0"."name")       → [("PAR", 18), ("REN", 6)]
}

call::<T, A>(name, argument): A is the argument’s type, T the type the function answers. T must be the real SQL type: length answers an integer, so T is i32; with i64, reading the row fails.

SQL templates: wrap

For anything else, wrap::<U>(template) puts an expression inside an SQL template, {} standing for it, and gives an expression of type U:

#![allow(unused)]
fn main() {
let select = Query::<Station>::new()
    .select((
        Station::code(),
        Station::platforms().expr().wrap::<String>("CAST({} AS text) || ' platforms'"),
    ))
    .order_by([Station::id().asc()])
    .limit(2)
    .into_select();
let rows: Vec<(String, String)> = db.rows(&select).await?;
// [("PAR", "28 platforms"), ("REN", "10 platforms")]
}

Common uses:

NeedTemplate
a cast"CAST({} AS numeric)"
a part of a date"EXTRACT(YEAR FROM {})::bigint" (into an i64)
a day from a moment"({} AT TIME ZONE 'Europe/Paris')::date"
a regular expression"({} ~ '^[A-Z]{3}$')" (a bool)
a JSON value deeper than one key"({} #>> '{dimensions,width}')"
a function of two arguments"round({}, 2)"

Rules:

  • The template is SQL that you write, part of your program. Never put in it a value that comes from a request: values go as parameters, in the comparison that follows (.eq(value)).
  • rind copies the template as it is, without parentheses around it. Put them in the template when an operator follows.
  • U is the type you read, and must match what the SQL answers.

A template takes one expression. For a function of two columns, write the SQL with raw SQL, or ask for the function to be added.

Not available

These Django expressions have no equivalent yet: Case/When (conditional values), window functions (Window, RowNumber, Rank), Concat of several columns, ExpressionWrapper with an output field (use wrap with the type). For them, write the query in raw SQL.

Next: Aggregates.