laravel-nestedset 0.2.1

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::{HashMap, HashSet};
use std::future::Future;

use laravel::db::{self, Condition, IntoCondition, col};
use laravel::model::{__query, Column, Model};
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>,
}

/// A node with a count of the related rows in its subtree, built by
/// [`LoadRelatives::with_subtree_counts`]. It serializes as the model's own fields plus `count`.
#[derive(Debug, Clone, Serialize)]
pub struct WithCount<M> {
    /// The node.
    #[serde(flatten)]
    pub node: M,
    /// The related rows that point at the node or at any node below it.
    pub count: u64,
}

/// 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;

    /// Each node with a count of the rows of another table that point at it or at any node below
    /// it: the products of a category and all its subcategories, say. One query for the list:
    ///
    /// ```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 }
    /// # }
    /// # #[model]
    /// # pub struct Product {
    /// #     pub id: i64,
    /// #     pub category_id: i64,
    /// #     pub published: bool,
    /// # }
    /// use laravel_nestedset::LoadRelatives;
    ///
    /// # async fn example() -> laravel::Result<()> {
    /// let menu = Category::roots()
    ///     .get()
    ///     .await?
    ///     .with_subtree_counts(Product::category_id)
    ///     .await?;
    ///
    /// for entry in &menu {
    ///     println!("{} ({})", entry.node.name, entry.count); // Phones (124)
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Fails when the query fails.
    fn with_subtree_counts<R, T>(
        self,
        foreign_key: Column<R, T>,
    ) -> impl Future<Output = laravel::Result<Vec<WithCount<M>>>> + Send
    where
        R: Model,
        T: Send + Sync + 'static;

    /// [`with_subtree_counts`](Self::with_subtree_counts), counting only the rows that `filter`
    /// matches, such as `Product::published.eq(true)`. The filter may use the other table's
    /// typed columns: the query joins that table under its own name.
    ///
    /// # Errors
    ///
    /// Fails when the query fails.
    fn with_subtree_counts_where<R, T>(
        self,
        foreign_key: Column<R, T>,
        filter: impl IntoCondition + Send,
    ) -> impl Future<Output = laravel::Result<Vec<WithCount<M>>>> + Send
    where
        R: Model,
        T: Send + Sync + 'static;
}

impl<M: NestedSet> LoadRelatives<M> for Vec<M> {
    async fn with_subtree_counts<R, T>(self, foreign_key: Column<R, T>) -> laravel::Result<Vec<WithCount<M>>>
    where
        R: Model,
        T: Send + Sync + 'static,
    {
        self.with_subtree_counts_where(foreign_key, None::<Condition>).await
    }

    async fn with_subtree_counts_where<R, T>(
        self,
        foreign_key: Column<R, T>,
        filter: impl IntoCondition + Send,
    ) -> laravel::Result<Vec<WithCount<M>>>
    where
        R: Model,
        T: Send + Sync + 'static,
    {
        let filter = db::all([filter]);
        let counts = subtree_counts(&self, foreign_key, filter).await?;
        Ok(self
            .into_iter()
            .map(|node| {
                let count = counts.get(node.node_key()).copied().unwrap_or(0);
                WithCount { node, count }
            })
            .collect())
    }

    async fn with_ancestors(self) -> laravel::Result<Vec<WithAncestors<M>>> {
        let starts: Option<Vec<crate::chain::ChainStart>> =
            self.iter().map(|node| crate::chain::chain_start(node, false)).collect();
        let found = match starts {
            // Integer keys: one recursive query up every node's parent chain.
            Some(starts) => {
                let starts = crate::chain::chain_keys(starts);
                __query::<M>()
                    .filter(crate::chain::chain::<M>(&starts))
                    .order_by(M::lft_column().asc())
                    .get()
                    .await?
            }
            None => 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)
}

/// The count of rows of `R` below each of `nodes`, keyed by node.
async fn subtree_counts<M: NestedSet, R: Model, T>(
    nodes: &[M],
    foreign_key: Column<R, T>,
    filter: Condition,
) -> laravel::Result<HashMap<M::Key, u64>> {
    let Some(first) = nodes.first() else {
        return Ok(HashMap::new());
    };
    let (table, key) = (M::META.table, M::META.key.name());
    let (lft, rgt) = (M::lft_column().name(), M::rgt_column().name());
    let node = |column: &str| col(format!("nested_node.{column}"));
    let below = |column: &str| col(format!("nested_below.{column}"));
    // The nodes below each listed node, itself included, in the same tree.
    let mut subtree = below(lft).ge(node(lft)) & below(lft).le(node(rgt));
    for name in first.scope().names() {
        subtree &= below(name).eq(node(name));
    }
    let related = R::META.table;
    let points_below = col(format!("{related}.{}", foreign_key.name())).eq(below(key));

    let mut counts = HashMap::new();
    for chunk in nodes.chunks(CHUNK) {
        let keys: Vec<M::Key> = chunk.iter().map(|node| node.node_key().clone()).collect();
        let mut query = db::table(format!("{table} as nested_node"));
        if let Some(connection) = M::META.connection {
            query = query.connection(connection);
        }
        let rows = query
            .join(format!("{table} as nested_below"), subtree.clone())
            .join(related, points_below.clone())
            .filter(node(key).is_in(keys) & filter.clone())
            .select((node(key).alias("node_key"), col("*").count().alias("total")))
            .group_by([format!("nested_node.{key}")])
            .get::<(M::Key, i64)>()
            .await?;
        counts.extend(
            rows.into_iter()
                .map(|(key, total)| (key, u64::try_from(total).unwrap_or(0))),
        );
    }
    Ok(counts)
}

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