Skip to main content

NestedSet

Trait NestedSet 

Source
pub trait NestedSet: Model {
Show 75 methods // Required methods fn lft_column() -> Column<Self, i64>; fn rgt_column() -> Column<Self, i64>; fn parent_column() -> Column<Self, Option<Self::Key>>; // Provided methods fn depth_column() -> Option<Column<Self, i64>> { ... } fn scope(&self) -> Scope<Self> { ... } fn lft(&self) -> i64 { ... } fn rgt(&self) -> i64 { ... } fn parent_key(&self) -> Option<&Self::Key> { ... } fn node_key(&self) -> &Self::Key { ... } fn is_root(&self) -> bool { ... } fn is_leaf(&self) -> bool { ... } fn descendant_count(&self) -> i64 { ... } fn is_descendant_of(&self, other: &Self) -> bool { ... } fn is_ancestor_of(&self, other: &Self) -> bool { ... } fn tree_query(&self) -> Builder<Self> { ... } fn roots() -> Builder<Self> { ... } fn children(&self) -> Builder<Self> { ... } fn descendants(&self) -> Builder<Self> { ... } fn descendants_and_self(&self) -> Builder<Self> { ... } fn ancestors(&self) -> Builder<Self> { ... } fn ancestors_and_self(&self) -> Builder<Self> { ... } fn allowed_parents(&self) -> Builder<Self> { ... } fn path( &self, column: Column<Self, String>, separator: &str, ) -> impl Future<Output = Result<String>> + Send { ... } fn find_by_path( column: Column<Self, String>, path: &str, ) -> impl Future<Output = Result<Option<Self>>> + Send { ... } fn find_by_path_below( &self, column: Column<Self, String>, path: &str, ) -> impl Future<Output = Result<Option<Self>>> + Send { ... } fn where_descendant_of(node: &Self) -> Condition { ... } fn where_descendant_or_self(node: &Self) -> Condition { ... } fn where_ancestor_of(node: &Self) -> Condition { ... } fn where_ancestor_or_self(node: &Self) -> Condition { ... } fn where_child_of(node: &Self) -> Condition { ... } fn where_in_subtree<R, T>( node: &Self, foreign_key: Column<R, T>, ) -> Condition where T: Send + Sync + 'static { ... } fn where_root() -> Condition { ... } fn where_has_parent() -> Condition { ... } fn where_leaf() -> Condition { ... } fn where_has_children() -> Condition { ... } fn ancestors_of( key: Self::Key, ) -> impl Future<Output = Result<Vec<Self>>> + Send { ... } fn ancestors_and_self_of( key: Self::Key, ) -> impl Future<Output = Result<Vec<Self>>> + Send { ... } fn descendants_of( key: Self::Key, ) -> impl Future<Output = Result<Vec<Self>>> + Send { ... } fn descendants_and_self_of( key: Self::Key, ) -> impl Future<Output = Result<Vec<Self>>> + Send { ... } fn children_of( key: Self::Key, ) -> impl Future<Output = Result<Vec<Self>>> + Send { ... } fn subtree_of( key: Self::Key, ) -> impl Future<Output = Result<TreeNode<Self>>> + Send { ... } fn parent(&self) -> impl Future<Output = Result<Option<Self>>> + Send { ... } fn depth(&self) -> impl Future<Output = Result<u64>> + Send { ... } fn siblings(&self) -> Builder<Self> { ... } fn next_siblings(&self) -> Builder<Self> { ... } fn prev_siblings(&self) -> Builder<Self> { ... } fn next_sibling(&self) -> impl Future<Output = Result<Option<Self>>> + Send { ... } fn prev_sibling(&self) -> impl Future<Output = Result<Option<Self>>> + Send { ... } fn is_child_of(&self, other: &Self) -> bool { ... } fn is_sibling_of(&self, other: &Self) -> bool { ... } fn default_order(query: Builder<Self>) -> Builder<Self> { ... } fn reversed(query: Builder<Self>) -> Builder<Self> { ... } fn leaves() -> Builder<Self> { ... } fn create_root( create: impl Into<CreateBuilder<Self>> + Send, ) -> impl Future<Output = Result<Self>> + Send { ... } fn create_root_in( scope: Scope<Self>, create: impl Into<CreateBuilder<Self>> + Send, ) -> impl Future<Output = Result<Self>> + Send { ... } fn create_child( &mut self, create: impl Into<CreateBuilder<Self>> + Send, ) -> impl Future<Output = Result<Self>> + Send where Option<Self::Key>: IntoExpr { ... } fn create_first_child( &mut self, create: impl Into<CreateBuilder<Self>> + Send, ) -> impl Future<Output = Result<Self>> + Send where Option<Self::Key>: IntoExpr { ... } fn create_before( &mut self, create: impl Into<CreateBuilder<Self>> + Send, ) -> impl Future<Output = Result<Self>> + Send where Option<Self::Key>: IntoExpr { ... } fn create_after( &mut self, create: impl Into<CreateBuilder<Self>> + Send, ) -> impl Future<Output = Result<Self>> + Send where Option<Self::Key>: IntoExpr { ... } fn create_tree( tree: NewNode<Self>, ) -> impl Future<Output = Result<Self>> + Send where Option<Self::Key>: IntoExpr { ... } fn create_child_tree( &mut self, tree: NewNode<Self>, ) -> impl Future<Output = Result<Self>> + Send where Option<Self::Key>: IntoExpr { ... } fn make_root(&mut self) -> impl Future<Output = Result<()>> + Send where Option<Self::Key>: IntoExpr { ... } fn append_to( &mut self, parent: &Self, ) -> impl Future<Output = Result<()>> + Send where Option<Self::Key>: IntoExpr { ... } fn prepend_to( &mut self, parent: &Self, ) -> impl Future<Output = Result<()>> + Send where Option<Self::Key>: IntoExpr { ... } fn insert_before( &mut self, neighbor: &Self, ) -> impl Future<Output = Result<()>> + Send where Option<Self::Key>: IntoExpr { ... } fn insert_after( &mut self, neighbor: &Self, ) -> impl Future<Output = Result<()>> + Send where Option<Self::Key>: IntoExpr { ... } fn copy_to( &self, target: &Self, ) -> impl Future<Output = Result<Self>> + Send where Option<Self::Key>: IntoExpr { ... } fn copy_as_root(&self) -> impl Future<Output = Result<Self>> + Send where Option<Self::Key>: IntoExpr { ... } fn up(&mut self, by: u64) -> impl Future<Output = Result<bool>> + Send where Option<Self::Key>: IntoExpr { ... } fn down(&mut self, by: u64) -> impl Future<Output = Result<bool>> + Send where Option<Self::Key>: IntoExpr { ... } fn delete_subtree(self) -> impl Future<Output = Result<u64>> + Send { ... } fn arrange( items: Vec<Arrangement<Self::Key>>, ) -> impl Future<Output = Result<u64>> + Send where Option<Self::Key>: IntoExpr { ... } fn arrange_children( &mut self, items: Vec<Arrangement<Self::Key>>, ) -> impl Future<Output = Result<u64>> + Send where Option<Self::Key>: IntoExpr { ... } fn check_tree( ) -> impl Future<Output = Result<TreeReport<Self::Key>>> + Send { ... } fn fix_tree() -> impl Future<Output = Result<u64>> + Send where Option<Self::Key>: IntoExpr { ... }
}
Expand description

