laravel-nestedset 0.1.0

Nested set trees for Laravel Rust models: fast subtree and ancestor queries, safe under concurrent writes.
Documentation

laravel-nestedset

Crates.io Docs.rs CI License: MIT

Nested set trees for Laravel Rust models: product categories, site menus, comment threads, org charts. A whole subtree or every ancestor of a node is one indexed query, a subtree moves with a fixed number of UPDATEs, and every write locks its tree, so concurrent writers can't corrupt it.

Installation

[dependencies]
laravel-nestedset = "0.1"

The package uses the database driver your application enables on laravel-rust: SQLite, PostgreSQL, MySQL, or MariaDB. It needs Rust 1.99 or later, like Laravel Rust itself.

Quick start: shop categories

Add the columns in a migration. nested_set() adds lft, rgt, a nullable parent_id, and the indexes the queries use:

use laravel_nestedset::NestedSetBlueprint;

tx.schema()
    .create("categories", |table| {
        table.id();
        table.string("name");
        table.nested_set();
        table.timestamps();
    })
    .await?;

Implement NestedSet for the model, naming its three columns:

use laravel::model::{Column, model};
use laravel::time::Timestamp;
use laravel_nestedset::NestedSet;

#[model]
pub struct Category {
    pub id: i64,
    pub name: String,
    #[default]
    pub lft: i64,
    #[default]
    pub rgt: i64,
    pub parent_id: Option<i64>,
    pub created_at: Timestamp,
    pub updated_at: Timestamp,
}

impl NestedSet for Category {
    fn lft_column() -> Column<Self, i64> {
        Category::lft
    }

    fn rgt_column() -> Column<Self, i64> {
        Category::rgt
    }

    fn parent_column() -> Column<Self, Option<i64>> {
        Category::parent_id
    }
}

That's all the setup. The examples below use this tree:

Shop
├── Phones
│   ├── Android
│   └── iPhone
├── Laptops
└── Tablets
Blog

Creating nodes

let mut shop = Category::create_root(Category::create().name("Shop")).await?;
let mut phones = shop.create_child(Category::create().name("Phones")).await?;
phones.create_child(Category::create().name("Android")).await?;
phones.create_child(Category::create().name("iPhone")).await?;
let mut laptops = shop.create_child(Category::create().name("Laptops")).await?;
laptops.create_after(Category::create().name("Tablets")).await?;
Category::create_root(Category::create().name("Blog")).await?;
Method The new node goes
Category::create_root(create) after the last root of its tree
node.create_child(create) last among node's children
node.create_first_child(create) first among node's children
node.create_before(create) right before node, under the same parent
node.create_after(create) right after node, under the same parent

Each takes the model's own create builder, so required columns, hooks, and events work as usual. The method reloads node afterwards, so its bounds stay current. Other models you hold, such as node's ancestors, keep their old bounds: load them again before you compare them.

To create a whole tree at once, nest NewNodes:

use laravel_nestedset::NewNode;

let shop = Category::create_tree(
    NewNode::new(Category::create().name("Shop")).children([
        NewNode::new(Category::create().name("Phones")).children([
            NewNode::new(Category::create().name("Android")),
            NewNode::new(Category::create().name("iPhone")),
        ]),
        NewNode::new(Category::create().name("Laptops")),
    ]),
)
.await?;

// Or below an existing node:
shop.create_child_tree(NewNode::new(Category::create().name("Audio"))).await?;

Moving nodes

A node moves with its whole subtree. However big the subtree, the move is two UPDATEs: one for the bounds and one for the parent.

phones.append_to(&laptops).await?;     // last child of Laptops
phones.prepend_to(&laptops).await?;    // first child of Laptops
phones.insert_before(&tablets).await?; // right before Tablets, under Tablets' parent
phones.insert_after(&tablets).await?;  // right after Tablets
phones.make_root().await?;             // a root, after the last one

tablets.up(1).await?;   // one place up among its siblings: true if it moved
tablets.down(2).await?; // two places down

