Skip to main content

laravel_nestedset/
scope.rs

1//! `Scope`: the columns that split one table into several independent trees.
2
3use std::fmt::{Debug, Write};
4
5use laravel::db::{self, Builder, Condition};
6use laravel::model::{Column, ComparableTo, CreateBuilder, FillValue, Model};
7
8type Setter<M> = Box<dyn Fn(CreateBuilder<M>) -> CreateBuilder<M> + Send + Sync>;
9
10/// The columns that tell trees in one table apart, such as the `menu_id` of a menu item.
11///
12/// Every query and write of the package stays inside the scope of the node it starts from, and a
13/// new child gets its parent's scope values. Build it in
14/// [`NestedSet::scope`](crate::NestedSet::scope):
15///
16/// ```no_run
17/// # use laravel::model::{Column, model};
18/// # use laravel_nestedset::{NestedSet, Scope};
19/// # #[model]
20/// # pub struct MenuItem {
21/// #     pub id: i64,
22/// #     pub menu_id: i64,
23/// #     pub title: String,
24/// #     #[default]
25/// #     pub lft: i64,
26/// #     #[default]
27/// #     pub rgt: i64,
28/// #     pub parent_id: Option<i64>,
29/// # }
30/// impl NestedSet for MenuItem {
31/// #     fn lft_column() -> Column<Self, i64> { MenuItem::lft }
32/// #     fn rgt_column() -> Column<Self, i64> { MenuItem::rgt }
33/// #     fn parent_column() -> Column<Self, Option<i64>> { MenuItem::parent_id }
34///     fn scope(&self) -> Scope<Self> {
35///         Scope::new().by(MenuItem::menu_id, &self.menu_id)
36///     }
37/// }
38/// ```
39pub struct Scope<M: Model> {
40    conditions: Vec<Condition>,
41    setters: Vec<Setter<M>>,
42    names: Vec<&'static str>,
43    key: String,
44}
45
46impl<M: Model> Scope<M> {
47    /// A scope over the whole table: one tree, or several roots side by side.
48    #[must_use]
49    pub fn new() -> Self {
50        Self {
51            conditions: Vec::new(),
52            setters: Vec::new(),
53            names: Vec::new(),
54            key: String::new(),
55        }
56    }
57
58    /// Adds the column `column` with the value `value` to the scope.
59    #[must_use]
60    pub fn by<T>(mut self, column: Column<M, T>, value: &T) -> Self
61    where
62        T: Clone + Debug + Send + Sync + 'static,
63        T: ComparableTo<T> + FillValue<T>,
64    {
65        self.conditions.push(column.eq(value.clone()));
66        self.names.push(column.name());
67        let owned = value.clone();
68        self.setters
69            .push(Box::new(move |create| create.set(column, owned.clone())));
70        let _ = write!(self.key, "|{}={value:?}", column.name());
71        self
72    }
73
74    /// The condition that matches the rows of this scope: every row when the scope has no
75    /// columns.
76    #[must_use]
77    pub fn condition(&self) -> Condition {
78        db::all(self.conditions.iter().cloned())
79    }
80
81    /// Filters `query` to the rows of this scope.
82    pub fn apply(&self, mut query: Builder<M>) -> Builder<M> {
83        for condition in &self.conditions {
84            query = query.filter(condition.clone());
85        }
86        query
87    }
88
89    /// The names of the scope's columns.
90    pub(crate) fn names(&self) -> &[&'static str] {
91        &self.names
92    }
93
94    /// Gives a create the scope's values.
95    pub(crate) fn fill(&self, mut create: CreateBuilder<M>) -> CreateBuilder<M> {
96        for setter in &self.setters {
97            create = setter(create);
98        }
99        create
100    }
101
102    /// A stable text that names this tree, used for the tree lock.
103    pub(crate) fn lock_name(&self) -> String {
104        format!("{}{}", M::META.table, self.key)
105    }
106}
107
108impl<M: Model> Default for Scope<M> {
109    fn default() -> Self {
110        Self::new()
111    }
112}