Following relations

Filters rarely stay on one table. "The journeys that leave from Paris", "the stations managed by sam", "the journeys that stop at Rennes": each follows a relation. This page shows how, in two parts:

  • relations to one row (a foreign key): they are joined;
  • relations to many rows (the other side of a key, a many-to-many relation): they are EXISTS sub-queries.

The difference is the most important thing to understand about rind's queries, so the page takes its time.

Relations to one row: a foreign key

A relation is a path, and the columns of the related row are reached through it:

#![allow(unused)]
fn main() {
Query::<Journey>::new().filter(Journey::origin().city().eq("Paris"))
}
SELECT "t0"."id", "t0"."code", …
FROM "timetable_journey" AS "t0"
INNER JOIN "network_station" AS "origin" ON "origin"."id" = "t0"."origin_id"
WHERE "origin"."city" = $1
-- params: [Text("Paris")]

Journeys 1 and 4. This is Django's filter(origin__city="Paris"). rind writes the join the path needs: you never write a join along a relation, and there is no select_related to add for a filter.

Paths go as far as the relations do:

#![allow(unused)]
fn main() {
Journey::destination().region().name()      // two relations
Journey::train().depot().code()             // a journey's train's depot
}

and several paths share their joins. This query filters on the origin twice and on the destination's region:

#![allow(unused)]
fn main() {
Query::<Journey>::new()
    .filter(Journey::origin().city().eq("Paris"))
    .filter(Journey::origin().code().eq("PAR"))
    .filter(Journey::destination().region().name().eq("Finistère"))
}
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"
WHERE "origin"."city" = $1 AND "origin"."code" = $2 AND "destination__region"."name" = $3

The stations are joined once as origin, once as destination, and the region once, named after the path that leads to it (destination__region, as Django would spell the lookup).

Which join

rind chooses between an INNER JOIN and a LEFT JOIN so that no row is lost by mistake:

  • INNER JOIN when it is safe: the foreign key cannot be NULL, or a condition in the main AND of the query needs the related row anyway.
  • LEFT JOIN otherwise: under an OR or a NOT, a nullable key keeps the rows that have no related row.

A journey's driver is a nullable key (journey 4 has none). In the main AND, an inner join is right, since a journey without a driver cannot match anyway:

#![allow(unused)]
fn main() {
Query::<Journey>::new().filter(Journey::driver().name().eq("Dana Driver"))
}
INNER JOIN "fleet_driver" AS "driver" ON "driver"."id" = "t0"."driver_id"
WHERE "driver"."name" = $1                                    → journeys 1, 3

Under an OR, an inner join would lose journey 4, which matches the other side of the OR:

#![allow(unused)]
fn main() {
Query::<Journey>::new()
    .filter(Journey::driver().name().eq("Dana Driver") | Journey::status().eq("cancelled"))
}
LEFT JOIN "fleet_driver" AS "driver" ON "driver"."id" = "t0"."driver_id"
WHERE "driver"."name" = $1 OR "t0"."status" = $2               → journeys 1, 3, 4

You do not choose; you only need to know that the result is the one you would expect from the condition.

Relations declared in another crate

