laravel-nestedset 0.1.0

Nested set trees for Laravel Rust models: fast subtree and ancestor queries, safe under concurrent writes.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
//! `NestedSet`: the trait a tree model implements.

use std::future::Future;

use laravel::db::{Builder, IntoExpr, col};
use laravel::model::{__query, Column, CreateBuilder, Model};

use crate::check::{self, TreeReport};
use crate::ops::{self, NewPlace, Place};
use crate::scope::Scope;
use crate::tree::NewNode;

/// A model stored as a nested set: each row keeps the `lft` and `rgt` bounds of its subtree and
/// the key of its parent.
///
/// ```ignore
/// use laravel::model::model;
/// use laravel_nestedset::NestedSet;
///
/// #[model]
/// pub struct Category {
///     pub id: i64,
///     pub name: String,
///     #[default]
///     pub lft: i64,
///     #[default]
///     pub rgt: i64,
///     pub parent_id: Option<i64>,
/// }
///
/// impl NestedSet for Category {
///     fn lft_column() -> Column<Self, i64> {
///         Category::lft
///     }
///
///     fn rgt_column() -> Column<Self, i64> {
///         Category::rgt
///     }
///
///     fn parent_column() -> Column<Self, Option<i64>> {
///         Category::parent_id
///     }
/// }
/// ```
///
/// Every write runs in a transaction that holds a lock on the node's tree, so concurrent writes
/// to the same tree wait for each other instead of corrupting the bounds.
pub trait NestedSet: Model {
    /// The left bound column, `lft` by [`nested_set`](crate::NestedSetBlueprint::nested_set).
    fn lft_column() -> Column<Self, i64>;

    /// The right bound column, `rgt` by [`nested_set`](crate::NestedSetBlueprint::nested_set).
    fn rgt_column() -> Column<Self, i64>;

    /// The parent key column, `parent_id` by
    /// [`nested_set`](crate::NestedSetBlueprint::nested_set). Roots hold `NULL`.
    fn parent_column() -> Column<Self, Option<Self::Key>>;

    /// The columns that separate trees in one table, such as a menu's items by `menu_id`. The
    /// whole table by default.
    ///
    /// ```ignore
    /// fn scope(&self) -> Scope<Self> {
    ///     Scope::new().by(MenuItem::menu_id, &self.menu_id)
    /// }
    /// ```
    fn scope(&self) -> Scope<Self> {
        Scope::new()
    }

    /// The node's left bound.
    fn lft(&self) -> i64 {
        *Self::lft_column().get(self)
    }

    /// The node's right bound.
    fn rgt(&self) -> i64 {
        *Self::rgt_column().get(self)
    }

    /// The node's parent key, `None` for a root.
    fn parent_key(&self) -> Option<&Self::Key> {
        Self::parent_column().get(self).as_ref()
    }

    /// The node's own key.
    fn node_key(&self) -> &Self::Key {
        Self::META.key.get(self)
    }

    /// Whether the node has no parent.
    fn is_root(&self) -> bool {
        self.parent_key().is_none()
    }

    /// Whether the node has no children.
    fn is_leaf(&self) -> bool {
        self.rgt() - self.lft() == 1
    }

    /// How many descendants the node has, read from its bounds without a query.
    fn descendant_count(&self) -> i64 {
        (self.rgt() - self.lft() - 1) / 2
    }

    /// Whether the node is inside `other`'s subtree. Compares the bounds the two models hold, so
    /// both must be fresh and of the same tree.
    fn is_descendant_of(&self, other: &Self) -> bool {
        self.lft() > other.lft() && self.rgt() < other.rgt()
    }

    /// Whether `other` is inside this node's subtree.
    fn is_ancestor_of(&self, other: &Self) -> bool {
        other.is_descendant_of(self)
    }

    /// Every row of this node's tree.
    fn tree_query(&self) -> Builder<Self> {
        self.scope().apply(__query::<Self>())
    }

    /// The roots of every tree in the table, ordered by their left bound.
    fn roots() -> Builder<Self> {
        __query::<Self>()
            .filter(Self::parent_column().is_null())
            .order_by(Self::lft_column().asc())
    }

    /// The node's direct children, in tree order.
    fn children(&self) -> Builder<Self> {
        self.tree_query()
            .filter(Self::parent_column().eq(self.node_key().clone()))
            .order_by(Self::lft_column().asc())
    }

    /// Every node below this one, in tree order: one query for the whole subtree.
    fn descendants(&self) -> Builder<Self> {
        self.tree_query()
            .filter(Self::lft_column().gt(self.lft()) & Self::rgt_column().lt(self.rgt()))
            .order_by(Self::lft_column().asc())
    }

