Trees
A tree model has rows whose parent is a row of the
same table: #[model(tree = "parent_id")]. Questions about a tree
(“Bretagne and everything inside it”, “the regions above Finistère”,
“France › Bretagne › Finistère”) need to walk the parent column as many
times as the tree is deep. SQL does that with recursive queries (WITH RECURSIVE). The model derive writes them for you, as functions of the
model.
In Django, you would add django-mptt or django-treebeard, which store
extra columns (lft, rght, path, depth) and keep them up to date
at every write. rind stores nothing more than the parent; each walk reads
the tree when it is asked.
The sample’s tree
level 0 level 1 level 2
1 France
2 Bretagne
3 Finistère
4 Occitanie
5 Italia
Two roots, France and Italia: a forest. Every walk stays inside the tree it starts in. The stations: Paris (1) is in France, Rennes (2) in Bretagne, Brest (3) and Quimper (4) in Finistère, Toulouse (5) in Occitanie, Milano (6) in Italia.
Walking down: subtree
Region::subtree(start) is the keys of the starting rows and of every
row below them, ready for in_sub:
#![allow(unused)]
fn main() {
// The stations of Bretagne, or of any region inside it.
Query::<Station>::new().filter(Station::region_id().in_sub(Region::subtree(2)))
// → stations 2, 3, 4
}
WHERE "t0"."region_id" IN (
WITH RECURSIVE "network_region_walk"("start", "id", "depth", "level", "seen") AS (
SELECT "t0"."id", "t0"."id", CAST(0 AS bigint), CAST(NULL AS bigint), ARRAY["t0"."id"]
FROM "network_region" AS "t0" WHERE "t0"."id" IN ($1)
UNION ALL
SELECT "network_region_walk"."start", "t0"."id", ("network_region_walk"."depth" + 1),
("network_region_walk"."level" + 1), ("network_region_walk"."seen" || "t0"."id")
FROM "network_region" AS "t0"
INNER JOIN "network_region_walk" ON "t0"."parent_id" = "network_region_walk"."id"
WHERE ("t0"."id" <> ALL("network_region_walk"."seen")))
SELECT "network_region_walk"."id" FROM "network_region_walk")
-- params: [Int(2)]
You do not write any of this. Three things are worth knowing about it:
- The walk is inside the sub-query. So it can go anywhere a
condition goes, in an
EXISTSor anINinside another query, and the tree is walked once for the query, however deep. - It keeps the
seenkeys of each branch, and does not enter a row twice: a row that is, by mistake, its own ancestor does not make the query run forever. - It counts the depth from the start, and can know the level from the root: the options below use them.
subtree takes one key (2), several (vec![1, 5]), another walk, or a
sub-query of keys.
Options
Each option narrows the walk. The keys each gives, on the sample’s tree:
| Walk | Keys | Meaning |
|---|---|---|
Region::subtree(1) | 1, 2, 3, 4 | France and everything below |
Region::subtree(1).without_self() | 2, 3, 4 | strictly below France |
Region::subtree(2).include_self(false) | 3 | the same, written with a boolean |
Region::subtree(1).max_down(1) | 1, 2, 4 | France and at most one level below |
Region::subtree(vec![1, 5]).down_to_level(1) | 1, 2, 4, 5 | no deeper than level 1 |
Region::subtree(vec![1, 5]).at_level(1) | 2, 4 | only the rows at level 1 |
Region::subtree(vec![1, 5]).at_level(2) | 3 | only the rows at level 2 |
Region::subtree(1).stop_at(Region::name().eq("Bretagne")) | 1, 4 | do not enter a row that matches |
max_down(n)counts from the starting rows:nlevels below them.down_to_level(n)andat_level(n)count from the root of each row’s tree, the roots being at level 0. To know the level, the walk first goes up from its starting rows; a row with no root above it (in a cycle) has no level, and is left out.stop_at(cond)does not enter a row that matchescond, nor what is below it.- The bounds are included:
max_down(1)keeps level 1.
Walking up: ancestry
Region::ancestry(start) is the keys of the starting rows and of every
row above them:
#![allow(unused)]
fn main() {
Region::id().in_sub(Region::ancestry(3)) // Finistère, Bretagne, France
}
| Walk | Keys | Meaning |
|---|---|---|
Region::ancestry(3) | 1, 2, 3 | Finistère and everything above |
Region::ancestry(3).without_self() | 1, 2 | strictly above |
Region::ancestry(3).max_up(1) | 2, 3 | Finistère and its parent |
Region::ancestry(3).up_to_level(1) | 2, 3 | no nearer the root than level 1 |
Region::ancestry(3).at_level(1) | 2 | its ancestor at level 1 |
Walks compose: a walk can start from another one.
#![allow(unused)]
fn main() {
// The level-1 ancestor of Finistère, and everything below it: Bretagne's subtree.
Region::subtree(Region::ancestry(3).at_level(1)) // → 2, 3
}
Starting from a condition: subtree_where, ancestry_where
A walk can start from the rows that match a condition, instead of keys:
#![allow(unused)]
fn main() {
// The stations whose region, or one of the regions above it, is called "Bretagne".
Query::<Station>::new()
.filter(Station::region_id().in_sub(Region::subtree_where(Region::name().eq("Bretagne"))))
// → stations 2, 3, 4
Region::ancestry_where(Region::name().eq("Finistère")) // → 1, 2, 3
}
Notice how the first question is turned around. “The station’s region, or one of its ancestors, is Bretagne” would walk up from every station’s region. “The station’s region is in the subtree of the regions called Bretagne” walks down once, from Bretagne. The rows are the same, and the second is much faster: on some twenty thousand rows of a real application, 10 ms instead of a second. Write it this way whenever the condition is “this or an ancestor matches”.
Pairs of start and row: with_start
with_start() gives (start, key) pairs: for each row reached, the row
its walk started from. It answers a Select, read with db.rows:
#![allow(unused)]
fn main() {
let pairs: Vec<(i64, i64)> = db.rows(&Region::ancestry(vec![3, 4]).with_start()).await?;
// [(3, 3), (4, 4), (4, 1), (3, 2), (3, 1)]: Finistère reaches 3, 2, 1; Occitanie reaches 4, 1
}
It is what you need to give each row a value that one of its ancestors carries. Started from the rows that carry a value, and stopped at them, each row is reached from its nearest carrier:
#![allow(unused)]
fn main() {
// sample/tests/db.rs
// France and Bretagne each carry a value: which one does each region take?
let carriers = || Region::name().in_(["France", "Bretagne"]);
let pairs: Vec<(i64, i64)> = db
.rows(&Region::subtree_where(carriers()).stop_at(carriers()).with_start())
.await?;
// [(1, 1), (2, 2), (2, 3), (1, 4)]: Finistère (3) from Bretagne, Occitanie (4) from France
}
(A walk does not stop at its own starting rows: stop_at applies to the
rows it would enter next.)
A row’s path: paths
Region::paths(&db, ids, column) reads, for each row, its ancestors from
the root down to itself, with one column of each, in one query:
#![allow(unused)]
fn main() {
// sample/tests/db.rs
let paths = Region::paths(&db, vec![3, 4, 5, 99], Region::name()).await?;
// {3: [(1, "France"), (2, "Bretagne"), (3, "Finistère")],
// 4: [(1, "France"), (4, "Occitanie")],
// 5: [(5, "Italia")]}
}
A key that is not in the table (99) is not in the map. This is what a breadcrumb needs, and what a serializer’s computed field calls for a page of rows.
The whole tree, in order: tree
Region::tree(order) is every row of the table with its depth and its
path from the root, to list the tree depth-first:
#![allow(unused)]
fn main() {
// sample/tests/db.rs
let tree = Region::tree_by_text(Region::name().expr());
let select = Query::<Region>::new()
.with_tree(&tree)
.select((Region::id(), tree.depth(), tree.path()))
.order_by([tree.asc()])
.into_select();
let rows: Vec<(i64, i64, Vec<i64>)> = db.rows(&select).await?;
// [(1, 0, [1]), (2, 1, [1, 2]), (3, 2, [1, 2, 3]), (4, 1, [1, 4]), (5, 0, [5])]
}
WITH RECURSIVE "region_tree"("tree_depth", "tree_path", "tree_ordering", "tree_pk") AS (
SELECT CAST(0 AS bigint), ARRAY["t0"."id"], ARRAY[CAST("t0"."name" AS text)], "t0"."id"
FROM "network_region" AS "t0" WHERE "t0"."parent_id" IS NULL
UNION ALL
SELECT ("region_tree"."tree_depth" + 1), ("region_tree"."tree_path" || "t0"."id"),
("region_tree"."tree_ordering" || CAST("t0"."name" AS text)), "t0"."id"
FROM "network_region" AS "t0" INNER JOIN "region_tree" ON "t0"."parent_id" = "region_tree"."tree_pk")
SELECT "t0"."id", "region_tree"."tree_depth", "region_tree"."tree_path"
FROM "network_region" AS "t0"
INNER JOIN "region_tree" ON "t0"."id" = "region_tree"."tree_pk"
ORDER BY "region_tree"."tree_ordering"
with_tree(&tree)adds the walk to the query and joins it.tree.depth()is the row’s depth (0 for a root),tree.path()the keys from the root down to it,tree.key()the row’s own key.tree.asc()orders depth-first, each row followed by what is below it, siblings in the order of the expression given (here, their names);tree.desc()is the reverse.tree(order)orders the siblings by any expression;tree_by_text(order)casts it totextfirst, which acharacter varyingcolumn needs (the walk’s arrays must have one type).
The tree’s columns filter like any other:
#![allow(unused)]
fn main() {
let tree = Region::tree(Region::id().expr());
Query::<Region>::new()
.with_tree(&tree)
.filter(tree.depth().ge(1))
.select((Region::name(), tree.depth(), tree.key()))
.order_by([tree.asc()])
// → [("Bretagne", 1, 2), ("Finistère", 2, 3), ("Occitanie", 1, 4)]
}
The tree starts from the roots (rows whose parent is NULL). Rows caught
in a cycle have no root, and are not in it.
Walks as CTEs: descendants, descendants_of, ancestors_of
The walks above are sub-queries. The same walks also exist as CTEs, named queries you join to (CTEs):
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/filters.rs
let below = Region::descendants(2);
Query::<Station>::new()
.with(&below)
.join_cte(&below.r(), Station::region_id().eq(below.col::<i64>("id")))
// → stations 2, 3, 4
}
| Function | CTE columns | Rows |
|---|---|---|
descendants(id) | start, id | the row and every row below it |
descendants_of(ids) | start, id | the same, for several starting rows |
ancestors_of(ids) | start, id, parent_id, height | the rows and every row above them |
The start column says which starting row each row was reached from.
That is what makes “for several regions at once” possible, here the
number of stations in each region and below it:
#![allow(unused)]
fn main() {
// sample/tests/db.rs
let down = Region::descendants_of(vec![1, 2, 5]);
let select = Query::<Region>::new()
.with(&down)
.filter(Region::id().in_([1, 2, 5]))
.select((
Region::id(),
Query::<Station>::new()
.join_cte(&down.r(), Station::region_id().eq(down.col::<i64>("id")))
.filter(down.col::<i64>("start").eq(Region::id().outer()))
.scalar_count(),
))
.order_by([Region::id().asc()])
.into_select();
let rows: Vec<(i64, i64)> = db.rows(&select).await?;
// [(1, 5), (2, 3), (5, 1)]: France has 5 stations below it, Bretagne 3, Italia 1
}
Prefer subtree and ancestry in conditions: they are shorter and go
anywhere. Use the CTEs to join the walk and read its columns.
Summary
| Function | Gives | Use for |
|---|---|---|
subtree(start) | keys: the rows and below | in_sub in a condition |
subtree_where(cond) | keys: the matching rows and below | “this or an ancestor matches” |
ancestry(start) | keys: the rows and above | in_sub in a condition |
ancestry_where(cond) | keys: the matching rows and above | “this or a descendant matches” |
….with_start() | (start, key) pairs | values carried by ancestors |
paths(&db, ids, column) | each row’s ancestors, with a column | breadcrumbs |
tree(order), tree_by_text(order) | every row with depth and path | listing a tree |
descendants(id), descendants_of(ids), ancestors_of(ids) | CTEs | joining the walk |
Options of subtree: without_self, include_self(bool), max_down(n),
down_to_level(n), at_level(n), stop_at(cond), with_start.
Options of ancestry: without_self, include_self(bool), max_up(n),
up_to_level(n), at_level(n), with_start.
Next: CTEs and unions.