A relation that another crate declares (reverse = … on its foreign key, or #[reverse(.., forward = …)]) comes as a trait of that crate. Import it, and the relation is followed like any other:

#![allow(unused)]
fn main() {
// sample/tests/db.rs
use accounts_models::{StationManager as _, StationPathManager as _};

Query::<Station>::new().filter(Station::manager().username().eq("sam"))   // → 1, 2
Journey::origin().manager().username().eq("sam")                          // through a path: the Path trait
}

StationManager gives Station::manager(); StationPathManager gives .manager() on a path that ends at a station (Journey::origin()). The compiler names the trait to import when you forget it (Reverse relations).

Relations to many rows: EXISTS

A journey has several stops, a station several departures, a user several groups. Such a relation is never joined in a filter. A filter through it is an EXISTS sub-query:

#![allow(unused)]
fn main() {
// sample/crates/timetable/timetable-api/src/journeys/filters.rs
// The journeys with a stop at Rennes (station 2).
Query::<Journey>::new().filter(Journey::stops().any(|stop| stop.station_id().eq(2)))
}
WHERE EXISTS (SELECT 1 FROM "timetable_stop" AS "t1"
              WHERE "t1"."journey_id" = "t0"."id" AND "t1"."station_id" = $1)
-- params: [Int(2)]

Journeys 1 and 3. any takes a closure, which receives a path to the related row (here a stop) and returns a condition on it.

Why not a join

In Django, Journey.objects.filter(stops__station=2) is a join. A journey with two stops at Rennes comes back twice, and you add .distinct(). Worse, a second filter on the same relation may join it a second time, and counts and sums over the result are multiplied.

An EXISTS asks "is there at least one such stop?". A journey is listed once, however many of its stops match. There is no .distinct() to add, and none to forget.

Coming from Django: a rind query on a model always gives each of its rows at most once. Only a union or a grouped query can change that, and you write them on purpose.

Conditions that must hold on the same related row go in one any:

#![allow(unused)]
fn main() {
// A stop that is at Rennes AND is the first one.
Journey::stops().any(|s| s.station_id().eq(2) & s.rank().eq(1))
}
WHERE EXISTS (SELECT 1 FROM "timetable_stop" AS "t1"
              WHERE "t1"."journey_id" = "t0"."id" AND ("t1"."station_id" = $1 AND "t1"."rank" = $2))

A path through a many relation can also be written directly in a condition, without any. Each such condition is then its own EXISTS, on a related row of its own:

#![allow(unused)]
fn main() {
// A stop at Rennes, and a first stop: maybe not the same one.
Query::<Journey>::new()
    .filter(Journey::stops().station_id().eq(2))
    .filter(Journey::stops().rank().eq(1))
}
WHERE EXISTS (SELECT 1 FROM "timetable_stop" AS "t1" WHERE "t1"."journey_id" = "t0"."id" AND "t1"."station_id" = $1)
  AND EXISTS (SELECT 1 FROM "timetable_stop" AS "t1" WHERE "t1"."journey_id" = "t0"."id" AND "t1"."rank" = $2)

This is what Django does with two chained filter() calls on a multi-valued relation. With the sample's data the two queries give the same journeys (1 and 3), because each has one stop; with more stops they would differ.

You meanWrite
one related row matches all the conditionsrel().any(|r| a & b)
each condition is matched by some related rowrel().a()… and rel().b()… in separate conditions

!any(..) is "there is no such related row". The journeys that stop nowhere:

#![allow(unused)]
fn main() {
Query::<Journey>::new().filter(!Journey::stops().any(|_| Cond::Const(true)))
// WHERE NOT EXISTS (SELECT 1 FROM "timetable_stop" AS "t1" WHERE "t1"."journey_id" = "t0"."id" AND TRUE)
// → journey 4
}

(Journey::stops().count().eq(0) says the same with a count: Aggregates.)

is_null through a many relation is ambiguous: does Journey::stops().arrives_at().is_null() mean "a stop without an arrival time" or "no stop"? rind refuses it, with a message that says what to write:

IS NULL through the multi-valued relation `stops` is ambiguous; write `any(..)` or `!any(..)`

Inside any, the related row's own relations can be followed: joined when they lead to one row, nested EXISTS when they lead to many.

#![allow(unused)]
fn main() {
// Journeys with a stop in a station of the city of Rennes.
Journey::stops().any(|s| s.station().city().eq("Rennes"))
}
WHERE EXISTS (SELECT 1 FROM "timetable_stop" AS "t1"
              INNER JOIN "network_station" AS "t1__station" ON "t1__station"."id" = "t1"."station_id"
              WHERE "t1"."journey_id" = "t0"."id" AND "t1__station"."city" = $1)
#![allow(unused)]
fn main() {
// Stations from which a journey leaves that stops at Rennes.
Station::departures().any(|j| j.stops().any(|s| s.station_id().eq(2)))
}
WHERE EXISTS (SELECT 1 FROM "timetable_journey" AS "t1" WHERE "t1"."origin_id" = "t0"."id"
              AND EXISTS (SELECT 1 FROM "timetable_stop" AS "t2"
                          WHERE "t2"."journey_id" = "t1"."id" AND "t2"."station_id" = $1))
-- → stations 1 and 3

Many-to-many relations

A many-to-many relation is a many relation like the others. The link table is joined inside the EXISTS:

#![allow(unused)]
fn main() {
Query::<User>::new().filter(User::groups().any(|g| g.slug().eq("drivers")))
}
WHERE EXISTS (SELECT 1 FROM "accounts_group" AS "t1"
              INNER JOIN "accounts_user_groups" AS "groups_through" ON "groups_through"."group_id" = "t1"."id"
              WHERE "groups_through"."user_id" = "t0"."id" AND "t1"."slug" = $1)
-- → user 4, bob

Excluding rows: exclude and !

exclude(cond) and filter(!cond) look the same. They differ, on purpose, where a value is unknown (NULL, or no related row):

#![allow(unused)]
fn main() {
// sample/tests/db.rs
let sams = || Station::manager().username().eq("sam");

Query::<Station>::new().exclude(sams())   // → 3, 4, 5, 6
Query::<Station>::new().filter(!sams())   // → no station
}
-- exclude
LEFT JOIN "accounts_user" AS "manager" ON "manager"."id" = "t0"."manager_id"
WHERE ("manager"."username" = $1) IS NOT TRUE

-- filter(!…)
LEFT JOIN "accounts_user" AS "manager" ON "manager"."id" = "t0"."manager_id"
WHERE NOT ("manager"."username" = $1)

Stations 1 and 2 are managed by sam; 3 to 6 have no manager at all.

  • exclude is Django's: it keeps the rows where the condition is false or unknown. A station without a manager is "not managed by sam", so it stays. It is written (…) IS NOT TRUE.
  • filter(!cond) is SQL's NOT: for a station without a manager, username = 'sam' is unknown, and so is its negation, so the row goes.

Use exclude when you think "everything but…", which is nearly always.

exclude can be called several times; each call adds its condition:

#![allow(unused)]
fn main() {
Query::<Station>::new()
    .exclude(Station::opened().is_null())
    .exclude(Station::platforms().lt(10))
// WHERE NOT ("t0"."opened" IS NULL) AND ("t0"."platforms" < $1) IS NOT TRUE   → 1, 2, 6
}

Through a many relation, exclude becomes NOT EXISTS:

#![allow(unused)]
fn main() {
Query::<Journey>::new().exclude(Journey::stops().station_id().eq(2))
// WHERE NOT EXISTS (SELECT 1 FROM "timetable_stop" AS "t1"
//                   WHERE "t1"."journey_id" = "t0"."id" AND "t1"."station_id" = $1)
// → journeys 2 and 4: those that do not stop at Rennes
}

Summary

RelationIn a filterExample
foreign key (to one row)a join, INNER or LEFTJourney::origin().city().eq("Paris")
reverse of a key, many-to-many (to many rows)an EXISTSJourney::stops().any(|s| …)
no related rowa NOT EXISTS!Journey::stops().any(…), exclude(…)
a relation of another crateimport its traituse accounts_models::StationManager as _;

To count or sum the related rows, see Aggregates. To read them, see Loading related rows.

Next: Ordering and pages.