A model stored as a nested set: each row keeps the lft and rgt bounds of its subtree and the key of its parent.

use laravel::model::{Column, model};
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>,
}

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
    }
}

Every write runs in a transaction that holds a lock on the node’s tree, so concurrent writes to the same tree wait for each other instead of corrupting the bounds.

Required Methods§

Source

fn lft_column() -> Column<Self, i64>

The left bound column, lft by nested_set.

Source

fn rgt_column() -> Column<Self, i64>

The right bound column, rgt by nested_set.

Source

fn parent_column() -> Column<Self, Option<Self::Key>>

The parent key column, parent_id by nested_set. Roots hold NULL.

Provided Methods§

Source

fn depth_column() -> Option<Column<Self, i64>>

An optional column that stores each node’s depth: 0 for roots, 1 for their children, and so on. When the model has one, every write keeps it current, depth reads it without a query, and a query can filter by level: Category::query().filter(Category::depth.eq(1)). Add it with nested_set_depth. None by default.

Source

fn scope(&self) -> Scope<Self>

The columns that separate trees in one table, such as a menu’s items by menu_id. The whole table by default.

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

fn lft(&self) -> i64

The node’s left bound.

Source

fn rgt(&self) -> i64

The node’s right bound.

Source

fn parent_key(&self) -> Option<&Self::Key>