The moved node is reloaded. A move fails, and changes nothing, when it would put a node inside its own subtree (NestedSetError::MoveIntoOwnSubtree) or into another tree of a scoped table (NestedSetError::ScopeMismatch).

Deleting nodes

let deleted = phones.delete_subtree().await?; // Phones, Android, iPhone: 3

delete_subtree removes the node and its whole subtree and closes the gap in the bounds.

[!IMPORTANT] Don't delete nodes with the model's delete or a delete query. That leaves a gap in the bounds and orphans the children. If it has happened, fix_tree repairs the table.

The rows go with one query, so model hooks and events don't run for them. Laravel Rust models have no soft deletes, so neither does this package.

Querying

Every query is a Laravel Rust model Builder, so you can filter, paginate, or count it further:

shop.descendants().get().await?;          // Phones, Android, iPhone, Laptops, Tablets
phones.descendants_and_self().get().await?;
android.ancestors().get().await?;         // Shop, Phones: breadcrumbs
android.ancestors_and_self().get().await?;
shop.children().get().await?;             // Phones, Laptops, Tablets
laptops.siblings().get().await?;          // Phones, Tablets
phones.next_siblings().get().await?;      // Laptops, Tablets
tablets.prev_siblings().get().await?;     // Phones, Laptops
laptops.next_sibling().await?;            // Some(Tablets)
laptops.prev_sibling().await?;            // Some(Phones)
android.parent().await?;                  // Some(Phones)
android.depth().await?;                   // 2
Category::roots().get().await?;           // Shop, Blog
Category::leaves().get().await?;          // Android, iPhone, Laptops, Tablets, Blog

let phones_in_stock = shop
    .descendants()
    .filter(Category::name.ne("Tablets"))
    .count()
    .await?;

Queries of a node stay inside its tree, and the ones that list nodes come in tree order. Order your own queries the same way with the default_order scope, or reverse it with reversed:

let all = Category::query().scope(Category::default_order).get().await?;

Checks read the bounds the models already hold, without a query:

android.is_leaf();               // true
shop.is_root();                  // true
android.is_descendant_of(&shop); // true
shop.is_ancestor_of(&android);   // true
android.is_child_of(&phones);    // true
android.is_sibling_of(&iphone);  // true
shop.descendant_count();         // 5

To get the goods of a category and of every category below it, take the subtree's keys:

let mut ids = phones.descendants().pluck(Category::id).await?;
ids.push(phones.id);
let goods = Product::query().filter(Product::category_id.is_in(ids)).get().await?;

Building a tree for JSON and templates

into_tree nests a list of nodes, such as a query's result, under their parents:

use laravel_nestedset::IntoTree;

let tree = Category::query()
    .scope(Category::default_order)
    .get()
    .await?
    .into_tree();

Each TreeNode holds the node, its depth in the built tree, and its children. It serializes as the model's own fields plus depth and children, so you can return it from a JSON endpoint or hand it to a template:

[
  {
    "id": 1, "name": "Shop", "lft": 1, "rgt": 12, "parent_id": null, "depth": 0,
    "children": [
      { "id": 2, "name": "Phones", "depth": 1, "children": ["..."] }
    ]
  }
]

Nodes whose parent isn't in the list are at the top, so a subtree works too: phones.descendants().get().await?.into_tree() gives Android and iPhone at the top. Siblings keep the order of the list.

into_flat_tree keeps one flat list, each node right before its children. That's what a <select> of categories, indented by depth, needs:

let options = Category::query().scope(Category::default_order).get().await?.into_flat_tree();

Several trees in one table: site menus

A scope splits a table into independent trees, such as menu items by menu_id. Each tree is numbered on its own, a node's queries stay inside its tree, and writes lock only that tree:

tx.schema()
    .create("menu_items", |table| {
        table.id();
        table.foreign_id("menu_id");
        table.string("title");
        table.nested_set_scoped(&["menu_id"]);
    })
    .await?;
use laravel_nestedset::{NestedSet, Scope};

