Skip to main content

laravel_nestedset/
relatives.rs

1//! Loading the ancestors or the subtrees of many nodes at once: `with_ancestors` and
2//! `with_descendants`.
3
4use std::collections::{HashMap, HashSet};
5use std::future::Future;
6
7use laravel::db::{self, Condition, IntoCondition, col};
8use laravel::model::{__query, Column, Model};
9use serde::Serialize;
10
11use crate::node::NestedSet;
12use crate::tree::{IntoTree, TreeNode};
13
14/// How many nodes one query covers; a longer list takes several queries.
15const CHUNK: usize = 200;
16
17/// A node with its ancestors, built by [`LoadRelatives::with_ancestors`]. It serializes as the
18/// model's own fields plus `ancestors`, from the root down.
19#[derive(Debug, Clone, Serialize)]
20pub struct WithAncestors<M> {
21    /// The node.
22    #[serde(flatten)]
23    pub node: M,
24    /// The nodes above it, from the root down: the breadcrumbs.
25    pub ancestors: Vec<M>,
26}
27
28/// A node with a count of the related rows in its subtree, built by
29/// [`LoadRelatives::with_subtree_counts`]. It serializes as the model's own fields plus `count`.
30#[derive(Debug, Clone, Serialize)]
31pub struct WithCount<M> {
32    /// The node.
33    #[serde(flatten)]
34    pub node: M,
35    /// The related rows that point at the node or at any node below it.
36    pub count: u64,
37}
38
39/// Loads the relatives of every node in a list with one query, instead of one per node.
40///
41/// ```no_run
42/// # use laravel::model::{Column, model};
43/// # use laravel_nestedset::NestedSet;
44/// # #[model]
45/// # pub struct Category {
46/// #     pub id: i64,
47/// #     pub name: String,
48/// #     #[default]
49/// #     pub lft: i64,
50/// #     #[default]
51/// #     pub rgt: i64,
52/// #     pub parent_id: Option<i64>,
53/// # }
54/// # impl NestedSet for Category {
55/// #     fn lft_column() -> Column<Self, i64> { Category::lft }
56/// #     fn rgt_column() -> Column<Self, i64> { Category::rgt }
57/// #     fn parent_column() -> Column<Self, Option<i64>> { Category::parent_id }
58/// # }
59/// use laravel_nestedset::LoadRelatives;
60/// # async fn example(term: &str) -> laravel::Result<()> {
61/// // Breadcrumbs for a page of search results: two queries, however long the page.
62/// let results = Category::query()
63///     .filter(Category::name.contains(term))
64///     .limit(20)
65///     .get()
66///     .await?
67///     .with_ancestors()
68///     .await?;
69///
70/// for result in &results {
71///     let path: Vec<&str> = result.ancestors.iter().map(|node| node.name.as_str()).collect();
72/// }
73/// # Ok(())
74/// # }
75/// ```
76pub trait LoadRelatives<M> {
77    /// Each node with the nodes above it, from the root down.
78    ///
79    /// # Errors
80    ///
81    /// Fails when the query fails.
82    fn with_ancestors(self) -> impl Future<Output = laravel::Result<Vec<WithAncestors<M>>>> + Send;
83
84    /// Each node as the top of its own subtree, nested: the menu below each of several roots,
85    /// for example.
86    ///
87    /// # Errors
88    ///
89    /// Fails when the query fails.
90    fn with_descendants(self) -> impl Future<Output = laravel::Result<Vec<TreeNode<M>>>> + Send;
91
92    /// Each node with a count of the rows of another table that point at it or at any node below
93    /// it: the products of a category and all its subcategories, say. One query for the list:
94    ///
95    /// ```no_run
96    /// # use laravel::model::{Column, model};
97    /// # use laravel_nestedset::NestedSet;
98    /// # #[model]
99    /// # pub struct Category {
100    /// #     pub id: i64,
101    /// #     pub name: String,
102    /// #     #[default]
103    /// #     pub lft: i64,
104    /// #     #[default]
105    /// #     pub rgt: i64,
106    /// #     pub parent_id: Option<i64>,
107    /// # }
108    /// # impl NestedSet for Category {
109    /// #     fn lft_column() -> Column<Self, i64> { Category::lft }
110    /// #     fn rgt_column() -> Column<Self, i64> { Category::rgt }
111    /// #     fn parent_column() -> Column<Self, Option<i64>> { Category::parent_id }
112    /// # }
113    /// # #[model]
114    /// # pub struct Product {
115    /// #     pub id: i64,
116    /// #     pub category_id: i64,
117    /// #     pub published: bool,
118    /// # }
119    /// use laravel_nestedset::LoadRelatives;
120    ///
121    /// # async fn example() -> laravel::Result<()> {
122    /// let menu = Category::roots()
123    ///     .get()
124    ///     .await?
125    ///     .with_subtree_counts(Product::category_id)
126    ///     .await?;
127    ///
128    /// for entry in &menu {
129    ///     println!("{} ({})", entry.node.name, entry.count); // Phones (124)
130    /// }
131    /// # Ok(())
132    /// # }
133    /// ```
134    ///
135    /// # Errors
136    ///
137    /// Fails when the query fails.
138    fn with_subtree_counts<R, T>(
139        self,
140        foreign_key: Column<R, T>,
141    ) -> impl Future<Output = laravel::Result<Vec<WithCount<M>>>> + Send
142    where
143        R: Model,
144        T: Send + Sync + 'static;
145
146    /// [`with_subtree_counts`](Self::with_subtree_counts), counting only the rows that `filter`
147    /// matches, such as `Product::published.eq(true)`. The filter may use the other table's
148    /// typed columns: the query joins that table under its own name.
149    ///
150    /// # Errors
151    ///
152    /// Fails when the query fails.
153    fn with_subtree_counts_where<R, T>(
154        self,
155        foreign_key: Column<R, T>,
156        filter: impl IntoCondition + Send,
157    ) -> impl Future<Output = laravel::Result<Vec<WithCount<M>>>> + Send
158    where
159        R: Model,
160        T: Send + Sync + 'static;
161}
162
163impl<M: NestedSet> LoadRelatives<M> for Vec<M> {
164    async fn with_subtree_counts<R, T>(self, foreign_key: Column<R, T>) -> laravel::Result<Vec<WithCount<M>>>
165    where
166        R: Model,
167        T: Send + Sync + 'static,
168    {
169        self.with_subtree_counts_where(foreign_key, None::<Condition>).await
170    }
171
172    async fn with_subtree_counts_where<R, T>(
173        self,
174        foreign_key: Column<R, T>,
175        filter: impl IntoCondition + Send,
176    ) -> laravel::Result<Vec<WithCount<M>>>
177    where
178        R: Model,
179        T: Send + Sync + 'static,
180    {
181        let filter = db::all([filter]);
182        let counts = subtree_counts(&self, foreign_key, filter).await?;
183        Ok(self
184            .into_iter()
185            .map(|node| {
186                let count = counts.get(node.node_key()).copied().unwrap_or(0);
187                WithCount { node, count }
188            })
189            .collect())
190    }
191
192    async fn with_ancestors(self) -> laravel::Result<Vec<WithAncestors<M>>> {
193        let starts: Option<Vec<crate::chain::ChainStart>> =
194            self.iter().map(|node| crate::chain::chain_start(node, false)).collect();
195        let found = match starts {
196            // Integer keys: one recursive query up every node's parent chain.
197            Some(starts) => {
198                let starts = crate::chain::chain_keys(starts);
199                __query::<M>()
200                    .filter(crate::chain::chain::<M>(&starts))
201                    .order_by(M::lft_column().asc())
202                    .get()
203                    .await?
204            }
205            None => load(&self, M::where_ancestor_of).await?,
206        };
207        Ok(self
208            .into_iter()
209            .map(|node| {
210                let ancestors = found
211                    .iter()
212                    .filter(|&candidate| same_tree(candidate, &node) && node.is_descendant_of(candidate))
213                    .cloned()
214                    .collect();
215                WithAncestors { node, ancestors }
216            })
217            .collect())
218    }
219
220    async fn with_descendants(self) -> laravel::Result<Vec<TreeNode<M>>> {
221        let found = load(&self, M::where_descendant_of).await?;
222        Ok(self
223            .into_iter()
224            .map(|node| {
225                let below = found
226                    .iter()
227                    .filter(|&candidate| same_tree(candidate, &node) && candidate.is_descendant_of(&node));
228                let subtree: Vec<M> = std::iter::once(node.clone()).chain(below.cloned()).collect();
229                subtree
230                    .into_tree()
231                    .into_iter()
232                    .next()
233                    .expect("the node tops its own subtree")
234            })
235            .collect())
236    }
237}
238
239/// The rows that `relation` matches for any of `nodes`, in tree order.
240async fn load<M: NestedSet>(nodes: &[M], relation: fn(&M) -> db::Condition) -> laravel::Result<Vec<M>> {
241    let mut found = Vec::new();
242    for chunk in nodes.chunks(CHUNK) {
243        let rows = __query::<M>()
244            .filter(db::any(chunk.iter().map(relation)))
245            .order_by(M::lft_column().asc())
246            .get()
247            .await?;
248        found.extend(rows);
249    }
250    // Nodes of one chunk can share relatives with another's: keep each row once, in tree order.
251    let mut seen = HashSet::new();
252    found.retain(|node| seen.insert(node.node_key().clone()));
253    found.sort_by_key(NestedSet::lft);
254    Ok(found)
255}
256
257/// The count of rows of `R` below each of `nodes`, keyed by node.
258async fn subtree_counts<M: NestedSet, R: Model, T>(
259    nodes: &[M],
260    foreign_key: Column<R, T>,
261    filter: Condition,
262) -> laravel::Result<HashMap<M::Key, u64>> {
263    let Some(first) = nodes.first() else {
264        return Ok(HashMap::new());
265    };
266    let (table, key) = (M::META.table, M::META.key.name());
267    let (lft, rgt) = (M::lft_column().name(), M::rgt_column().name());
268    let node = |column: &str| col(format!("nested_node.{column}"));
269    let below = |column: &str| col(format!("nested_below.{column}"));
270    // The nodes below each listed node, itself included, in the same tree.
271    let mut subtree = below(lft).ge(node(lft)) & below(lft).le(node(rgt));
272    for name in first.scope().names() {
273        subtree &= below(name).eq(node(name));
274    }
275    let related = R::META.table;
276    let points_below = col(format!("{related}.{}", foreign_key.name())).eq(below(key));
277
278    let mut counts = HashMap::new();
279    for chunk in nodes.chunks(CHUNK) {
280        let keys: Vec<M::Key> = chunk.iter().map(|node| node.node_key().clone()).collect();
281        let mut query = db::table(format!("{table} as nested_node"));
282        if let Some(connection) = M::META.connection {
283            query = query.connection(connection);
284        }
285        let rows = query
286            .join(format!("{table} as nested_below"), subtree.clone())
287            .join(related, points_below.clone())
288            .filter(node(key).is_in(keys) & filter.clone())
289            .select((node(key).alias("node_key"), col("*").count().alias("total")))
290            .group_by([format!("nested_node.{key}")])
291            .get::<(M::Key, i64)>()
292            .await?;
293        counts.extend(
294            rows.into_iter()
295                .map(|(key, total)| (key, u64::try_from(total).unwrap_or(0))),
296        );
297    }
298    Ok(counts)
299}
300
301fn same_tree<M: NestedSet>(a: &M, b: &M) -> bool {
302    a.scope().lock_name() == b.scope().lock_name()
303}