Skip to main content

laravel_nestedset/
node.rs

1//! `NestedSet`: the trait a tree model implements.
2
3use std::future::Future;
4
5use laravel::db::{Builder, Condition, IntoExpr, col};
6use laravel::model::{__query, Column, CreateBuilder, Model};
7
8use crate::arrange::{self, Arrangement};
9use crate::chain;
10use crate::check::{self, TreeReport};
11use crate::ops::{self, NewPlace, Place};
12use crate::scope::Scope;
13use crate::tree::{IntoTree, NewNode, TreeNode};
14
15/// A model stored as a nested set: each row keeps the `lft` and `rgt` bounds of its subtree and
16/// the key of its parent.
17///
18/// ```no_run
19/// use laravel::model::{Column, model};
20/// use laravel_nestedset::NestedSet;
21///
22/// #[model]
23/// pub struct Category {
24///     pub id: i64,
25///     pub name: String,
26///     #[default]
27///     pub lft: i64,
28///     #[default]
29///     pub rgt: i64,
30///     pub parent_id: Option<i64>,
31/// }
32///
33/// impl NestedSet for Category {
34///     fn lft_column() -> Column<Self, i64> {
35///         Category::lft
36///     }
37///
38///     fn rgt_column() -> Column<Self, i64> {
39///         Category::rgt
40///     }
41///
42///     fn parent_column() -> Column<Self, Option<i64>> {
43///         Category::parent_id
44///     }
45/// }
46/// ```
47///
48/// Every write runs in a transaction that holds a lock on the node's tree, so concurrent writes
49/// to the same tree wait for each other instead of corrupting the bounds.
50pub trait NestedSet: Model {
51    /// The left bound column, `lft` by [`nested_set`](crate::NestedSetBlueprint::nested_set).
52    fn lft_column() -> Column<Self, i64>;
53
54    /// The right bound column, `rgt` by [`nested_set`](crate::NestedSetBlueprint::nested_set).
55    fn rgt_column() -> Column<Self, i64>;
56
57    /// The parent key column, `parent_id` by
58    /// [`nested_set`](crate::NestedSetBlueprint::nested_set). Roots hold `NULL`.
59    fn parent_column() -> Column<Self, Option<Self::Key>>;
60
61    /// An optional column that stores each node's depth: `0` for roots, `1` for their children,
62    /// and so on. When the model has one, every write keeps it current,
63    /// [`depth`](Self::depth) reads it without a query, and a query can filter by level:
64    /// `Category::query().filter(Category::depth.eq(1))`. Add it with
65    /// [`nested_set_depth`](crate::NestedSetBlueprint::nested_set_depth). `None` by default.
66    #[must_use]
67    fn depth_column() -> Option<Column<Self, i64>> {
68        None
69    }
70
71    /// The columns that separate trees in one table, such as a menu's items by `menu_id`. The
72    /// whole table by default.
73    ///
74    /// ```no_run
75    /// # use laravel::model::{Column, model};
76    /// # use laravel_nestedset::{NestedSet, Scope};
77    /// # #[model]
78    /// # pub struct MenuItem {
79    /// #     pub id: i64,
80    /// #     pub menu_id: i64,
81    /// #     pub title: String,
82    /// #     #[default]
83    /// #     pub lft: i64,
84    /// #     #[default]
85    /// #     pub rgt: i64,
86    /// #     pub parent_id: Option<i64>,
87    /// # }
88    /// impl NestedSet for MenuItem {
89    /// #     fn lft_column() -> Column<Self, i64> { MenuItem::lft }
90    /// #     fn rgt_column() -> Column<Self, i64> { MenuItem::rgt }
91    /// #     fn parent_column() -> Column<Self, Option<i64>> { MenuItem::parent_id }
92    ///     fn scope(&self) -> Scope<Self> {
93    ///         Scope::new().by(MenuItem::menu_id, &self.menu_id)
94    ///     }
95    /// }
96    /// ```
97    fn scope(&self) -> Scope<Self> {
98        Scope::new()
99    }
100
101    /// The node's left bound.
102    fn lft(&self) -> i64 {
103        *Self::lft_column().get(self)
104    }
105
106    /// The node's right bound.
107    fn rgt(&self) -> i64 {
108        *Self::rgt_column().get(self)
109    }
110
111    /// The node's parent key, `None` for a root.
112    fn parent_key(&self) -> Option<&Self::Key> {
113        Self::parent_column().get(self).as_ref()
114    }
115
116    /// The node's own key.
117    fn node_key(&self) -> &Self::Key {
118        Self::META.key.get(self)
119    }
120
121    /// Whether the node has no parent.
122    fn is_root(&self) -> bool {
123        self.parent_key().is_none()
124    }
125
126    /// Whether the node has no children.
127    fn is_leaf(&self) -> bool {
128        self.rgt() - self.lft() == 1
129    }
130
131    /// How many descendants the node has, read from its bounds without a query.
132    fn descendant_count(&self) -> i64 {
133        (self.rgt() - self.lft() - 1) / 2
134    }
135
136    /// Whether the node is inside `other`'s subtree. Compares the bounds the two models hold, so
137    /// both must be fresh and of the same tree.
138    fn is_descendant_of(&self, other: &Self) -> bool {
139        self.lft() > other.lft() && self.rgt() < other.rgt()
140    }
141
142    /// Whether `other` is inside this node's subtree.
143    fn is_ancestor_of(&self, other: &Self) -> bool {
144        other.is_descendant_of(self)
145    }
146
147    /// Every row of this node's tree.
148    fn tree_query(&self) -> Builder<Self> {
149        self.scope().apply(__query::<Self>())
150    }
151
152    /// The roots of every tree in the table, ordered by their left bound.
153    fn roots() -> Builder<Self> {
154        __query::<Self>()
155            .filter(Self::where_root())
156            .order_by(Self::lft_column().asc())
157    }
158
159    /// The node's direct children, in tree order.
160    fn children(&self) -> Builder<Self> {
161        __query::<Self>()
162            .filter(Self::where_child_of(self))
163            .order_by(Self::lft_column().asc())
164    }
165
166    /// Every node below this one, in tree order: one query for the whole subtree.
167    fn descendants(&self) -> Builder<Self> {
168        __query::<Self>()
169            .filter(Self::where_descendant_of(self))
170            .order_by(Self::lft_column().asc())
171    }
172
173    /// The node and every node below it, in tree order.
174    fn descendants_and_self(&self) -> Builder<Self> {
175        __query::<Self>()
176            .filter(Self::where_descendant_or_self(self))
177            .order_by(Self::lft_column().asc())
178    }
179
180    /// Every node above this one, from the root down: the breadcrumbs.
181    fn ancestors(&self) -> Builder<Self> {
182        __query::<Self>()
183            .filter(Self::where_ancestor_of(self))
184            .order_by(Self::lft_column().asc())
185    }
186
187    /// Every node above this one and the node itself, from the root down.
188    fn ancestors_and_self(&self) -> Builder<Self> {
189        __query::<Self>()
190            .filter(Self::where_ancestor_or_self(self))
191            .order_by(Self::lft_column().asc())
192    }
193
194    /// The nodes this node may move under: every node of its tree except itself and its
195    /// subtree, in tree order. Feed it to the parent `<select>` of an edit form, so nobody can pick
196    /// a node below the one they edit:
197    ///
198    /// ```no_run
199    /// # use laravel::model::{Column, model};
200    /// # use laravel_nestedset::NestedSet;
201    /// # #[model]
202    /// # pub struct Category {
203    /// #     pub id: i64,
204    /// #     pub name: String,
205    /// #     #[default]
206    /// #     pub lft: i64,
207    /// #     #[default]
208    /// #     pub rgt: i64,
209    /// #     pub parent_id: Option<i64>,
210    /// # }
211    /// # impl NestedSet for Category {
212    /// #     fn lft_column() -> Column<Self, i64> { Category::lft }
213    /// #     fn rgt_column() -> Column<Self, i64> { Category::rgt }
214    /// #     fn parent_column() -> Column<Self, Option<i64>> { Category::parent_id }
215    /// # }
216    /// use laravel_nestedset::IntoTree;
217    ///
218    /// # async fn example(category: Category) -> laravel::Result<()> {
219    /// let options: Vec<(String, i64)> = category
220    ///     .allowed_parents()
221    ///     .get()
222    ///     .await?
223    ///     .into_flat_tree_with_depth()
224    ///     .into_iter()
225    ///     .map(|(node, depth)| (format!("{}{}", "— ".repeat(depth), node.name), node.id))
226    ///     .collect();
227    /// # Ok(())
228    /// # }
229    /// ```
230    fn allowed_parents(&self) -> Builder<Self> {
231        self.tree_query()
232            .filter(!Self::where_descendant_or_self(self))
233            .order_by(Self::lft_column().asc())
234    }
235
236    /// The values of `column` from the root down to this node, joined by `separator`: a slug
237    /// path such as `shop/phones/android`, or breadcrumbs as text.
238    ///
239    /// # Errors
240    ///
241    /// Fails when the query fails.
242    fn path(
243        &self,
244        column: Column<Self, String>,
245        separator: &str,
246    ) -> impl Future<Output = laravel::Result<String>> + Send {
247        let values = self.ancestors_and_self().pluck(column);
248        let separator = separator.to_owned();
249        async move { Ok(values.await?.join(&separator)) }
250    }
251
252    /// The node at a slug path such as `shop/phones/android`: a root whose `column` is `shop`,
253    /// its child `phones`, and that one's child `android`. One query, for the nodes whose
254    /// `column` is one of the segments. `None` when no node is at the path. In a scoped table,
255    /// the first tree with a match wins; use [`find_by_path_below`](Self::find_by_path_below)
256    /// from a root to stay in one tree.
257    ///
258    /// # Errors
259    ///
260    /// Fails when the query fails.
261    fn find_by_path(
262        column: Column<Self, String>,
263        path: &str,
264    ) -> impl Future<Output = laravel::Result<Option<Self>>> + Send {
265        let segments = segments(path);
266        let query = __query::<Self>()
267            .filter(column.is_in(segments.clone()))
268            .order_by(Self::lft_column().asc());
269        async move { Ok(walk(&query.get().await?, column, &segments, None)) }
270    }
271
272    /// The node at a slug path below this one: `phones/android` from the `shop` node.
273    ///
274    /// # Errors
275    ///
276    /// Fails when the query fails.
277    fn find_by_path_below(
278        &self,
279        column: Column<Self, String>,
280        path: &str,
281    ) -> impl Future<Output = laravel::Result<Option<Self>>> + Send {
282        let segments = segments(path);
283        let query = __query::<Self>()
284            .filter(Self::where_descendant_of(self) & column.is_in(segments.clone()))
285            .order_by(Self::lft_column().asc());
286        let start = Some(self.node_key().clone());
287        async move { Ok(walk(&query.get().await?, column, &segments, start)) }
288    }
289
290    /// Matches the nodes below `node`, in its tree. Combine it with any other condition:
291    ///
292    /// ```no_run
293    /// # use laravel::model::{Column, model};
294    /// # use laravel_nestedset::NestedSet;
295    /// # #[model]
296    /// # pub struct Category {
297    /// #     pub id: i64,
298    /// #     pub name: String,
299    /// #     #[default]
300    /// #     pub lft: i64,
301    /// #     #[default]
302    /// #     pub rgt: i64,
303    /// #     pub parent_id: Option<i64>,
304    /// # }
305    /// # impl NestedSet for Category {
306    /// #     fn lft_column() -> Column<Self, i64> { Category::lft }
307    /// #     fn rgt_column() -> Column<Self, i64> { Category::rgt }
308    /// #     fn parent_column() -> Column<Self, Option<i64>> { Category::parent_id }
309    /// # }
310    /// # async fn example(phones: Category) -> laravel::Result<()> {
311    /// let pro_phones = Category::query()
312    ///     .filter(Category::where_descendant_of(&phones) & Category::name.contains("Pro"))
313    ///     .get()
314    ///     .await?;
315    /// # Ok(())
316    /// # }
317    /// ```
318    #[must_use]
319    fn where_descendant_of(node: &Self) -> Condition {
320        // Below a node, every left bound lies between the node's bounds: both ends on the same
321        // indexed column let the database read just the subtree's part of the index.
322        node.scope().condition() & Self::lft_column().gt(node.lft()) & Self::lft_column().lt(node.rgt())
323    }
324
325    /// Matches `node` and the nodes below it.
326    #[must_use]
327    fn where_descendant_or_self(node: &Self) -> Condition {
328        node.scope().condition() & Self::lft_column().between(node.lft(), node.rgt())
329    }
330
331    /// Matches the nodes above `node`.
332    #[must_use]
333    fn where_ancestor_of(node: &Self) -> Condition {
334        match chain::chain_start(node, false) {
335            Some(start) => chain::chain::<Self>(&chain::chain_keys([start])),
336            None => node.scope().condition() & Self::lft_column().lt(node.lft()) & Self::rgt_column().gt(node.rgt()),
337        }
338    }
339
340    /// Matches `node` and the nodes above it.
341    #[must_use]
342    fn where_ancestor_or_self(node: &Self) -> Condition {
343        match chain::chain_start(node, true) {
344            Some(start) => chain::chain::<Self>(&chain::chain_keys([start])),
345            None => node.scope().condition() & Self::lft_column().le(node.lft()) & Self::rgt_column().ge(node.rgt()),
346        }
347    }
348
349    /// Matches the direct children of `node`.
350    #[must_use]
351    fn where_child_of(node: &Self) -> Condition {
352        node.scope().condition() & Self::parent_column().eq(node.node_key().clone())
353    }
354
355    /// Matches the rows of another table that point at `node` or at any node below it: every
356    /// product of a category and its subcategories, in one query of the products.
357    ///
358    /// ```no_run
359    /// # use laravel::model::{Column, model};
360    /// # use laravel_nestedset::NestedSet;
361    /// # #[model]
362    /// # pub struct Category {
363    /// #     pub id: i64,
364    /// #     #[default]
365    /// #     pub lft: i64,
366    /// #     #[default]
367    /// #     pub rgt: i64,
368    /// #     pub parent_id: Option<i64>,
369    /// # }
370    /// # impl NestedSet for Category {
371    /// #     fn lft_column() -> Column<Self, i64> { Category::lft }
372    /// #     fn rgt_column() -> Column<Self, i64> { Category::rgt }
373    /// #     fn parent_column() -> Column<Self, Option<i64>> { Category::parent_id }
374    /// # }
375    /// # #[model]
376    /// # pub struct Product {
377    /// #     pub id: i64,
378    /// #     pub category_id: i64,
379    /// #     pub price: i64,
380    /// # }
381    /// # async fn example(phones: Category) -> laravel::Result<()> {
382    /// let cheap_phones = Product::query()
383    ///     .filter(Category::where_in_subtree(&phones, Product::category_id) & Product::price.lt(300))
384    ///     .get()
385    ///     .await?;
386    /// # Ok(())
387    /// # }
388    /// ```
389    #[must_use]
390    fn where_in_subtree<R, T>(node: &Self, foreign_key: Column<R, T>) -> Condition
391    where
392        T: Send + Sync + 'static,
393    {
394        let keys = laravel::db::table(Self::META.table)
395            .select([Self::META.key.name()])
396            .filter(Self::where_descendant_or_self(node));
397        foreign_key.is_in(keys)
398    }
399
400    /// Matches roots.
401    #[must_use]
402    fn where_root() -> Condition {
403        Self::parent_column().is_null()
404    }
405
406    /// Matches nodes with a parent.
407    #[must_use]
408    fn where_has_parent() -> Condition {
409        Self::parent_column().is_not_null()
410    }
411
412    /// Matches nodes without children.
413    #[must_use]
414    fn where_leaf() -> Condition {
415        let (lft, rgt) = (Self::lft_column().name(), Self::rgt_column().name());
416        col(rgt).eq(col(lft) + 1)
417    }
418
419    /// Matches nodes with children.
420    #[must_use]
421    fn where_has_children() -> Condition {
422        !Self::where_leaf()
423    }
424
425    /// The nodes above the node with `key`, from the root down, without loading the node first
426    /// yourself.
427    ///
428    /// ```no_run
429    /// # use laravel::model::{Column, model};
430    /// # use laravel_nestedset::NestedSet;
431    /// # #[model]
432    /// # pub struct Category {
433    /// #     pub id: i64,
434    /// #     pub name: String,
435    /// #     #[default]
436    /// #     pub lft: i64,
437    /// #     #[default]
438    /// #     pub rgt: i64,
439    /// #     pub parent_id: Option<i64>,
440    /// # }
441    /// # impl NestedSet for Category {
442    /// #     fn lft_column() -> Column<Self, i64> { Category::lft }
443    /// #     fn rgt_column() -> Column<Self, i64> { Category::rgt }
444    /// #     fn parent_column() -> Column<Self, Option<i64>> { Category::parent_id }
445    /// # }
446    /// # async fn example(id: i64) -> laravel::Result<()> {
447    /// let breadcrumbs = Category::ancestors_of(id).await?;
448    /// # Ok(())
449    /// # }
450    /// ```
451    ///
452    /// # Errors
453    ///
454    /// Fails with [`NestedSetError::NodeNotFound`](crate::NestedSetError) when there's no such
455    /// node, and when a query fails.
456    fn ancestors_of(key: Self::Key) -> impl Future<Output = laravel::Result<Vec<Self>>> + Send {
457        async move { ops::find::<Self>(&key).await?.ancestors().get().await }
458    }
459
460    /// The node with `key` and the nodes above it, from the root down.
461    ///
462    /// # Errors
463    ///
464    /// As [`ancestors_of`](Self::ancestors_of).
465    fn ancestors_and_self_of(key: Self::Key) -> impl Future<Output = laravel::Result<Vec<Self>>> + Send {
466        async move { ops::find::<Self>(&key).await?.ancestors_and_self().get().await }
467    }
468
469    /// The nodes below the node with `key`, in tree order.
470    ///
471    /// # Errors
472    ///
473    /// As [`ancestors_of`](Self::ancestors_of).
474    fn descendants_of(key: Self::Key) -> impl Future<Output = laravel::Result<Vec<Self>>> + Send {
475        async move { ops::find::<Self>(&key).await?.descendants().get().await }
476    }
477
478    /// The node with `key` and the nodes below it, in tree order.
479    ///
480    /// # Errors
481    ///
482    /// As [`ancestors_of`](Self::ancestors_of).
483    fn descendants_and_self_of(key: Self::Key) -> impl Future<Output = laravel::Result<Vec<Self>>> + Send {
484        async move { ops::find::<Self>(&key).await?.descendants_and_self().get().await }
485    }
486
487    /// The direct children of the node with `key`, in tree order.
488    ///
489    /// # Errors
490    ///
491    /// As [`ancestors_of`](Self::ancestors_of).
492    fn children_of(key: Self::Key) -> impl Future<Output = laravel::Result<Vec<Self>>> + Send {
493        async move { ops::find::<Self>(&key).await?.children().get().await }
494    }
495
496    /// The node with `key` and its whole subtree, nested: one query for the subtree.
497    ///
498    /// ```no_run
499    /// # use laravel::model::{Column, model};
500    /// # use laravel_nestedset::{NestedSet, Scope};
501    /// # #[model]
502    /// # pub struct MenuItem {
503    /// #     pub id: i64,
504    /// #     pub menu_id: i64,
505    /// #     pub title: String,
506    /// #     #[default]
507    /// #     pub lft: i64,
508    /// #     #[default]
509    /// #     pub rgt: i64,
510    /// #     pub parent_id: Option<i64>,
511    /// # }
512    /// impl NestedSet for MenuItem {
513    /// #     fn lft_column() -> Column<Self, i64> { MenuItem::lft }
514    /// #     fn rgt_column() -> Column<Self, i64> { MenuItem::rgt }
515    /// #     fn parent_column() -> Column<Self, Option<i64>> { MenuItem::parent_id }
516    ///     fn scope(&self) -> Scope<Self> {
517    ///         Scope::new().by(MenuItem::menu_id, &self.menu_id)
518    ///     }
519    /// }
520    /// # async fn example(header_id: i64) -> laravel::Result<()> {
521    /// let menu = MenuItem::subtree_of(header_id).await?; // a TreeNode with its children
522    /// # Ok(())
523    /// # }
524    /// ```
525    ///
526    /// # Errors
527    ///
528    /// As [`ancestors_of`](Self::ancestors_of).
529    fn subtree_of(key: Self::Key) -> impl Future<Output = laravel::Result<TreeNode<Self>>> + Send {
530        async move {
531            let node = ops::find::<Self>(&key).await?;
532            let nodes = node.descendants_and_self().get().await?;
533            Ok(nodes
534                .into_tree()
535                .into_iter()
536                .next()
537                .expect("the node is in its own subtree"))
538        }
539    }
540
541    /// The node's parent, `None` for a root.
542    ///
543    /// # Errors
544    ///
545    /// Fails when the query fails.
546    fn parent(&self) -> impl Future<Output = laravel::Result<Option<Self>>> + Send {
547        let query = self
548            .parent_key()
549            .map(|parent| self.tree_query().filter(Self::META.key.eq(parent.clone())));
550        async move {
551            match query {
552                Some(query) => query.first().await,
553                None => Ok(None),
554            }
555        }
556    }
557
558    /// The node's depth: `0` for a root, `1` for its children, and so on. Read from the
559    /// [`depth_column`](Self::depth_column) when the model has one, or one `count` query.
560    ///
561    /// # Errors
562    ///
563    /// Fails when the query fails.
564    fn depth(&self) -> impl Future<Output = laravel::Result<u64>> + Send {
565        let stored = Self::depth_column().map(|column| u64::try_from(*column.get(self)).unwrap_or(0));
566        let count = self.ancestors().count();
567        async move {
568            match stored {
569                Some(depth) => Ok(depth),
570                None => count.await,
571            }
572        }
573    }
574
575    /// The other nodes with the same parent, in tree order. For a root, the other roots of its
576    /// scope.
577    fn siblings(&self) -> Builder<Self> {
578        let parent = match self.parent_key() {
579            Some(parent) => Self::parent_column().eq(parent.clone()),
580            None => Self::parent_column().is_null(),
581        };
582        self.tree_query()
583            .filter(parent & Self::META.key.ne(self.node_key().clone()))
584            .order_by(Self::lft_column().asc())
585    }
586
587    /// The siblings after this node, nearest first.
588    fn next_siblings(&self) -> Builder<Self> {
589        self.siblings().filter(Self::lft_column().gt(self.lft()))
590    }
591
592    /// The siblings before this node, in tree order: the nearest is the last.
593    fn prev_siblings(&self) -> Builder<Self> {
594        self.siblings().filter(Self::lft_column().lt(self.lft()))
595    }
596
597    /// The sibling right after this node, if there is one.
598    ///
599    /// # Errors
600    ///
601    /// Fails when the query fails.
602    fn next_sibling(&self) -> impl Future<Output = laravel::Result<Option<Self>>> + Send {
603        self.next_siblings().first()
604    }
605
606    /// The sibling right before this node, if there is one.
607    ///
608    /// # Errors
609    ///
610    /// Fails when the query fails.
611    fn prev_sibling(&self) -> impl Future<Output = laravel::Result<Option<Self>>> + Send {
612        let parent = match self.parent_key() {
613            Some(parent) => Self::parent_column().eq(parent.clone()),
614            None => Self::parent_column().is_null(),
615        };
616        self.tree_query()
617            .filter(parent & Self::lft_column().lt(self.lft()))
618            .order_by(Self::lft_column().desc())
619            .first()
620    }
621
622    /// Whether `other` is this node's parent.
623    fn is_child_of(&self, other: &Self) -> bool {
624        self.parent_key() == Some(other.node_key())
625    }
626
627    /// Whether this node and `other` are different nodes with the same parent.
628    fn is_sibling_of(&self, other: &Self) -> bool {
629        self.parent_key() == other.parent_key() && self.node_key() != other.node_key()
630    }
631
632    /// Orders a query by the left bound: tree order, each node before its children. Use it as a
633    /// scope: `Category::query().scope(Category::default_order)`.
634    fn default_order(query: Builder<Self>) -> Builder<Self> {
635        query.order_by(Self::lft_column().asc())
636    }
637
638    /// Orders a query by the left bound, descending: tree order reversed.
639    fn reversed(query: Builder<Self>) -> Builder<Self> {
640        query.order_by(Self::lft_column().desc())
641    }
642
643    /// Every node without children, across the table. Filter it to a tree with
644    /// [`tree_query`](Self::tree_query)'s scope when the table has several.
645    fn leaves() -> Builder<Self> {
646        let (lft, rgt) = (Self::lft_column().name(), Self::rgt_column().name());
647        __query::<Self>().filter(col(rgt).eq(col(lft) + 1))
648    }
649
650    /// Creates a new root after the last tree of its scope.
651    ///
652    /// The new row's scope is only known once it's in, so this locks the roots of the whole table
653    /// first: new roots anywhere in the table take turns. In a table with many trees that get new
654    /// roots often, such as one tree per comment thread, use
655    /// [`create_root_in`](Self::create_root_in), which locks only the one tree.
656    ///
657    /// ```no_run
658    /// # use laravel::model::{Column, model};
659    /// # use laravel_nestedset::NestedSet;
660    /// # #[model]
661    /// # pub struct Category {
662    /// #     pub id: i64,
663    /// #     pub name: String,
664    /// #     #[default]
665    /// #     pub lft: i64,
666    /// #     #[default]
667    /// #     pub rgt: i64,
668    /// #     pub parent_id: Option<i64>,
669    /// # }
670    /// # impl NestedSet for Category {
671    /// #     fn lft_column() -> Column<Self, i64> { Category::lft }
672    /// #     fn rgt_column() -> Column<Self, i64> { Category::rgt }
673    /// #     fn parent_column() -> Column<Self, Option<i64>> { Category::parent_id }
674    /// # }
675    /// # async fn example() -> laravel::Result<()> {
676    /// let shop = Category::create_root(Category::create().name("Shop")).await?;
677    /// # Ok(())
678    /// # }
679    /// ```
680    ///
681    /// # Errors
682    ///
683    /// Fails when a query fails.
684    fn create_root(
685        create: impl Into<CreateBuilder<Self>> + Send,
686    ) -> impl Future<Output = laravel::Result<Self>> + Send {
687        ops::create_root(create.into())
688    }
689
690    /// Creates a new root in the tree of `scope`, locking only that tree: new roots of other
691    /// trees don't wait for it. The scope's values fill the create, and the root goes after the
692    /// tree's last one, in one insert.
693    ///
694    /// ```no_run
695    /// # use laravel::model::{Column, model};
696    /// # use laravel_nestedset::{NestedSet, Scope};
697    /// # #[model]
698    /// # pub struct Comment {
699    /// #     pub id: i64,
700    /// #     pub thread_id: i64,
701    /// #     pub body: String,
702    /// #     #[default]
703    /// #     pub lft: i64,
704    /// #     #[default]
705    /// #     pub rgt: i64,
706    /// #     pub parent_id: Option<i64>,
707    /// # }
708    /// # impl NestedSet for Comment {
709    /// #     fn lft_column() -> Column<Self, i64> { Comment::lft }
710    /// #     fn rgt_column() -> Column<Self, i64> { Comment::rgt }
711    /// #     fn parent_column() -> Column<Self, Option<i64>> { Comment::parent_id }
712    /// #     fn scope(&self) -> Scope<Self> { Scope::new().by(Comment::thread_id, &self.thread_id) }
713    /// # }
714    /// # async fn example(thread_id: i64) -> laravel::Result<()> {
715    /// let comment = Comment::create_root_in(
716    ///     Scope::new().by(Comment::thread_id, &thread_id),
717    ///     Comment::create().body("First!"),
718    /// )
719    /// .await?;
720    /// # Ok(())
721    /// # }
722    /// ```
723    ///
724    /// On PostgreSQL the lock is per tree. MySQL and MariaDB can't lock a tree that has no rows
725    /// yet, so there new roots still take turns across the table, as with `create_root`, but for
726    /// a shorter time and without deadlocks between new trees.
727    ///
728    /// # Errors
729    ///
730    /// Fails with [`NestedSetError::OutsideScope`](crate::NestedSetError) when `scope` isn't
731    /// built from the model's scope columns, so the new row would land outside it; nothing is
732    /// written then. Fails when a query fails.
733    fn create_root_in(
734        scope: Scope<Self>,
735        create: impl Into<CreateBuilder<Self>> + Send,
736    ) -> impl Future<Output = laravel::Result<Self>> + Send {
737        ops::create_root_in(scope, create.into())
738    }
739
740    /// Creates a new node as the last child of this one, and reloads this node. The child gets
741    /// this node's scope values.
742    ///
743    /// ```no_run
744    /// # use laravel::model::{Column, model};
745    /// # use laravel_nestedset::NestedSet;
746    /// # #[model]
747    /// # pub struct Category {
748    /// #     pub id: i64,
749    /// #     pub name: String,
750    /// #     #[default]
751    /// #     pub lft: i64,
752    /// #     #[default]
753    /// #     pub rgt: i64,
754    /// #     pub parent_id: Option<i64>,
755    /// # }
756    /// # impl NestedSet for Category {
757    /// #     fn lft_column() -> Column<Self, i64> { Category::lft }
758    /// #     fn rgt_column() -> Column<Self, i64> { Category::rgt }
759    /// #     fn parent_column() -> Column<Self, Option<i64>> { Category::parent_id }
760    /// # }
761    /// # async fn example(mut shop: Category) -> laravel::Result<()> {
762    /// let phones = shop.create_child(Category::create().name("Phones")).await?;
763    /// # Ok(())
764    /// # }
765    /// ```
766    ///
767    /// # Errors
768    ///
769    /// Fails when this node no longer exists or a query fails.
770    fn create_child(
771        &mut self,
772        create: impl Into<CreateBuilder<Self>> + Send,
773    ) -> impl Future<Output = laravel::Result<Self>> + Send
774    where
775        Option<Self::Key>: IntoExpr,
776    {
777        ops::create_near(self, create.into(), NewPlace::LastChild)
778    }
779
780    /// Creates a new node as the first child of this one, and reloads this node.
781    ///
782    /// # Errors
783    ///
784    /// Fails when this node no longer exists or a query fails.
785    fn create_first_child(
786        &mut self,
787        create: impl Into<CreateBuilder<Self>> + Send,
788    ) -> impl Future<Output = laravel::Result<Self>> + Send
789    where
790        Option<Self::Key>: IntoExpr,
791    {
792        ops::create_near(self, create.into(), NewPlace::FirstChild)
793    }
794
795    /// Creates a new node right before this one, with the same parent, and reloads this node.
796    ///
797    /// # Errors
798    ///
799    /// Fails when this node no longer exists or a query fails.
800    fn create_before(
801        &mut self,
802        create: impl Into<CreateBuilder<Self>> + Send,
803    ) -> impl Future<Output = laravel::Result<Self>> + Send
804    where
805        Option<Self::Key>: IntoExpr,
806    {
807        ops::create_near(self, create.into(), NewPlace::Before)
808    }
809
810    /// Creates a new node right after this one, with the same parent, and reloads this node.
811    ///
812    /// # Errors
813    ///
814    /// Fails when this node no longer exists or a query fails.
815    fn create_after(
816        &mut self,
817        create: impl Into<CreateBuilder<Self>> + Send,
818    ) -> impl Future<Output = laravel::Result<Self>> + Send
819    where
820        Option<Self::Key>: IntoExpr,
821    {
822        ops::create_near(self, create.into(), NewPlace::After)
823    }
824
825    /// Creates a root with all its children from nested [`NewNode`]s, and returns the root.
826    ///
827    /// # Errors
828    ///
829    /// Fails when a query fails. The nodes created before the failure stay.
830    fn create_tree(tree: NewNode<Self>) -> impl Future<Output = laravel::Result<Self>> + Send
831    where
832        Option<Self::Key>: IntoExpr,
833    {
834        async move {
835            let mut root = ops::create_root(tree.create).await?;
836            create_children(&mut root, tree.children).await?;
837            Ok(root)
838        }
839    }
840
841    /// Creates `tree` with all its children as the last child of this node, and returns its top
842    /// node.
843    ///
844    /// # Errors
845    ///
846    /// Fails when this node no longer exists or a query fails.
847    fn create_child_tree(&mut self, tree: NewNode<Self>) -> impl Future<Output = laravel::Result<Self>> + Send
848    where
849        Option<Self::Key>: IntoExpr,
850    {
851        async move {
852            let mut top = ops::create_near(self, tree.create, NewPlace::LastChild).await?;
853            create_children(&mut top, tree.children).await?;
854            *self = ops::reload_fresh(self).await?;
855            Ok(top)
856        }
857    }
858
859    /// Moves this node with its subtree to the end of its scope, as a root. Reloads this
860    /// node.
861    ///
862    /// # Errors
863    ///
864    /// Fails when this node no longer exists or a query fails.
865    fn make_root(&mut self) -> impl Future<Output = laravel::Result<()>> + Send
866    where
867        Option<Self::Key>: IntoExpr,
868    {
869        ops::move_node(self, None, Place::Root)
870    }
871
872    /// Moves this node with its subtree to be the last child of `parent`. Reloads
873    /// this node; reload `parent` before you read its bounds.
874    ///
875    /// # Errors
876    ///
877    /// Fails with [`NestedSetError::MoveIntoOwnSubtree`](crate::NestedSetError) when `parent`
878    /// is this node or below it, with [`NestedSetError::ScopeMismatch`](crate::NestedSetError)
879    /// when it's in another tree, and when a node no longer exists or a query fails.
880    fn append_to(&mut self, parent: &Self) -> impl Future<Output = laravel::Result<()>> + Send
881    where
882        Option<Self::Key>: IntoExpr,
883    {
884        ops::move_node(self, Some(parent), Place::LastChild)
885    }
886
887    /// Moves this node with its subtree to be the first child of `parent`.
888    ///
889    /// # Errors
890    ///
891    /// As [`append_to`](Self::append_to).
892    fn prepend_to(&mut self, parent: &Self) -> impl Future<Output = laravel::Result<()>> + Send
893    where
894        Option<Self::Key>: IntoExpr,
895    {
896        ops::move_node(self, Some(parent), Place::FirstChild)
897    }
898
899    /// Moves this node with its subtree right before `neighbor`, under `neighbor`'s parent.
900    ///
901    /// # Errors
902    ///
903    /// As [`append_to`](Self::append_to).
904    fn insert_before(&mut self, neighbor: &Self) -> impl Future<Output = laravel::Result<()>> + Send
905    where
906        Option<Self::Key>: IntoExpr,
907    {
908        ops::move_node(self, Some(neighbor), Place::Before)
909    }
910
911    /// Moves this node with its subtree right after `neighbor`, under `neighbor`'s parent.
912    ///
913    /// # Errors
914    ///
915    /// As [`append_to`](Self::append_to).
916    fn insert_after(&mut self, neighbor: &Self) -> impl Future<Output = laravel::Result<()>> + Send
917    where
918        Option<Self::Key>: IntoExpr,
919    {
920        ops::move_node(self, Some(neighbor), Place::After)
921    }
922
923    /// Copies this node with its whole subtree as the last child of `target`, and returns the
924    /// copy. Every column is copied except the key and the timestamps, as `replicate` does, and
925    /// the copies take `target`'s tree: copy the header menu into the footer menu, say. The
926    /// copies are inserted one by one, so model hooks and events run for each.
927    ///
928    /// # Errors
929    ///
930    /// Fails when this node or `target` no longer exists or a query fails; nothing is copied
931    /// then.
932    fn copy_to(&self, target: &Self) -> impl Future<Output = laravel::Result<Self>> + Send
933    where
934        Option<Self::Key>: IntoExpr,
935    {
936        ops::copy_subtree(self, Some(target))
937    }
938
939    /// Copies this node with its whole subtree as a new root after the last one of its tree.
940    ///
941    /// # Errors
942    ///
943    /// As [`copy_to`](Self::copy_to).
944    fn copy_as_root(&self) -> impl Future<Output = laravel::Result<Self>> + Send
945    where
946        Option<Self::Key>: IntoExpr,
947    {
948        ops::copy_subtree(self, None)
949    }
950
951    /// Moves this node `by` places up among its siblings. Returns whether it moved: `false`
952    /// when there aren't `by` siblings before it.
953    ///
954    /// # Errors
955    ///
956    /// Fails when a node no longer exists or a query fails.
957    fn up(&mut self, by: u64) -> impl Future<Output = laravel::Result<bool>> + Send
958    where
959        Option<Self::Key>: IntoExpr,
960    {
961        async move {
962            if by == 0 {
963                return Ok(false);
964            }
965            let parent = match self.parent_key() {
966                Some(parent) => Self::parent_column().eq(parent.clone()),
967                None => Self::parent_column().is_null(),
968            };
969            let neighbor = self
970                .tree_query()
971                .filter(parent & Self::lft_column().lt(self.lft()))
972                .order_by(Self::lft_column().desc())
973                .offset(by - 1)
974                .first()
975                .await?;
976            match neighbor {
977                Some(neighbor) => self.insert_before(&neighbor).await.map(|()| true),
978                None => Ok(false),
979            }
980        }
981    }
982
983    /// Moves this node `by` places down among its siblings. Returns whether it moved.
984    ///
985    /// # Errors
986    ///
987    /// Fails when a node no longer exists or a query fails.
988    fn down(&mut self, by: u64) -> impl Future<Output = laravel::Result<bool>> + Send
989    where
990        Option<Self::Key>: IntoExpr,
991    {
992        async move {
993            if by == 0 {
994                return Ok(false);
995            }
996            let neighbor = self.next_siblings().offset(by - 1).first().await?;
997            match neighbor {
998                Some(neighbor) => self.insert_after(&neighbor).await.map(|()| true),
999                None => Ok(false),
1000            }
1001        }
1002    }
1003
1004    /// Deletes this node and every node below it, and closes the gap in the bounds. Returns how
1005    /// many rows it deleted.
1006    ///
1007    /// Delete nodes only this way: deleting a row with the model's `delete` or a query leaves
1008    /// a gap in the bounds and orphans its children. The rows go with one query, so model hooks
1009    /// and events don't run for them.
1010    ///
1011    /// # Errors
1012    ///
1013    /// Fails when this node no longer exists or a query fails.
1014    fn delete_subtree(self) -> impl Future<Output = laravel::Result<u64>> + Send {
1015        async move { ops::delete_subtree(&self).await }
1016    }
1017
1018    /// Rearranges a tree the way `items` lists it: the listed nodes become roots, in the listed
1019    /// order, with the listed children below them. Made for saving a drag-and-drop tree editor:
1020    ///
1021    /// ```no_run
1022    /// # use laravel::model::{Column, model};
1023    /// # use laravel_nestedset::NestedSet;
1024    /// # #[model]
1025    /// # pub struct Category {
1026    /// #     pub id: i64,
1027    /// #     #[default]
1028    /// #     pub lft: i64,
1029    /// #     #[default]
1030    /// #     pub rgt: i64,
1031    /// #     pub parent_id: Option<i64>,
1032    /// # }
1033    /// # impl NestedSet for Category {
1034    /// #     fn lft_column() -> Column<Self, i64> { Category::lft }
1035    /// #     fn rgt_column() -> Column<Self, i64> { Category::rgt }
1036    /// #     fn parent_column() -> Column<Self, Option<i64>> { Category::parent_id }
1037    /// # }
1038    /// use laravel_nestedset::Arrangement;
1039    ///
1040    /// # async fn example(body: &str) -> laravel::Result<()> {
1041    /// // [{"id": 1, "children": [{"id": 3}, {"id": 2}]}, {"id": 4}]
1042    /// let items: Vec<Arrangement<i64>> = serde_json::from_str(body)?;
1043    /// Category::arrange(items).await?;
1044    /// # Ok(())
1045    /// # }
1046    /// ```
1047    ///
1048    /// Every listed node must be in one tree, the tree of the first one. Nodes of that tree the
1049    /// list leaves out keep their parent and come after the listed siblings. One transaction
1050    /// rebuilds the whole tree; returns how many rows changed.
1051    ///
1052    /// # Errors
1053    ///
1054    /// Fails with [`NestedSetError::NodeNotFound`](crate::NestedSetError) when a listed node
1055    /// isn't in the tree, with [`NestedSetError::DuplicateKey`](crate::NestedSetError) when one
1056    /// is listed twice, and when a query fails. Nothing changes then.
1057    fn arrange(items: Vec<Arrangement<Self::Key>>) -> impl Future<Output = laravel::Result<u64>> + Send
1058    where
1059        Option<Self::Key>: IntoExpr,
1060    {
1061        arrange::arrange::<Self>(None, items)
1062    }
1063
1064    /// Rearranges the nodes below this one the way `items` lists them, as
1065    /// [`arrange`](Self::arrange) does for roots, and reloads this node.
1066    ///
1067    /// # Errors
1068    ///
1069    /// As [`arrange`](Self::arrange), and with
1070    /// [`NestedSetError::MoveIntoOwnSubtree`](crate::NestedSetError) when the list holds this
1071    /// node or one above it.
1072    fn arrange_children(
1073        &mut self,
1074        items: Vec<Arrangement<Self::Key>>,
1075    ) -> impl Future<Output = laravel::Result<u64>> + Send
1076    where
1077        Option<Self::Key>: IntoExpr,
1078    {
1079        async move {
1080            let changed = arrange::arrange(Some(&*self), items).await?;
1081            *self = ops::reload_fresh(self).await?;
1082            Ok(changed)
1083        }
1084    }
1085
1086    /// Checks every tree in the table and names the broken nodes.
1087    ///
1088    /// # Errors
1089    ///
1090    /// Fails when the query fails.
1091    fn check_tree() -> impl Future<Output = laravel::Result<TreeReport<Self::Key>>> + Send {
1092        check::check_tree::<Self>()
1093    }
1094
1095    /// Rebuilds the bounds of every tree in the table from `parent_id`. Use it to
1096    /// repair a tree, or to fill `lft` and `rgt` on a table that only had `parent_id`.
1097    /// Siblings keep their order; a node whose parent is missing becomes a root. Returns how many
1098    /// rows it changed.
1099    ///
1100    /// # Errors
1101    ///
1102    /// Fails when a query fails; nothing changes then.
1103    fn fix_tree() -> impl Future<Output = laravel::Result<u64>> + Send
1104    where
1105        Option<Self::Key>: IntoExpr,
1106    {
1107        check::fix_tree::<Self>()
1108    }
1109}
1110
1111/// Creates `children`, each with its own children, below `parent`, depth first.
1112async fn create_children<M: NestedSet>(parent: &mut M, children: Vec<NewNode<M>>) -> laravel::Result<()>
1113where
1114    Option<M::Key>: IntoExpr,
1115{
1116    let mut stack: Vec<(M, std::vec::IntoIter<NewNode<M>>)> = vec![(parent.clone(), children.into_iter())];
1117    while let Some((top, pending)) = stack.last_mut() {
1118        let Some(next) = pending.next() else {
1119            stack.pop();
1120            continue;
1121        };
1122        let child = ops::create_near(top, next.create, NewPlace::LastChild).await?;
1123        stack.push((child, next.children.into_iter()));
1124    }
1125    *parent = ops::reload_fresh(parent).await?;
1126    Ok(())
1127}
1128
1129/// The non-empty segments of a slash-separated path.
1130fn segments(path: &str) -> Vec<String> {
1131    path.split('/')
1132        .filter(|segment| !segment.is_empty())
1133        .map(str::to_owned)
1134        .collect()
1135}
1136
1137/// Follows `segments` down from the children of `start` (the roots when `None`) through
1138/// `candidates`, which are in tree order.
1139fn walk<M: NestedSet>(
1140    candidates: &[M],
1141    column: Column<M, String>,
1142    segments: &[String],
1143    start: Option<M::Key>,
1144) -> Option<M> {
1145    if segments.is_empty() {
1146        return None;
1147    }
1148    let mut parent = start;
1149    let mut found = None;
1150    for segment in segments {
1151        let next = candidates
1152            .iter()
1153            .find(|node| column.get(node) == segment && node.parent_key() == parent.as_ref())?;
1154        parent = Some(next.node_key().clone());
1155        found = Some(next);
1156    }
1157    found.cloned()
1158}