impl NestedSet for MenuItem {
    // lft_column, rgt_column, and parent_column, as above.

    fn scope(&self) -> Scope<Self> {
        Scope::new().by(MenuItem::menu_id, &self.menu_id)
    }
}

let mut header = MenuItem::create_root(MenuItem::create().menu_id(1).title("Header")).await?;
header.create_child(MenuItem::create().menu_id(1).title("Blog")).await?;

A new child gets its parent's scope values, and a node can't move into another tree. Table-wide queries, such as MenuItem::roots() or MenuItem::query(), see every tree: filter them by the scope columns yourself.

Checking and fixing a tree

check_tree checks every tree in the table and names the broken nodes:

let report = Category::check_tree().await?;
if report.is_broken() {
    println!("bad bounds: {:?}", report.oddness);
    println!("shared bounds: {:?}", report.duplicates);
    println!("parent_id doesn't match the bounds: {:?}", report.wrong_parent);
    println!("parent_id points nowhere: {:?}", report.missing_parent);
}

fix_tree rebuilds every bound from parent_id, in one transaction, and returns how many rows it changed:

let changed = Category::fix_tree().await?;

Siblings keep their current order. A node whose parent is gone, or that sits in a parent_id cycle, becomes a root. The same call turns an existing parent_id table into a nested set: add the columns with table.nested_set() or, when parent_id is already there, with big_integer("lft").default(0) and big_integer("rgt").default(0), then run fix_tree once.

Concurrency

Every write runs in a transaction on the model's connection and first locks the tree it changes:

Database Lock
PostgreSQL pg_advisory_xact_lock on the table and scope values
MySQL, MariaDB The tree's root rows, FOR UPDATE
SQLite The database write lock, taken before any bound is read

The bounds of every node involved are read again under the lock, so a stale model in your hands can't put a node in the wrong place. On PostgreSQL, writes to different trees of a scoped table don't wait for each other. New roots and moves to root also take turns across the whole table, because a new root's tree is only known once its row is in.

On MySQL, two roots created at the same moment in a table without any rows yet can hit a deadlock: the database rolls one of them back and returns the error, and the tree stays valid. Retry that create.

The test suite runs concurrent writers on all three databases, and a property test runs random sequences of every operation, checking the tree after each step.

Nested set, adjacency list, or closure table?

Adjacency list (parent_id only) Nested set (this package) Closure table
Children One query One query One query
Whole subtree, ancestors Recursive CTE or one query per level One indexed range query One join
Insert One row One row plus shifting bounds to its right One row plus one per ancestor
Move a subtree One update Two updates, touching the rows between old and new place Delete and insert paths for the whole subtree
Extra storage None Two integers per row One row per ancestor-descendant pair
Best for Write-heavy trees, shallow reads Read-heavy trees: categories, menus, breadcrumbs Deep trees with frequent moves and reads

Nested sets pay on writes to make reads cheap, which suits trees that are read on every page and edited from an admin panel.

Custom column names

The bound and parent columns can have any names: map the fields and return them from lft_column, rgt_column, and parent_column. For a table whose bounds are _lft and _rgt:

#[model]
pub struct Category {
    pub id: i64,
    #[column("_lft")]
    pub lft: i64,
    #[column("_rgt")]
    pub rgt: i64,
    pub parent_id: Option<i64>,
}

Not there yet: rebuilding existing nodes from a nested list, and eager loading ancestors or descendants as relations.

Testing

Tests run in Docker; nothing gets installed on the host. run.sh runs a command in rust:1.99 with rustfmt and clippy added. SQLite runs in memory:

./run.sh cargo test

PostgreSQL and MySQL run from docker-compose.yml:

docker compose up -d
DATABASE_ENV="-e NESTEDSET_TEST_POSTGRES_URL=postgres://postgres:secret@127.0.0.1:55432/postgres \
  -e NESTEDSET_TEST_MYSQL_URL=mysql://root:secret@127.0.0.1:53306/nestedset" \
  ./run.sh cargo test --features postgres,mysql

License

MIT. See LICENSE.md.