The node’s parent key, None for a root.

Source

fn node_key(&self) -> &Self::Key

The node’s own key.

Source

fn is_root(&self) -> bool

Whether the node has no parent.

Source

fn is_leaf(&self) -> bool

Whether the node has no children.

Source

fn descendant_count(&self) -> i64

How many descendants the node has, read from its bounds without a query.

Source

fn is_descendant_of(&self, other: &Self) -> bool

Whether the node is inside other’s subtree. Compares the bounds the two models hold, so both must be fresh and of the same tree.

Source

fn is_ancestor_of(&self, other: &Self) -> bool

Whether other is inside this node’s subtree.

Source

fn tree_query(&self) -> Builder<Self>

Every row of this node’s tree.

Source

fn roots() -> Builder<Self>

The roots of every tree in the table, ordered by their left bound.

Source

fn children(&self) -> Builder<Self>

The node’s direct children, in tree order.

Source

fn descendants(&self) -> Builder<Self>

Every node below this one, in tree order: one query for the whole subtree.

Source

fn descendants_and_self(&self) -> Builder<Self>

The node and every node below it, in tree order.

Source

fn ancestors(&self) -> Builder<Self>

Every node above this one, from the root down: the breadcrumbs.

Source

fn ancestors_and_self(&self) -> Builder<Self>

Every node above this one and the node itself, from the root down.

Source

fn allowed_parents(&self) -> Builder<Self>

The nodes this node may move under: every node of its tree except itself and its subtree, in tree order. Feed it to the parent <select> of an edit form, so nobody can pick a node below the one they edit:

use laravel_nestedset::IntoTree;

let options: Vec<(String, i64)> = category
    .allowed_parents()
    .get()
    .await?
    .into_flat_tree_with_depth()
    .into_iter()
    .map(|(node, depth)| (format!("{}{}", "— ".repeat(depth), node.name), node.id))
    .collect();
Source

fn path( &self, column: Column<Self, String>, separator: &str, ) -> impl Future<Output = Result<String>> + Send

The values of column from the root down to this node, joined by separator: a slug path such as shop/phones/android, or breadcrumbs as text.

§Errors

Fails when the query fails.

Source

fn find_by_path( column: Column<Self, String>, path: &str, ) -> impl Future<Output = Result<Option<Self>>> + Send

The node at a slug path such as shop/phones/android: a root whose column is shop, its child phones, and that one’s child android. One query, for the nodes whose column is one of the segments. None when no node is at the path. In a scoped table, the first tree with a match wins; use find_by_path_below from a root to stay in one tree.

§Errors

Fails when the query fails.

Source

fn find_by_path_below( &self, column: Column<Self, String>, path: &str, ) -> impl Future<Output = Result<Option<Self>>> + Send

The node at a slug path below this one: phones/android from the shop node.

§Errors

Fails when the query fails.

Source

fn where_descendant_of(node: &Self) -> Condition

Matches the nodes below node, in its tree. Combine it with any other condition:

let pro_phones = Category::query()
    .filter(Category::where_descendant_of(&phones) & Category::name.contains("Pro"))
    .get()
    .await?;
Source

fn where_descendant_or_self(node: &Self) -> Condition

Matches node and the nodes below it.

Source

fn where_ancestor_of(node: &Self) -> Condition

Matches the nodes above node.

Source

fn where_ancestor_or_self(node: &Self) -> Condition

Matches node and the nodes above it.

Source

fn where_child_of(node: &Self) -> Condition

Matches the direct children of node.

Source

fn where_in_subtree<R, T>(node: &Self, foreign_key: Column<R, T>) -> Condition
where T: Send + Sync + 'static,

