laravel-nestedset 0.2.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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
//! `NestedSet`: the trait a tree model implements.

use std::future::Future;

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

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

/// A model stored as a nested set: each row keeps the `lft` and `rgt` bounds of its subtree and
/// the key of its parent.
///
/// ```no_run
/// use laravel::model::{Column, 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>>;

    /// An optional column that stores each node's depth: `0` for roots, `1` for their children,
    /// and so on. When the model has one, every write keeps it current,
    /// [`depth`](Self::depth) reads it without a query, and a query can filter by level:
    /// `Category::query().filter(Category::depth.eq(1))`. Add it with
    /// [`nested_set_depth`](crate::NestedSetBlueprint::nested_set_depth). `None` by default.
    #[must_use]
    fn depth_column() -> Option<Column<Self, i64>> {
        None
    }

    /// The columns that separate trees in one table, such as a menu's items by `menu_id`. The
    /// whole table by default.
    ///
    /// ```no_run
    /// # use laravel::model::{Column, model};
    /// # use laravel_nestedset::{NestedSet, Scope};
    /// # #[model]
    /// # pub struct MenuItem {
    /// #     pub id: i64,
    /// #     pub menu_id: i64,
    /// #     pub title: String,
    /// #     #[default]
    /// #     pub lft: i64,
    /// #     #[default]
    /// #     pub rgt: i64,
    /// #     pub parent_id: Option<i64>,
    /// # }
    /// impl NestedSet for MenuItem {
    /// #     fn lft_column() -> Column<Self, i64> { MenuItem::lft }
    /// #     fn rgt_column() -> Column<Self, i64> { MenuItem::rgt }
    /// #     fn parent_column() -> Column<Self, Option<i64>> { MenuItem::parent_id }
    ///     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::where_root())
            .order_by(Self::lft_column().asc())
    }

    /// The node's direct children, in tree order.
    fn children(&self) -> Builder<Self> {
        __query::<Self>()
            .filter(Self::where_child_of(self))
            .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> {
        __query::<Self>()
            .filter(Self::where_descendant_of(self))
            .order_by(Self::lft_column().asc())
    }

    /// The node and every node below it, in tree order.
    fn descendants_and_self(&self) -> Builder<Self> {
        __query::<Self>()
            .filter(Self::where_descendant_or_self(self))
            .order_by(Self::lft_column().asc())
    }

    /// Every node above this one, from the root down: the breadcrumbs.
    fn ancestors(&self) -> Builder<Self> {
        __query::<Self>()
            .filter(Self::where_ancestor_of(self))
            .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> {
        __query::<Self>()
            .filter(Self::where_ancestor_or_self(self))
            .order_by(Self::lft_column().asc())
    }

    /// Matches the nodes below `node`, in its tree. Combine it with any other condition:
    ///
    /// ```no_run
    /// # use laravel::model::{Column, 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 }
    /// # }
    /// # async fn example(phones: Category) -> laravel::Result<()> {
    /// let pro_phones = Category::query()
    ///     .filter(Category::where_descendant_of(&phones) & Category::name.contains("Pro"))
    ///     .get()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    fn where_descendant_of(node: &Self) -> Condition {
        node.scope().condition() & Self::lft_column().gt(node.lft()) & Self::rgt_column().lt(node.rgt())
    }

    /// Matches `node` and the nodes below it.
    #[must_use]
    fn where_descendant_or_self(node: &Self) -> Condition {
        node.scope().condition() & Self::lft_column().ge(node.lft()) & Self::rgt_column().le(node.rgt())
    }

    /// Matches the nodes above `node`.
    #[must_use]
    fn where_ancestor_of(node: &Self) -> Condition {
        node.scope().condition() & Self::lft_column().lt(node.lft()) & Self::rgt_column().gt(node.rgt())
    }

    /// Matches `node` and the nodes above it.
    #[must_use]
    fn where_ancestor_or_self(node: &Self) -> Condition {
        node.scope().condition() & Self::lft_column().le(node.lft()) & Self::rgt_column().ge(node.rgt())
    }

    /// Matches the direct children of `node`.
    #[must_use]
    fn where_child_of(node: &Self) -> Condition {
        node.scope().condition() & Self::parent_column().eq(node.node_key().clone())
    }

    /// Matches roots.
    #[must_use]
    fn where_root() -> Condition {
        Self::parent_column().is_null()
    }

    /// Matches nodes with a parent.
    #[must_use]
    fn where_has_parent() -> Condition {
        Self::parent_column().is_not_null()
    }

    /// Matches nodes without children.
    #[must_use]
    fn where_leaf() -> Condition {
        let (lft, rgt) = (Self::lft_column().name(), Self::rgt_column().name());
        col(rgt).eq(col(lft) + 1)
    }

    /// Matches nodes with children.
    #[must_use]
    fn where_has_children() -> Condition {
        !Self::where_leaf()
    }

    /// The nodes above the node with `key`, from the root down, without loading the node first
    /// yourself.
    ///
    /// ```no_run
    /// # use laravel::model::{Column, 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 }
    /// # }
    /// # async fn example(id: i64) -> laravel::Result<()> {
    /// let breadcrumbs = Category::ancestors_of(id).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Fails with [`NestedSetError::NodeNotFound`](crate::NestedSetError) when there's no such
    /// node, and when a query fails.
    fn ancestors_of(key: Self::Key) -> impl Future<Output = laravel::Result<Vec<Self>>> + Send {
        async move { ops::find::<Self>(&key).await?.ancestors().get().await }
    }

    /// The node with `key` and the nodes above it, from the root down.
    ///
    /// # Errors
    ///
    /// As [`ancestors_of`](Self::ancestors_of).
    fn ancestors_and_self_of(key: Self::Key) -> impl Future<Output = laravel::Result<Vec<Self>>> + Send {
        async move { ops::find::<Self>(&key).await?.ancestors_and_self().get().await }
    }

    /// The nodes below the node with `key`, in tree order.
    ///
    /// # Errors
    ///
    /// As [`ancestors_of`](Self::ancestors_of).
    fn descendants_of(key: Self::Key) -> impl Future<Output = laravel::Result<Vec<Self>>> + Send {
        async move { ops::find::<Self>(&key).await?.descendants().get().await }
    }

    /// The node with `key` and the nodes below it, in tree order.
    ///
    /// # Errors
    ///
    /// As [`ancestors_of`](Self::ancestors_of).
    fn descendants_and_self_of(key: Self::Key) -> impl Future<Output = laravel::Result<Vec<Self>>> + Send {
        async move { ops::find::<Self>(&key).await?.descendants_and_self().get().await }
    }

    /// The direct children of the node with `key`, in tree order.
    ///
    /// # Errors
    ///
    /// As [`ancestors_of`](Self::ancestors_of).
    fn children_of(key: Self::Key) -> impl Future<Output = laravel::Result<Vec<Self>>> + Send {
        async move { ops::find::<Self>(&key).await?.children().get().await }
    }

    /// The node with `key` and its whole subtree, nested: one query for the subtree.
    ///
    /// ```no_run
    /// # use laravel::model::{Column, model};
    /// # use laravel_nestedset::{NestedSet, Scope};
    /// # #[model]
    /// # pub struct MenuItem {
    /// #     pub id: i64,
    /// #     pub menu_id: i64,
    /// #     pub title: String,
    /// #     #[default]
    /// #     pub lft: i64,
    /// #     #[default]
    /// #     pub rgt: i64,
    /// #     pub parent_id: Option<i64>,
    /// # }
    /// impl NestedSet for MenuItem {
    /// #     fn lft_column() -> Column<Self, i64> { MenuItem::lft }
    /// #     fn rgt_column() -> Column<Self, i64> { MenuItem::rgt }
    /// #     fn parent_column() -> Column<Self, Option<i64>> { MenuItem::parent_id }
    ///     fn scope(&self) -> Scope<Self> {
    ///         Scope::new().by(MenuItem::menu_id, &self.menu_id)
    ///     }
    /// }
    /// # async fn example(header_id: i64) -> laravel::Result<()> {
    /// let menu = MenuItem::subtree_of(header_id).await?; // a TreeNode with its children
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// As [`ancestors_of`](Self::ancestors_of).
    fn subtree_of(key: Self::Key) -> impl Future<Output = laravel::Result<TreeNode<Self>>> + Send {
        async move {
            let node = ops::find::<Self>(&key).await?;
            let nodes = node.descendants_and_self().get().await?;
            Ok(nodes
                .into_tree()
                .into_iter()
                .next()
                .expect("the node is in its own subtree"))
        }
    }

    /// 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. Read from the
    /// [`depth_column`](Self::depth_column) when the model has one, or one `count` query.
    ///
    /// # Errors
    ///
    /// Fails when the query fails.
    fn depth(&self) -> impl Future<Output = laravel::Result<u64>> + Send {
        let stored = Self::depth_column().map(|column| u64::try_from(*column.get(self)).unwrap_or(0));
        let count = self.ancestors().count();
        async move {
            match stored {
                Some(depth) => Ok(depth),
                None => count.await,
            }
        }
    }

    /// 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.
    ///
    /// ```no_run
    /// # use laravel::model::{Column, 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 }
    /// # }
    /// # async fn example() -> laravel::Result<()> {
    /// let shop = Category::create_root(Category::create().name("Shop")).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # 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.
    ///
    /// ```no_run
    /// # use laravel::model::{Column, 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 }
    /// # }
    /// # async fn example(mut shop: Category) -> laravel::Result<()> {
    /// let phones = shop.create_child(Category::create().name("Phones")).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # 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 }
    }

    /// Rearranges a tree the way `items` lists it: the listed nodes become roots, in the listed
    /// order, with the listed children below them. Made for saving a drag-and-drop tree editor:
    ///
    /// ```no_run
    /// # use laravel::model::{Column, model};
    /// # use laravel_nestedset::NestedSet;
    /// # #[model]
    /// # pub struct Category {
    /// #     pub id: i64,
    /// #     #[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 }
    /// # }
    /// use laravel_nestedset::Arrangement;
    ///
    /// # async fn example(body: &str) -> laravel::Result<()> {
    /// // [{"id": 1, "children": [{"id": 3}, {"id": 2}]}, {"id": 4}]
    /// let items: Vec<Arrangement<i64>> = serde_json::from_str(body)?;
    /// Category::arrange(items).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Every listed node must be in one tree, the tree of the first one. Nodes of that tree the
    /// list leaves out keep their parent and come after the listed siblings. One transaction
    /// rebuilds the whole tree; returns how many rows changed.
    ///
    /// # Errors
    ///
    /// Fails with [`NestedSetError::NodeNotFound`](crate::NestedSetError) when a listed node
    /// isn't in the tree, with [`NestedSetError::DuplicateKey`](crate::NestedSetError) when one
    /// is listed twice, and when a query fails. Nothing changes then.
    fn arrange(items: Vec<Arrangement<Self::Key>>) -> impl Future<Output = laravel::Result<u64>> + Send
    where
        Option<Self::Key>: IntoExpr,
    {
        arrange::arrange::<Self>(None, items)
    }

    /// Rearranges the nodes below this one the way `items` lists them, as
    /// [`arrange`](Self::arrange) does for roots, and reloads this node.
    ///
    /// # Errors
    ///
    /// As [`arrange`](Self::arrange), and with
    /// [`NestedSetError::MoveIntoOwnSubtree`](crate::NestedSetError) when the list holds this
    /// node or one above it.
    fn arrange_children(
        &mut self,
        items: Vec<Arrangement<Self::Key>>,
    ) -> impl Future<Output = laravel::Result<u64>> + Send
    where
        Option<Self::Key>: IntoExpr,
    {
        async move {
            let changed = arrange::arrange(Some(&*self), items).await?;
            *self = ops::reload_fresh(self).await?;
            Ok(changed)
        }
    }

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