    /// The node and every node below it, in tree order.
    fn descendants_and_self(&self) -> Builder<Self> {
        self.tree_query()
            .filter(Self::lft_column().ge(self.lft()) & Self::rgt_column().le(self.rgt()))
            .order_by(Self::lft_column().asc())
    }

    /// Every node above this one, from the root down.
    fn ancestors(&self) -> Builder<Self> {
        self.tree_query()
            .filter(Self::lft_column().lt(self.lft()) & Self::rgt_column().gt(self.rgt()))
            .order_by(Self::lft_column().asc())
    }

    /// Every node above this one and the node itself, from the root down.
    fn ancestors_and_self(&self) -> Builder<Self> {
        self.tree_query()
            .filter(Self::lft_column().le(self.lft()) & Self::rgt_column().ge(self.rgt()))
            .order_by(Self::lft_column().asc())
    }

    /// The node's parent, `None` for a root.
    ///
    /// # Errors
    ///
    /// Fails when the query fails.
    fn parent(&self) -> impl Future<Output = laravel::Result<Option<Self>>> + Send {
        let query = self
            .parent_key()
            .map(|parent| self.tree_query().filter(Self::META.key.eq(parent.clone())));
        async move {
            match query {
                Some(query) => query.first().await,
                None => Ok(None),
            }
        }
    }

    /// The node's depth: `0` for a root, `1` for its children, and so on. One `count` query.
    ///
    /// # Errors
    ///
    /// Fails when the query fails.
    fn depth(&self) -> impl Future<Output = laravel::Result<u64>> + Send {
        self.ancestors().count()
    }

    /// The other nodes with the same parent, in tree order. For a root, the other roots of its
    /// scope.
    fn siblings(&self) -> Builder<Self> {
        let parent = match self.parent_key() {
            Some(parent) => Self::parent_column().eq(parent.clone()),
            None => Self::parent_column().is_null(),
        };
        self.tree_query()
            .filter(parent & Self::META.key.ne(self.node_key().clone()))
            .order_by(Self::lft_column().asc())
    }

    /// The siblings after this node, nearest first.
    fn next_siblings(&self) -> Builder<Self> {
        self.siblings().filter(Self::lft_column().gt(self.lft()))
    }

    /// The siblings before this node, in tree order: the nearest is the last.
    fn prev_siblings(&self) -> Builder<Self> {
        self.siblings().filter(Self::lft_column().lt(self.lft()))
    }

    /// The sibling right after this node, if there is one.
    ///
    /// # Errors
    ///
    /// Fails when the query fails.
    fn next_sibling(&self) -> impl Future<Output = laravel::Result<Option<Self>>> + Send {
        self.next_siblings().first()
    }

    /// The sibling right before this node, if there is one.
    ///
    /// # Errors
    ///
    /// Fails when the query fails.
    fn prev_sibling(&self) -> impl Future<Output = laravel::Result<Option<Self>>> + Send {
        let parent = match self.parent_key() {
            Some(parent) => Self::parent_column().eq(parent.clone()),
            None => Self::parent_column().is_null(),
        };
        self.tree_query()
            .filter(parent & Self::lft_column().lt(self.lft()))
            .order_by(Self::lft_column().desc())
            .first()
    }

    /// Whether `other` is this node's parent.
    fn is_child_of(&self, other: &Self) -> bool {
        self.parent_key() == Some(other.node_key())
    }

    /// Whether this node and `other` are different nodes with the same parent.
    fn is_sibling_of(&self, other: &Self) -> bool {
        self.parent_key() == other.parent_key() && self.node_key() != other.node_key()
    }

    /// Orders a query by the left bound: tree order, each node before its children. Use it as a
    /// scope: `Category::query().scope(Category::default_order)`.
    fn default_order(query: Builder<Self>) -> Builder<Self> {
        query.order_by(Self::lft_column().asc())
    }

    /// Orders a query by the left bound, descending: tree order reversed.
    fn reversed(query: Builder<Self>) -> Builder<Self> {
        query.order_by(Self::lft_column().desc())
    }

    /// Every node without children, across the table. Filter it to a tree with
    /// [`tree_query`](Self::tree_query)'s scope when the table has several.
    fn leaves() -> Builder<Self> {
        let (lft, rgt) = (Self::lft_column().name(), Self::rgt_column().name());
        __query::<Self>().filter(col(rgt).eq(col(lft) + 1))
    }

    /// Creates a new root after the last tree of its scope.
    ///
    /// ```ignore
    /// let shop = Category::create_root(Category::create().name("Shop")).await?;
    /// ```
    ///
    /// # Errors
    ///
    /// Fails when a query fails.
    fn create_root(
        create: impl Into<CreateBuilder<Self>> + Send,
    ) -> impl Future<Output = laravel::Result<Self>> + Send {
        ops::create_root(create.into())
    }