Matches the rows of another table that point at node or at any node below it: every product of a category and its subcategories, in one query of the products.

let cheap_phones = Product::query()
    .filter(Category::where_in_subtree(&phones, Product::category_id) & Product::price.lt(300))
    .get()
    .await?;
Source

fn where_root() -> Condition

Matches roots.

Source

fn where_has_parent() -> Condition

Matches nodes with a parent.

Source

fn where_leaf() -> Condition

Matches nodes without children.

Source

fn where_has_children() -> Condition

Matches nodes with children.

Source

fn ancestors_of( key: Self::Key, ) -> impl Future<Output = Result<Vec<Self>>> + Send

The nodes above the node with key, from the root down, without loading the node first yourself.

let breadcrumbs = Category::ancestors_of(id).await?;
§Errors

Fails with NestedSetError::NodeNotFound when there’s no such node, and when a query fails.

Source

fn ancestors_and_self_of( key: Self::Key, ) -> impl Future<Output = Result<Vec<Self>>> + Send

The node with key and the nodes above it, from the root down.

§Errors

As ancestors_of.

Source

fn descendants_of( key: Self::Key, ) -> impl Future<Output = Result<Vec<Self>>> + Send

The nodes below the node with key, in tree order.

§Errors

As ancestors_of.

Source

fn descendants_and_self_of( key: Self::Key, ) -> impl Future<Output = Result<Vec<Self>>> + Send

The node with key and the nodes below it, in tree order.

§Errors

As ancestors_of.

Source

fn children_of(key: Self::Key) -> impl Future<Output = Result<Vec<Self>>> + Send

The direct children of the node with key, in tree order.

§Errors

As ancestors_of.

Source

fn subtree_of( key: Self::Key, ) -> impl Future<Output = Result<TreeNode<Self>>> + Send

The node with key and its whole subtree, nested: one query for the subtree.

impl NestedSet for MenuItem {
    fn scope(&self) -> Scope<Self> {
        Scope::new().by(MenuItem::menu_id, &self.menu_id)
    }
}
let menu = MenuItem::subtree_of(header_id).await?; // a TreeNode with its children
§Errors

As ancestors_of.

Source

fn parent(&self) -> impl Future<Output = Result<Option<Self>>> + Send

The node’s parent, None for a root.

§Errors

Fails when the query fails.

Source

fn depth(&self) -> impl Future<Output = Result<u64>> + Send

The node’s depth: 0 for a root, 1 for its children, and so on. Read from the depth_column when the model has one, or one count query.

§Errors

Fails when the query fails.

Source

fn siblings(&self) -> Builder<Self>

The other nodes with the same parent, in tree order. For a root, the other roots of its scope.

Source

fn next_siblings(&self) -> Builder<Self>

The siblings after this node, nearest first.

Source

fn prev_siblings(&self) -> Builder<Self>

The siblings before this node, in tree order: the nearest is the last.

Source

fn next_sibling(&self) -> impl Future<Output = Result<Option<Self>>> + Send

The sibling right after this node, if there is one.

§Errors

Fails when the query fails.

Source

fn prev_sibling(&self) -> impl Future<Output = Result<Option<Self>>> + Send

The sibling right before this node, if there is one.

§Errors

Fails when the query fails.

Source

fn is_child_of(&self, other: &Self) -> bool

Whether other is this node’s parent.

Source

fn is_sibling_of(&self, other: &Self) -> bool

Whether this node and other are different nodes with the same parent.

Source

fn default_order(query: Builder<Self>) -> Builder<Self>

Orders a query by the left bound: tree order, each node before its children. Use it as a scope: Category::query().scope(Category::default_order).

Source

fn reversed(query: Builder<Self>) -> Builder<Self>

Orders a query by the left bound, descending: tree order reversed.

Source

fn leaves() -> Builder<Self>

Every node without children, across the table. Filter it to a tree with tree_query’s scope when the table has several.

Source

fn create_root( create: impl Into<CreateBuilder<Self>> + Send, ) -> impl Future<Output = Result<Self>> + Send

Creates a new root after the last tree of its scope.

