laravel-nestedset 0.1.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::{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):
///
/// ```ignore
/// 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
    }

    /// 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()
    }
}