laravel-nestedset 0.2.0

Nested set trees for Laravel Rust models: fast subtree and ancestor queries, safe under concurrent writes.
Documentation
//! `Scope`: the columns that split one table into several independent trees.

use std::fmt::{Debug, Write};

use laravel::db::{self, Builder, Condition};
use laravel::model::{Column, ComparableTo, CreateBuilder, FillValue, Model};

type Setter<M> = Box<dyn Fn(CreateBuilder<M>) -> CreateBuilder<M> + Send + Sync>;

/// The columns that tell trees in one table apart, such as the `menu_id` of a menu item.
///
/// Every query and write of the package stays inside the scope of the node it starts from, and a
/// new child gets its parent's scope values. Build it in
/// [`NestedSet::scope`](crate::NestedSet::scope):
///
/// ```no_run
/// # use laravel::model::{Column, model};
/// # use laravel_nestedset::{NestedSet, Scope};
/// # #[model]
/// # pub struct MenuItem {
/// #     pub id: i64,
/// #     pub menu_id: i64,
/// #     pub title: String,
/// #     #[default]
/// #     pub lft: i64,
/// #     #[default]
/// #     pub rgt: i64,
/// #     pub parent_id: Option<i64>,
/// # }
/// impl NestedSet for MenuItem {
/// #     fn lft_column() -> Column<Self, i64> { MenuItem::lft }
/// #     fn rgt_column() -> Column<Self, i64> { MenuItem::rgt }
/// #     fn parent_column() -> Column<Self, Option<i64>> { MenuItem::parent_id }
///     fn scope(&self) -> Scope<Self> {
///         Scope::new().by(MenuItem::menu_id, &self.menu_id)
///     }
/// }
/// ```
pub struct Scope<M: Model> {
    conditions: Vec<Condition>,
    setters: Vec<Setter<M>>,
    key: String,
}

impl<M: Model> Scope<M> {
    /// A scope over the whole table: one tree, or several roots side by side.
    #[must_use]
    pub fn new() -> Self {
        Self {
            conditions: Vec::new(),
            setters: Vec::new(),
            key: String::new(),
        }
    }

    /// Adds the column `column` with the value `value` to the scope.
    #[must_use]
    pub fn by<T>(mut self, column: Column<M, T>, value: &T) -> Self
    where
        T: Clone + Debug + Send + Sync + 'static,
        T: ComparableTo<T> + FillValue<T>,
    {
        self.conditions.push(column.eq(value.clone()));
        let owned = value.clone();
        self.setters
            .push(Box::new(move |create| create.set(column, owned.clone())));
        let _ = write!(self.key, "|{}={value:?}", column.name());
        self
    }

    /// The condition that matches the rows of this scope: every row when the scope has no
    /// columns.
    #[must_use]
    pub fn condition(&self) -> Condition {
        db::all(self.conditions.iter().cloned())
    }

    /// Filters `query` to the rows of this scope.
    pub fn apply(&self, mut query: Builder<M>) -> Builder<M> {
        for condition in &self.conditions {
            query = query.filter(condition.clone());
        }
        query
    }

    /// Gives a create the scope's values.
    pub(crate) fn fill(&self, mut create: CreateBuilder<M>) -> CreateBuilder<M> {
        for setter in &self.setters {
            create = setter(create);
        }
        create
    }

    /// A stable text that names this tree, used for the tree lock.
    pub(crate) fn lock_name(&self) -> String {
        format!("{}{}", M::META.table, self.key)
    }
}

impl<M: Model> Default for Scope<M> {
    fn default() -> Self {
        Self::new()
    }
}