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

Trees

Some tables hold a hierarchy: regions inside regions, categories inside categories, the folders of a file system. Each row has a parent, which is a row of the same table. rind calls such a model a tree.

In Django, you would use django-mptt or django-treebeard, which add columns (lft, rght, path, depth) and keep them up to date at every write. rind adds nothing to the table: it walks the parent column with PostgreSQL’s recursive queries (WITH RECURSIVE), when you ask.

Declaring a tree

A tree is a model with a foreign key to itself, and tree = "…" naming that key:

#![allow(unused)]
fn main() {
// sample/crates/network/network-models/src/lib.rs
#[derive(Debug, Clone, Model)]
#[model(table = "network_region", tree = "parent_id")]
#[reverse(name = children, model = Region, fk = "parent_id")]
pub struct Region {
    pub id: i64,
    #[column(max_length = 100)]
    pub name: String,
    /// The region it is part of; none for a country.
    #[fk(Region, on_delete = cascade)]
    pub parent_id: Option<i64>,
    // …
}
}
  • parent_id is an ordinary foreign key, nullable: the roots of the tree (here, the countries) have no parent.
  • tree = "parent_id" gives the model the tree functions below.
  • #[reverse(name = children, ..)] is optional: it gives the relation to the direct children, Region::children(), as for any foreign key.
  • on_delete = cascade deletes a region’s sub-regions with it. Choose restrict if a region with children must not be deleted.

A table can have several roots (France and Italia): it is then a forest, and each walk stays inside its own tree.

The sample’s data

The examples below use these regions:

1 France
├── 2 Bretagne
│   └── 3 Finistère
└── 4 Occitanie
5 Italia

A region and everything below it

The most common question: “the stations of Bretagne, including those of its sub-regions”. subtree(id) is the keys of a region and of every region below it, 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)))
}

It is a sub-query, so it goes anywhere a condition goes. The tree is walked once per request, however deep it is.

Options narrow the walk:

#![allow(unused)]
fn main() {
Region::subtree(1).max_down(1)            // France and its direct children: 1, 2, 4
Region::subtree(1).without_self()         // strictly below France: 2, 3, 4
Region::subtree(vec![1, 5]).at_level(1)   // the level-1 regions of France and Italia: 2, 4
}

A region and everything above it

ancestry(id) goes up instead: a region, its parent, and so on to the root.

#![allow(unused)]
fn main() {
Region::id().in_sub(Region::ancestry(3))           // Finistère, Bretagne, France
Region::id().in_sub(Region::ancestry(3).max_up(1)) // Finistère and Bretagne
}

Starting from a condition

A walk can start from the rows that match a condition rather than from keys:

#![allow(unused)]
fn main() {
// the stations whose region, or one of the regions above it, is called "Bretagne"
Station::region_id().in_sub(Region::subtree_where(Region::name().eq("Bretagne")))
}

“Its region or one above it matches” is the same as “its region is below a region that matches”, and the second is much faster: one walk down from the matching regions, instead of a walk up from every station.

A path, for a breadcrumb

paths reads, for some rows, their ancestors from the root down, with one column of each, in one query:

#![allow(unused)]
fn main() {
let paths = Region::paths(&db, vec![3, 4], Region::name()).await?;
// paths[&3]: [(1, "France"), (2, "Bretagne"), (3, "Finistère")]
// paths[&4]: [(1, "France"), (4, "Occitanie")]
}

It is what a “France › Bretagne › Finistère” field of a serializer needs.

The whole tree, in order

tree(order) gives every row with its depth and its path, to list a tree depth-first, siblings ordered by an expression:

#![allow(unused)]
fn main() {
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])]
}

tree_by_text turns the ordering expression into text first, which a character varying column needs.

Every function

FunctionGives
subtree(start)the keys of the rows and every row below them, for in_sub
subtree_where(cond)the same, starting from the rows that match cond
ancestry(start)the keys of the rows and every row above them
ancestry_where(cond)the same, starting from the rows that match cond
descendants(id), descendants_of(ids), ancestors_of(ids)the same walks as common table expressions (CTEs), to join
tree(order), tree_by_text(order)every row with depth(), path() and an order
paths(&db, ids, column)each row’s ancestors from the root, with a column of each

The options of a walk (max_down, max_up, at_level, down_to_level, up_to_level, without_self, stop_at, with_start) and the CTE functions are explained in Queries: trees.

Mistakes in the data

A row that is, by mistake, its own ancestor (1 → 2 → 1) would make a naive recursive query run forever. rind’s walks stop when they meet a row again. Such a row has no level, so it is left out of the walks that use levels (at_level, down_to_level).

To prevent the mistake, check it in the input that changes a parent: the new parent must not be in the row’s own subtree.

Next: Indexes and constraints.