The new row’s scope is only known once it’s in, so this locks the roots of the whole table first: new roots anywhere in the table take turns. In a table with many trees that get new roots often, such as one tree per comment thread, use create_root_in, which locks only the one tree.

let shop = Category::create_root(Category::create().name("Shop")).await?;
§Errors

Fails when a query fails.

Source

fn create_root_in( scope: Scope<Self>, create: impl Into<CreateBuilder<Self>> + Send, ) -> impl Future<Output = Result<Self>> + Send

Creates a new root in the tree of scope, locking only that tree: new roots of other trees don’t wait for it. The scope’s values fill the create, and the root goes after the tree’s last one, in one insert.

let comment = Comment::create_root_in(
    Scope::new().by(Comment::thread_id, &thread_id),
    Comment::create().body("First!"),
)
.await?;

On PostgreSQL the lock is per tree. MySQL and MariaDB can’t lock a tree that has no rows yet, so there new roots still take turns across the table, as with create_root, but for a shorter time and without deadlocks between new trees.

§Errors

Fails with NestedSetError::OutsideScope when scope isn’t built from the model’s scope columns, so the new row would land outside it; nothing is written then. Fails when a query fails.

Source

fn create_child( &mut self, create: impl Into<CreateBuilder<Self>> + Send, ) -> impl Future<Output = Result<Self>> + Send
where Option<Self::Key>: IntoExpr,

Creates a new node as the last child of this one, and reloads this node. The child gets this node’s scope values.

let phones = shop.create_child(Category::create().name("Phones")).await?;
§Errors

Fails when this node no longer exists or a query fails.

Source

fn create_first_child( &mut self, create: impl Into<CreateBuilder<Self>> + Send, ) -> impl Future<Output = Result<Self>> + Send
where Option<Self::Key>: IntoExpr,

Creates a new node as the first child of this one, and reloads this node.

§Errors

Fails when this node no longer exists or a query fails.

Source

fn create_before( &mut self, create: impl Into<CreateBuilder<Self>> + Send, ) -> impl Future<Output = Result<Self>> + Send
where Option<Self::Key>: IntoExpr,

Creates a new node right before this one, with the same parent, and reloads this node.

§Errors

Fails when this node no longer exists or a query fails.

Source

fn create_after( &mut self, create: impl Into<CreateBuilder<Self>> + Send, ) -> impl Future<Output = Result<Self>> + Send
where Option<Self::Key>: IntoExpr,

Creates a new node right after this one, with the same parent, and reloads this node.

§Errors

Fails when this node no longer exists or a query fails.

Source

fn create_tree(tree: NewNode<Self>) -> impl Future<Output = Result<Self>> + Send
where Option<Self::Key>: IntoExpr,

Creates a root with all its children from nested NewNodes, and returns the root.

§Errors

Fails when a query fails. The nodes created before the failure stay.

Source

fn create_child_tree( &mut self, tree: NewNode<Self>, ) -> impl Future<Output = Result<Self>> + Send
where Option<Self::Key>: IntoExpr,

Creates tree with all its children as the last child of this node, and returns its top node.

§Errors

Fails when this node no longer exists or a query fails.

Source

fn make_root(&mut self) -> impl Future<Output = Result<()>> + Send
where Option<Self::Key>: IntoExpr,

Moves this node with its subtree to the end of its scope, as a root. Reloads this node.

§Errors

Fails when this node no longer exists or a query fails.

Source

fn append_to( &mut self, parent: &Self, ) -> impl Future<Output = Result<()>> + Send
where Option<Self::Key>: IntoExpr,

Moves this node with its subtree to be the last child of parent. Reloads this node; reload parent before you read its bounds.

§Errors

Fails with NestedSetError::MoveIntoOwnSubtree when parent is this node or below it, with NestedSetError::ScopeMismatch when it’s in another tree, and when a node no longer exists or a query fails.

Source

fn prepend_to( &mut self, parent: &Self, ) -> impl Future<Output = Result<()>> + Send
where Option<Self::Key>: IntoExpr,

Moves this node with its subtree to be the first child of parent.

§Errors

As append_to.

Source