    /// Creates a new node as the last child of this one, and reloads this node. The child gets
    /// this node's scope values.
    ///
    /// ```ignore
    /// let phones = shop.create_child(Category::create().name("Phones")).await?;
    /// ```
    ///
    /// # Errors
    ///
    /// Fails when this node no longer exists or a query fails.
    fn create_child(
        &mut self,
        create: impl Into<CreateBuilder<Self>> + Send,
    ) -> impl Future<Output = laravel::Result<Self>> + Send
    where
        Option<Self::Key>: IntoExpr,
    {
        ops::create_near(self, create.into(), NewPlace::LastChild)
    }

    /// Creates a new node as the first child of this one, and reloads this node.
    ///
    /// # Errors
    ///
    /// Fails when this node no longer exists or a query fails.
    fn create_first_child(
        &mut self,
        create: impl Into<CreateBuilder<Self>> + Send,
    ) -> impl Future<Output = laravel::Result<Self>> + Send
    where
        Option<Self::Key>: IntoExpr,
    {
        ops::create_near(self, create.into(), NewPlace::FirstChild)
    }

    /// Creates a new node right before this one, with the same parent, and reloads this node.
    ///
    /// # Errors
    ///
    /// Fails when this node no longer exists or a query fails.
    fn create_before(
        &mut self,
        create: impl Into<CreateBuilder<Self>> + Send,
    ) -> impl Future<Output = laravel::Result<Self>> + Send
    where
        Option<Self::Key>: IntoExpr,
    {
        ops::create_near(self, create.into(), NewPlace::Before)
    }

    /// Creates a new node right after this one, with the same parent, and reloads this node.
    ///
    /// # Errors
    ///
    /// Fails when this node no longer exists or a query fails.
    fn create_after(
        &mut self,
        create: impl Into<CreateBuilder<Self>> + Send,
    ) -> impl Future<Output = laravel::Result<Self>> + Send
    where
        Option<Self::Key>: IntoExpr,
    {
        ops::create_near(self, create.into(), NewPlace::After)
    }

    /// Creates a root with all its children from nested [`NewNode`]s, and returns the root.
    ///
    /// # Errors
    ///
    /// Fails when a query fails. The nodes created before the failure stay.
    fn create_tree(tree: NewNode<Self>) -> impl Future<Output = laravel::Result<Self>> + Send
    where
        Option<Self::Key>: IntoExpr,
    {
        async move {
            let mut root = ops::create_root(tree.create).await?;
            create_children(&mut root, tree.children).await?;
            Ok(root)
        }
    }

    /// Creates `tree` with all its children as the last child of this node, and returns its top
    /// node.
    ///
    /// # Errors
    ///
    /// Fails when this node no longer exists or a query fails.
    fn create_child_tree(&mut self, tree: NewNode<Self>) -> impl Future<Output = laravel::Result<Self>> + Send
    where
        Option<Self::Key>: IntoExpr,
    {
        async move {
            let mut top = ops::create_near(self, tree.create, NewPlace::LastChild).await?;
            create_children(&mut top, tree.children).await?;
            *self = ops::reload_fresh(self).await?;
            Ok(top)
        }
    }

    /// Moves this node with its subtree to the end of its scope, as a root. Reloads this
    /// node.
    ///
    /// # Errors
    ///
    /// Fails when this node no longer exists or a query fails.
    fn make_root(&mut self) -> impl Future<Output = laravel::Result<()>> + Send
    where
        Option<Self::Key>: IntoExpr,
    {
        ops::move_node(self, None, Place::Root)
    }

    /// Moves this node with its subtree to be the last child of `parent`. Reloads
    /// this node; reload `parent` before you read its bounds.
    ///
    /// # Errors
    ///
    /// Fails with [`NestedSetError::MoveIntoOwnSubtree`](crate::NestedSetError) when `parent`
    /// is this node or below it, with [`NestedSetError::ScopeMismatch`](crate::NestedSetError)
    /// when it's in another tree, and when a node no longer exists or a query fails.
    fn append_to(&mut self, parent: &Self) -> impl Future<Output = laravel::Result<()>> + Send
    where
        Option<Self::Key>: IntoExpr,
    {
        ops::move_node(self, Some(parent), Place::LastChild)
    }

    /// Moves this node with its subtree to be the first child of `parent`.
    ///
    /// # Errors
    ///
    /// As [`append_to`](Self::append_to).
    fn prepend_to(&mut self, parent: &Self) -> impl Future<Output = laravel::Result<()>> + Send
    where
        Option<Self::Key>: IntoExpr,
    {
        ops::move_node(self, Some(parent), Place::FirstChild)
    }

