laravel-nestedset 0.2.0

Nested set trees for Laravel Rust models: fast subtree and ancestor queries, safe under concurrent writes.
Documentation
//! Loading the ancestors or the subtrees of many nodes at once: `with_ancestors` and
//! `with_descendants`.

use std::collections::HashSet;
use std::future::Future;

use laravel::db;
use laravel::model::__query;
use serde::Serialize;

use crate::node::NestedSet;
use crate::tree::{IntoTree, TreeNode};

/// How many nodes one query covers; a longer list takes several queries.
const CHUNK: usize = 200;

/// A node with its ancestors, built by [`LoadRelatives::with_ancestors`]. It serializes as the
/// model's own fields plus `ancestors`, from the root down.
#[derive(Debug, Clone, Serialize)]
pub struct WithAncestors<M> {
    /// The node.
    #[serde(flatten)]
    pub node: M,
    /// The nodes above it, from the root down: the breadcrumbs.
    pub ancestors: Vec<M>,
}

/// Loads the relatives of every node in a list with one query, instead of one per node.
///
/// ```no_run
/// # 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 }
/// # }
/// use laravel_nestedset::LoadRelatives;
/// # async fn example(term: &str) -> laravel::Result<()> {
/// // Breadcrumbs for a page of search results: two queries, however long the page.
/// let results = Category::query()
///     .filter(Category::name.contains(term))
///     .limit(20)
///     .get()
///     .await?
///     .with_ancestors()
///     .await?;
///
/// for result in &results {
///     let path: Vec<&str> = result.ancestors.iter().map(|node| node.name.as_str()).collect();
/// }
/// # Ok(())
/// # }
/// ```
pub trait LoadRelatives<M> {
    /// Each node with the nodes above it, from the root down.
    ///
    /// # Errors
    ///
    /// Fails when the query fails.
    fn with_ancestors(self) -> impl Future<Output = laravel::Result<Vec<WithAncestors<M>>>> + Send;

    /// Each node as the top of its own subtree, nested: the menu below each of several roots,
    /// for example.
    ///
    /// # Errors
    ///
    /// Fails when the query fails.
    fn with_descendants(self) -> impl Future<Output = laravel::Result<Vec<TreeNode<M>>>> + Send;
}

impl<M: NestedSet> LoadRelatives<M> for Vec<M> {
    async fn with_ancestors(self) -> laravel::Result<Vec<WithAncestors<M>>> {
        let found = load(&self, M::where_ancestor_of).await?;
        Ok(self
            .into_iter()
            .map(|node| {
                let ancestors = found
                    .iter()
                    .filter(|&candidate| same_tree(candidate, &node) && node.is_descendant_of(candidate))
                    .cloned()
                    .collect();
                WithAncestors { node, ancestors }
            })
            .collect())
    }

    async fn with_descendants(self) -> laravel::Result<Vec<TreeNode<M>>> {
        let found = load(&self, M::where_descendant_of).await?;
        Ok(self
            .into_iter()
            .map(|node| {
                let below = found
                    .iter()
                    .filter(|&candidate| same_tree(candidate, &node) && candidate.is_descendant_of(&node));
                let subtree: Vec<M> = std::iter::once(node.clone()).chain(below.cloned()).collect();
                subtree
                    .into_tree()
                    .into_iter()
                    .next()
                    .expect("the node tops its own subtree")
            })
            .collect())
    }
}

/// The rows that `relation` matches for any of `nodes`, in tree order.
async fn load<M: NestedSet>(nodes: &[M], relation: fn(&M) -> db::Condition) -> laravel::Result<Vec<M>> {
    let mut found = Vec::new();
    for chunk in nodes.chunks(CHUNK) {
        let rows = __query::<M>()
            .filter(db::any(chunk.iter().map(relation)))
            .order_by(M::lft_column().asc())
            .get()
            .await?;
        found.extend(rows);
    }
    // Nodes of one chunk can share relatives with another's: keep each row once, in tree order.
    let mut seen = HashSet::new();
    found.retain(|node| seen.insert(node.node_key().clone()));
    found.sort_by_key(NestedSet::lft);
    Ok(found)
}

fn same_tree<M: NestedSet>(a: &M, b: &M) -> bool {
    a.scope().lock_name() == b.scope().lock_name()
}