fn insert_before( &mut self, neighbor: &Self, ) -> impl Future<Output = Result<()>> + Send
where Option<Self::Key>: IntoExpr,

Moves this node with its subtree right before neighbor, under neighbor’s parent.

§Errors

As append_to.

Source

fn insert_after( &mut self, neighbor: &Self, ) -> impl Future<Output = Result<()>> + Send
where Option<Self::Key>: IntoExpr,

Moves this node with its subtree right after neighbor, under neighbor’s parent.

§Errors

As append_to.

Source

fn copy_to(&self, target: &Self) -> impl Future<Output = Result<Self>> + Send
where Option<Self::Key>: IntoExpr,

Copies this node with its whole subtree as the last child of target, and returns the copy. Every column is copied except the key and the timestamps, as replicate does, and the copies take target’s tree: copy the header menu into the footer menu, say. The copies are inserted one by one, so model hooks and events run for each.

§Errors

Fails when this node or target no longer exists or a query fails; nothing is copied then.

Source

fn copy_as_root(&self) -> impl Future<Output = Result<Self>> + Send
where Option<Self::Key>: IntoExpr,

Copies this node with its whole subtree as a new root after the last one of its tree.

§Errors

As copy_to.

Source

fn up(&mut self, by: u64) -> impl Future<Output = Result<bool>> + Send
where Option<Self::Key>: IntoExpr,

Moves this node by places up among its siblings. Returns whether it moved: false when there aren’t by siblings before it.

§Errors

Fails when a node no longer exists or a query fails.

Source

fn down(&mut self, by: u64) -> impl Future<Output = Result<bool>> + Send
where Option<Self::Key>: IntoExpr,

Moves this node by places down among its siblings. Returns whether it moved.

§Errors

Fails when a node no longer exists or a query fails.

Source

fn delete_subtree(self) -> impl Future<Output = Result<u64>> + Send

Deletes this node and every node below it, and closes the gap in the bounds. Returns how many rows it deleted.

Delete nodes only this way: deleting a row with the model’s delete or a query leaves a gap in the bounds and orphans its children. The rows go with one query, so model hooks and events don’t run for them.

§Errors

Fails when this node no longer exists or a query fails.

Source

fn arrange( items: Vec<Arrangement<Self::Key>>, ) -> impl Future<Output = Result<u64>> + Send
where Option<Self::Key>: IntoExpr,

Rearranges a tree the way items lists it: the listed nodes become roots, in the listed order, with the listed children below them. Made for saving a drag-and-drop tree editor:

use laravel_nestedset::Arrangement;

// [{"id": 1, "children": [{"id": 3}, {"id": 2}]}, {"id": 4}]
let items: Vec<Arrangement<i64>> = serde_json::from_str(body)?;
Category::arrange(items).await?;

Every listed node must be in one tree, the tree of the first one. Nodes of that tree the list leaves out keep their parent and come after the listed siblings. One transaction rebuilds the whole tree; returns how many rows changed.

§Errors

Fails with NestedSetError::NodeNotFound when a listed node isn’t in the tree, with NestedSetError::DuplicateKey when one is listed twice, and when a query fails. Nothing changes then.

Source

fn arrange_children( &mut self, items: Vec<Arrangement<Self::Key>>, ) -> impl Future<Output = Result<u64>> + Send
where Option<Self::Key>: IntoExpr,

Rearranges the nodes below this one the way items lists them, as arrange does for roots, and reloads this node.

§Errors

As arrange, and with NestedSetError::MoveIntoOwnSubtree when the list holds this node or one above it.

Source

fn check_tree() -> impl Future<Output = Result<TreeReport<Self::Key>>> + Send

Checks every tree in the table and names the broken nodes.

§Errors

Fails when the query fails.

Source

fn fix_tree() -> impl Future<Output = Result<u64>> + Send
where Option<Self::Key>: IntoExpr,

Rebuilds the bounds of every tree in the table from parent_id. Use it to repair a tree, or to fill lft and rgt on a table that only had parent_id. Siblings keep their order; a node whose parent is missing becomes a root. Returns how many rows it changed.

§Errors

Fails when a query fails; nothing changes then.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§