    /// Moves this node with its subtree right before `neighbor`, under `neighbor`'s parent.
    ///
    /// # Errors
    ///
    /// As [`append_to`](Self::append_to).
    fn insert_before(&mut self, neighbor: &Self) -> impl Future<Output = laravel::Result<()>> + Send
    where
        Option<Self::Key>: IntoExpr,
    {
        ops::move_node(self, Some(neighbor), Place::Before)
    }

    /// Moves this node with its subtree right after `neighbor`, under `neighbor`'s parent.
    ///
    /// # Errors
    ///
    /// As [`append_to`](Self::append_to).
    fn insert_after(&mut self, neighbor: &Self) -> impl Future<Output = laravel::Result<()>> + Send
    where
        Option<Self::Key>: IntoExpr,
    {
        ops::move_node(self, Some(neighbor), Place::After)
    }

    /// Moves this node `by` places up among its siblings. Returns whether it moved: `false`
    /// when there aren't `by` siblings before it.
    ///
    /// # Errors
    ///
    /// Fails when a node no longer exists or a query fails.
    fn up(&mut self, by: u64) -> impl Future<Output = laravel::Result<bool>> + Send
    where
        Option<Self::Key>: IntoExpr,
    {
        async move {
            if by == 0 {
                return Ok(false);
            }
            let parent = match self.parent_key() {
                Some(parent) => Self::parent_column().eq(parent.clone()),
                None => Self::parent_column().is_null(),
            };
            let neighbor = self
                .tree_query()
                .filter(parent & Self::lft_column().lt(self.lft()))
                .order_by(Self::lft_column().desc())
                .offset(by - 1)
                .first()
                .await?;
            match neighbor {
                Some(neighbor) => self.insert_before(&neighbor).await.map(|()| true),
                None => Ok(false),
            }
        }
    }

    /// Moves this node `by` places down among its siblings. Returns whether it moved.
    ///
    /// # Errors
    ///
    /// Fails when a node no longer exists or a query fails.
    fn down(&mut self, by: u64) -> impl Future<Output = laravel::Result<bool>> + Send
    where
        Option<Self::Key>: IntoExpr,
    {
        async move {
            if by == 0 {
                return Ok(false);
            }
            let neighbor = self.next_siblings().offset(by - 1).first().await?;
            match neighbor {
                Some(neighbor) => self.insert_after(&neighbor).await.map(|()| true),
                None => Ok(false),
            }
        }
    }

    /// Deletes this node and every node below it, and closes the gap in the bounds. Returns how
    /// many rows it deleted.
    ///
    /// Delete nodes only this way: deleting a row with the model's `delete` or a query leaves
    /// a gap in the bounds and orphans its children. The rows go with one query, so model hooks
    /// and events don't run for them.
    ///
    /// # Errors
    ///
    /// Fails when this node no longer exists or a query fails.
    fn delete_subtree(self) -> impl Future<Output = laravel::Result<u64>> + Send {
        async move { ops::delete_subtree(&self).await }
    }

    /// Checks every tree in the table and names the broken nodes.
    ///
    /// # Errors
    ///
    /// Fails when the query fails.
    fn check_tree() -> impl Future<Output = laravel::Result<TreeReport<Self::Key>>> + Send {
        check::check_tree::<Self>()
    }

    /// Rebuilds the bounds of every tree in the table from `parent_id`. Use it to
    /// repair a tree, or to fill `lft` and `rgt` on a table that only had `parent_id`.
    /// Siblings keep their order; a node whose parent is missing becomes a root. Returns how many
    /// rows it changed.
    ///
    /// # Errors
    ///
    /// Fails when a query fails; nothing changes then.
    fn fix_tree() -> impl Future<Output = laravel::Result<u64>> + Send
    where
        Option<Self::Key>: IntoExpr,
    {
        check::fix_tree::<Self>()
    }
}

/// Creates `children`, each with its own children, below `parent`, depth first.
async fn create_children<M: NestedSet>(parent: &mut M, children: Vec<NewNode<M>>) -> laravel::Result<()>
where
    Option<M::Key>: IntoExpr,
{
    let mut stack: Vec<(M, std::vec::IntoIter<NewNode<M>>)> = vec![(parent.clone(), children.into_iter())];
    while let Some((top, pending)) = stack.last_mut() {
        let Some(next) = pending.next() else {
            stack.pop();
            continue;
        };
        let child = ops::create_near(top, next.create, NewPlace::LastChild).await?;
        stack.push((child, next.children.into_iter()));
    }
    *parent = ops::reload_fresh(parent).await?;
    Ok(())
}