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
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
//! `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::chain;
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())
}
/// The nodes this node may move under: every node of its tree except itself and its
/// subtree, in tree order. Feed it to the parent `<select>` of an edit form, so nobody can pick
/// a node below the one they edit:
///
/// ```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 }
/// # }
/// use laravel_nestedset::IntoTree;
///
/// # async fn example(category: Category) -> laravel::Result<()> {
/// let options: Vec<(String, i64)> = category
/// .allowed_parents()
/// .get()
/// .await?
/// .into_flat_tree_with_depth()
/// .into_iter()
/// .map(|(node, depth)| (format!("{}{}", "— ".repeat(depth), node.name), node.id))
/// .collect();
/// # Ok(())
/// # }
/// ```
fn allowed_parents(&self) -> Builder<Self> {
self.tree_query()
.filter(!Self::where_descendant_or_self(self))
.order_by(Self::lft_column().asc())
}
/// The values of `column` from the root down to this node, joined by `separator`: a slug
/// path such as `shop/phones/android`, or breadcrumbs as text.
///
/// # Errors
///
/// Fails when the query fails.
fn path(
&self,
column: Column<Self, String>,
separator: &str,
) -> impl Future<Output = laravel::Result<String>> + Send {
let values = self.ancestors_and_self().pluck(column);
let separator = separator.to_owned();
async move { Ok(values.await?.join(&separator)) }
}
/// The node at a slug path such as `shop/phones/android`: a root whose `column` is `shop`,
/// its child `phones`, and that one's child `android`. One query, for the nodes whose
/// `column` is one of the segments. `None` when no node is at the path. In a scoped table,
/// the first tree with a match wins; use [`find_by_path_below`](Self::find_by_path_below)
/// from a root to stay in one tree.
///
/// # Errors
///
/// Fails when the query fails.
fn find_by_path(
column: Column<Self, String>,
path: &str,
) -> impl Future<Output = laravel::Result<Option<Self>>> + Send {
let segments = segments(path);
let query = __query::<Self>()
.filter(column.is_in(segments.clone()))
.order_by(Self::lft_column().asc());
async move { Ok(walk(&query.get().await?, column, &segments, None)) }
}
/// The node at a slug path below this one: `phones/android` from the `shop` node.
///
/// # Errors
///
/// Fails when the query fails.
fn find_by_path_below(
&self,
column: Column<Self, String>,
path: &str,
) -> impl Future<Output = laravel::Result<Option<Self>>> + Send {
let segments = segments(path);
let query = __query::<Self>()
.filter(Self::where_descendant_of(self) & column.is_in(segments.clone()))
.order_by(Self::lft_column().asc());
let start = Some(self.node_key().clone());
async move { Ok(walk(&query.get().await?, column, &segments, start)) }
}
/// 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 {
// Below a node, every left bound lies between the node's bounds: both ends on the same
// indexed column let the database read just the subtree's part of the index.
node.scope().condition() & Self::lft_column().gt(node.lft()) & Self::lft_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().between(node.lft(), node.rgt())
}
/// Matches the nodes above `node`.
#[must_use]
fn where_ancestor_of(node: &Self) -> Condition {
match chain::chain_start(node, false) {
Some(start) => chain::chain::<Self>(&chain::chain_keys([start])),
None => 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 {
match chain::chain_start(node, true) {
Some(start) => chain::chain::<Self>(&chain::chain_keys([start])),
None => 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 the rows of another table that point at `node` or at any node below it: every
/// product of a category and its subcategories, in one query of the products.
///
/// ```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 }
/// # }
/// # #[model]
/// # pub struct Product {
/// # pub id: i64,
/// # pub category_id: i64,
/// # pub price: i64,
/// # }
/// # async fn example(phones: Category) -> laravel::Result<()> {
/// let cheap_phones = Product::query()
/// .filter(Category::where_in_subtree(&phones, Product::category_id) & Product::price.lt(300))
/// .get()
/// .await?;
/// # Ok(())
/// # }
/// ```
#[must_use]
fn where_in_subtree<R, T>(node: &Self, foreign_key: Column<R, T>) -> Condition
where
T: Send + Sync + 'static,
{
let keys = laravel::db::table(Self::META.table)
.select([Self::META.key.name()])
.filter(Self::where_descendant_or_self(node));
foreign_key.is_in(keys)
}
/// 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.
///
/// The new row's scope is only known once it's in, so this locks the roots of the whole table
/// first: new roots anywhere in the table take turns. In a table with many trees that get new
/// roots often, such as one tree per comment thread, use
/// [`create_root_in`](Self::create_root_in), which locks only the one tree.
///
/// ```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 root in the tree of `scope`, locking only that tree: new roots of other
/// trees don't wait for it. The scope's values fill the create, and the root goes after the
/// tree's last one, in one insert.
///
/// ```no_run
/// # use laravel::model::{Column, model};
/// # use laravel_nestedset::{NestedSet, Scope};
/// # #[model]
/// # pub struct Comment {
/// # pub id: i64,
/// # pub thread_id: i64,
/// # pub body: String,
/// # #[default]
/// # pub lft: i64,
/// # #[default]
/// # pub rgt: i64,
/// # pub parent_id: Option<i64>,
/// # }
/// # impl NestedSet for Comment {
/// # fn lft_column() -> Column<Self, i64> { Comment::lft }
/// # fn rgt_column() -> Column<Self, i64> { Comment::rgt }
/// # fn parent_column() -> Column<Self, Option<i64>> { Comment::parent_id }
/// # fn scope(&self) -> Scope<Self> { Scope::new().by(Comment::thread_id, &self.thread_id) }
/// # }
/// # async fn example(thread_id: i64) -> laravel::Result<()> {
/// let comment = Comment::create_root_in(
/// Scope::new().by(Comment::thread_id, &thread_id),
/// Comment::create().body("First!"),
/// )
/// .await?;
/// # Ok(())
/// # }
/// ```
///
/// On PostgreSQL the lock is per tree. MySQL and MariaDB can't lock a tree that has no rows
/// yet, so there new roots still take turns across the table, as with `create_root`, but for
/// a shorter time and without deadlocks between new trees.
///
/// # Errors
///
/// Fails with [`NestedSetError::OutsideScope`](crate::NestedSetError) when `scope` isn't
/// built from the model's scope columns, so the new row would land outside it; nothing is
/// written then. Fails when a query fails.
fn create_root_in(
scope: Scope<Self>,
create: impl Into<CreateBuilder<Self>> + Send,
) -> impl Future<Output = laravel::Result<Self>> + Send {
ops::create_root_in(scope, 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)
}
/// Copies this node with its whole subtree as the last child of `target`, and returns the
/// copy. Every column is copied except the key and the timestamps, as `replicate` does, and
/// the copies take `target`'s tree: copy the header menu into the footer menu, say. The
/// copies are inserted one by one, so model hooks and events run for each.
///
/// # Errors
///
/// Fails when this node or `target` no longer exists or a query fails; nothing is copied
/// then.
fn copy_to(&self, target: &Self) -> impl Future<Output = laravel::Result<Self>> + Send
where
Option<Self::Key>: IntoExpr,
{
ops::copy_subtree(self, Some(target))
}
/// Copies this node with its whole subtree as a new root after the last one of its tree.
///
/// # Errors
///
/// As [`copy_to`](Self::copy_to).
fn copy_as_root(&self) -> impl Future<Output = laravel::Result<Self>> + Send
where
Option<Self::Key>: IntoExpr,
{
ops::copy_subtree(self, None)
}
/// 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(())
}
/// The non-empty segments of a slash-separated path.
fn segments(path: &str) -> Vec<String> {
path.split('/')
.filter(|segment| !segment.is_empty())
.map(str::to_owned)
.collect()
}
/// Follows `segments` down from the children of `start` (the roots when `None`) through
/// `candidates`, which are in tree order.
fn walk<M: NestedSet>(
candidates: &[M],
column: Column<M, String>,
segments: &[String],
start: Option<M::Key>,
) -> Option<M> {
if segments.is_empty() {
return None;
}
let mut parent = start;
let mut found = None;
for segment in segments {
let next = candidates
.iter()
.find(|node| column.get(node) == segment && node.parent_key() == parent.as_ref())?;
parent = Some(next.node_key().clone());
found = Some(next);
}
found.cloned()
}