laravel-nestedset 0.3.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
# laravel-nestedset

[![Crates.io](https://img.shields.io/crates/v/laravel-nestedset.svg)](https://crates.io/crates/laravel-nestedset)
[![Docs.rs](https://docs.rs/laravel-nestedset/badge.svg)](https://docs.rs/laravel-nestedset)
[![CI](https://github.com/axvilab/laravel-nestedset-rs/actions/workflows/ci.yml/badge.svg)](https://github.com/axvilab/laravel-nestedset-rs/actions/workflows/ci.yml)
[![License: MIT OR Apache-2.0](https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-blue.svg)](#license)

Nested set trees for [Laravel Rust](https://crates.io/crates/laravel-rust) models: product
categories, site menus, comment threads, org charts. A whole subtree or every ancestor of a node
is one indexed query, a subtree moves with a fixed number of `UPDATE`s, and every write locks its
tree, so concurrent writers can't corrupt it.

- [Installation]#installation
- [Quick start: shop categories]#quick-start-shop-categories
- [Creating nodes]#creating-nodes
- [Moving nodes]#moving-nodes
- [Copying a subtree]#copying-a-subtree
- [Deleting nodes]#deleting-nodes
- [Querying]#querying
  - [Tree conditions in any query]#tree-conditions-in-any-query
  - [By key, without loading the node]#by-key-without-loading-the-node
  - [Relatives of a whole list, without N+1]#relatives-of-a-whole-list-without-n1
  - [Products of a category and its subcategories]#products-of-a-category-and-its-subcategories
  - [Slug paths]#slug-paths
- [Building a tree for JSON and templates]#building-a-tree-for-json-and-templates
- [Admin forms: the parent select]#admin-forms-the-parent-select
- [Saving a drag-and-drop tree editor]#saving-a-drag-and-drop-tree-editor
- [Reacting to changes]#reacting-to-changes
- [Several trees in one table: site menus]#several-trees-in-one-table-site-menus
- [Storing the depth]#storing-the-depth
- [Checking and fixing a tree]#checking-and-fixing-a-tree
- [Concurrency]#concurrency
- [Performance]#performance
- [Nested set, adjacency list, or closure table?]#nested-set-adjacency-list-or-closure-table
- [Custom column names and UUID keys]#custom-column-names-and-uuid-keys
- [Testing]#testing

## Installation

```toml
[dependencies]
laravel-nestedset = "0.3"
```

The package uses the database driver your application enables on `laravel-rust`: SQLite,
PostgreSQL, MySQL, or MariaDB. It needs Rust 1.99 or later, like Laravel Rust itself.

## Quick start: shop categories

Add the columns in a migration. `nested_set()` adds `lft`, `rgt`, a nullable `parent_id`, and the
indexes the queries use:

```rust
use laravel_nestedset::NestedSetBlueprint;

tx.schema()
    .create("categories", |table| {
        table.id();
        table.string("name");
        table.nested_set();
        table.timestamps();
    })
    .await?;
```

Implement `NestedSet` for the model, naming its three columns:

```rust
use laravel::model::{Column, model};
use laravel::time::Timestamp;
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>,
    pub created_at: Timestamp,
    pub updated_at: Timestamp,
}

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
    }
}
```

That's all the setup. The examples below use this tree:

```text
Shop
├── Phones
│   ├── Android
│   └── iPhone
├── Laptops
└── Tablets
Blog
```

## Creating nodes

```rust
let mut shop = Category::create_root(Category::create().name("Shop")).await?;
let mut phones = shop.create_child(Category::create().name("Phones")).await?;
phones.create_child(Category::create().name("Android")).await?;
phones.create_child(Category::create().name("iPhone")).await?;
let mut laptops = shop.create_child(Category::create().name("Laptops")).await?;
laptops.create_after(Category::create().name("Tablets")).await?;
Category::create_root(Category::create().name("Blog")).await?;
```

| Method | The new node goes |
| --- | --- |
| `Category::create_root(create)` | after the last root of its tree |
| `node.create_child(create)` | last among `node`'s children |
| `node.create_first_child(create)` | first among `node`'s children |
| `node.create_before(create)` | right before `node`, under the same parent |
| `node.create_after(create)` | right after `node`, under the same parent |

Each takes the model's own create builder, so required columns, hooks, and events work as usual.
The method reloads `node` afterwards, so its bounds stay current. Other models you hold, such as
`node`'s ancestors, keep their old bounds: load them again before you compare them.

To create a whole tree at once, nest `NewNode`s:

```rust
use laravel_nestedset::NewNode;

let shop = Category::create_tree(
    NewNode::new(Category::create().name("Shop")).children([
        NewNode::new(Category::create().name("Phones")).children([
            NewNode::new(Category::create().name("Android")),
            NewNode::new(Category::create().name("iPhone")),
        ]),
        NewNode::new(Category::create().name("Laptops")),
    ]),
)
.await?;

// Or below an existing node:
shop.create_child_tree(NewNode::new(Category::create().name("Audio"))).await?;
```

## Moving nodes

A node moves with its whole subtree. However big the subtree, the move is two `UPDATE`s: one
for the bounds and one for the parent.

```rust
phones.append_to(&laptops).await?;     // last child of Laptops
phones.prepend_to(&laptops).await?;    // first child of Laptops
phones.insert_before(&tablets).await?; // right before Tablets, under Tablets' parent
phones.insert_after(&tablets).await?;  // right after Tablets
phones.make_root().await?;             // a root, after the last one

tablets.up(1).await?;   // one place up among its siblings: true if it moved
tablets.down(2).await?; // two places down
```

The moved node is reloaded. A move fails, and changes nothing, when it would put a node inside
its own subtree (`NestedSetError::MoveIntoOwnSubtree`) or into another tree of a scoped table
(`NestedSetError::ScopeMismatch`).

## Copying a subtree

```rust
let copy = phones.copy_to(&laptops).await?; // Phones, Android, iPhone, again below Laptops
let template = menu.copy_as_root().await?;  // a copy after the last root of its tree
```

Every column is copied except the key and the timestamps, as `replicate` does. The space opens
with one `UPDATE`, then the copies go in one by one, so the model's hooks and events run for
each. A copy may go into another tree of a scoped table, such as the header menu into the footer
menu: the copies take the target's scope values. It may also go below the node itself, as a copy
of the subtree as it was.

## Deleting nodes

```rust
let deleted = phones.delete_subtree().await?; // Phones, Android, iPhone: 3
```

`delete_subtree` removes the node and its whole subtree and closes the gap in the bounds.

> [!IMPORTANT]
> Don't delete nodes with the model's `delete` or a `delete` query. That leaves a gap in the
> bounds and orphans the children. If it has happened, [`fix_tree`]#checking-and-fixing-a-tree
> repairs the table.

The rows go with one query, so model hooks and events don't run for them. Laravel Rust models
have no soft deletes, so neither does this package.

## Querying

Every query is a Laravel Rust model `Builder`, so you can filter, paginate, or count it further:

```rust
shop.descendants().get().await?;          // Phones, Android, iPhone, Laptops, Tablets
phones.descendants_and_self().get().await?;
android.ancestors().get().await?;         // Shop, Phones: breadcrumbs
android.ancestors_and_self().get().await?;
shop.children().get().await?;             // Phones, Laptops, Tablets
laptops.siblings().get().await?;          // Phones, Tablets
phones.next_siblings().get().await?;      // Laptops, Tablets
tablets.prev_siblings().get().await?;     // Phones, Laptops
laptops.next_sibling().await?;            // Some(Tablets)
laptops.prev_sibling().await?;            // Some(Phones)
android.parent().await?;                  // Some(Phones)
android.depth().await?;                   // 2, or read from a depth column
Category::roots().get().await?;           // Shop, Blog
Category::leaves().get().await?;          // Android, iPhone, Laptops, Tablets, Blog

let phones_in_stock = shop
    .descendants()
    .filter(Category::name.ne("Tablets"))
    .count()
    .await?;
```

Queries of a node stay inside its tree, and the ones that list nodes come in tree order. Order
your own queries the same way with the `default_order` scope, or reverse it with `reversed`:

```rust
let all = Category::query().scope(Category::default_order).get().await?;
```

Checks read the bounds the models already hold, without a query:

```rust
android.is_leaf();               // true
shop.is_root();                  // true
android.is_descendant_of(&shop); // true
shop.is_ancestor_of(&android);   // true
android.is_child_of(&phones);    // true
android.is_sibling_of(&iphone);  // true
shop.descendant_count();         // 5
```

To get the goods of a category and of every category below it, take the subtree's keys:

```rust
let mut ids = phones.descendants().pluck(Category::id).await?;
ids.push(phones.id);
let goods = Product::query().filter(Product::category_id.is_in(ids)).get().await?;
```

### Tree conditions in any query

Every relation is also a condition, so it combines with any other filter through `&`, `|`, and
`!`:

```rust
let pro_phones = Category::query()
    .filter(Category::where_descendant_of(&phones) & Category::name.contains("Pro"))
    .get()
    .await?;

let shallow_leaves = Category::query()
    .filter(Category::where_leaf() & !Category::where_descendant_of(&phones))
    .get()
    .await?;
```

| Condition | Matches |
| --- | --- |
| `where_descendant_of(&node)`, `where_descendant_or_self(&node)` | the subtree below `node`, without or with it |
| `where_ancestor_of(&node)`, `where_ancestor_or_self(&node)` | the path above `node`, without or with it |
| `where_child_of(&node)` | `node`'s direct children |
| `where_root()`, `where_has_parent()` | roots, non-roots |
| `where_leaf()`, `where_has_children()` | leaves, nodes with children |

The conditions that take a node stay inside its tree in a [scoped table](#several-trees-in-one-table-site-menus).

### By key, without loading the node

When all you have is a key, such as a route parameter, skip loading the node yourself:

```rust
let breadcrumbs = Category::ancestors_of(id).await?;
let subtree = Category::descendants_of(id).await?;
let children = Category::children_of(id).await?;
let menu = Category::subtree_of(id).await?; // a TreeNode: the node with its subtree nested
```

There are `_and_self_of` versions of the first two. Each reads the node by its primary key, then
runs the relation's query, and fails with `NestedSetError::NodeNotFound` when there's no such
node.

### Relatives of a whole list, without N+1

`with_ancestors` loads the breadcrumbs of every node in a list with one query, however long the
list. That's what a page of search results needs:

```rust
use laravel_nestedset::LoadRelatives;

let results = Category::query()
    .filter(Category::name.contains(term))
    .limit(20)
    .get()
    .await?
    .with_ancestors()
    .await?;

for result in &results {
    let path: Vec<&str> = result.ancestors.iter().map(|node| node.name.as_str()).collect();
    println!("{} / {}", path.join(" / "), result.node.name);
}
```

`with_descendants` does the same for subtrees, and gives each node as a nested
[`TreeNode`](#building-a-tree-for-json-and-templates): two queries for every menu of a site,
for example. Both serialize, with `ancestors` or `children` next to the model's fields.

### Products of a category and its subcategories

`where_in_subtree` matches the rows of another table that point at a node or at any node below
it. It's a condition on the other model's query, so filter, sort, and paginate as usual:

```rust
let phones_on_sale = Product::query()
    .filter(Category::where_in_subtree(&phones, Product::category_id) & Product::on_sale.eq(true))
    .order_by(Product::price.asc())
    .get()
    .await?;
```

For a menu with counts, `with_subtree_counts` counts them for a whole list of nodes in one query,
and `with_subtree_counts_where` counts only the rows a condition matches:

```rust
let menu = Category::roots()
    .get()
    .await?
    .with_subtree_counts_where(Product::category_id, Product::published.eq(true))
    .await?;

for entry in &menu {
    println!("{} ({})", entry.node.name, entry.count); // Phones (124)
}
```

Each `WithCount` serializes as the node's fields plus `count`.

### Slug paths

For URLs such as `/catalog/shop/phones/android`, build the path from a column and find a node by
it:

```rust
android.path(Category::slug, "/").await?;            // "shop/phones/android"
android.path(Category::name, " › ").await?;          // "Shop › Phones › Android"

Category::find_by_path(Category::slug, "shop/phones/android").await?; // Some(android)
shop.find_by_path_below(Category::slug, "phones/android").await?;     // the same, from a node
```

`find_by_path` reads only the nodes whose column matches a segment, in one query, and checks that
they chain from a root down. A wrong segment anywhere gives `None`.

## Building a tree for JSON and templates

`into_tree` nests a list of nodes, such as a query's result, under their parents:

```rust
use laravel_nestedset::IntoTree;

let tree = Category::query()
    .scope(Category::default_order)
    .get()
    .await?
    .into_tree();
```

Each `TreeNode` holds the `node`, its `depth` in the built tree, and its `children`. It
serializes as the model's own fields plus `depth` and `children`, so you can return it from a
JSON endpoint or hand it to a template:

```json
[
  {
    "id": 1, "name": "Shop", "lft": 1, "rgt": 12, "parent_id": null, "depth": 0,
    "children": [
      { "id": 2, "name": "Phones", "depth": 1, "children": ["..."] }
    ]
  }
]
```

Nodes whose parent isn't in the list are at the top, so a subtree works too:
`phones.descendants().get().await?.into_tree()` gives Android and iPhone at the top.
Siblings keep the order of the list.

`into_flat_tree` keeps one flat list, each node right before its children. That's what a
`<select>` of categories, indented by depth, needs:

```rust
let options = Category::query().scope(Category::default_order).get().await?.into_flat_tree();
```

## Admin forms: the parent select

`allowed_parents` lists the nodes a node may move under: its whole tree except itself and its
subtree. `into_flat_tree_with_depth` puts them in tree order with each one's depth, ready to
indent:

```rust
use laravel_nestedset::IntoTree;

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();
```

Nobody can pick a node below the one they edit, and if they send one anyway, the move fails with
`NestedSetError::MoveIntoOwnSubtree`.

## Saving a drag-and-drop tree editor

Tree editors on the frontend send the whole new arrangement as nested ids. `arrange` applies it
in one transaction:

```rust
use laravel_nestedset::Arrangement;

// [{"id": 1, "children": [{"id": 3}, {"id": 2}]}, {"id": 4}]
let items: Vec<Arrangement<i64>> = serde_json::from_str(&body)?;
Category::arrange(items).await?; // the listed nodes become roots, in this order

menu.arrange_children(items).await?; // or below one node
```

An `Arrangement` deserializes from `{"id": .., "children": [..]}` or `{"key": .., ..}`, and
you can build one in Rust with `Arrangement::new(id).children([...])`. Every listed node must be
in one tree. Nodes the list leaves out keep their parent and come after the listed siblings, so
an editor may send just the part it changed. A node listed twice, a missing node, or a node
listed below itself fails the call, and nothing changes.

## Reacting to changes

Every write dispatches `TreeChanged` once it commits: after `create_*`, every move and copy,
`delete_subtree`, `arrange`, and a `fix_tree` that changed rows. A listener can drop a cached menu:

```rust
use laravel::event::{Event, listener};
use laravel_nestedset::{TreeChange, TreeChanged};

#[listener]
async fn forget_the_menu(event: Event<TreeChanged>) {
    if event.is_for::<Category>() {
        // Drop the cached category menu...
    }
}
```

The event carries the `change` (`Created`, `Moved`, `Copied`, `Deleted`, `Arranged`, or `Fixed`) and, for a
single node, its `key`.

## Several trees in one table: site menus

A scope splits a table into independent trees, such as menu items by `menu_id`. Each tree is
numbered on its own, a node's queries stay inside its tree, and writes lock only that tree:

```rust
tx.schema()
    .create("menu_items", |table| {
        table.id();
        table.foreign_id("menu_id");
        table.string("title");
        table.nested_set_scoped(&["menu_id"]);
    })
    .await?;
```

```rust
use laravel_nestedset::{NestedSet, Scope};

impl NestedSet for MenuItem {
    // lft_column, rgt_column, and parent_column, as above.

    fn scope(&self) -> Scope<Self> {
        Scope::new().by(MenuItem::menu_id, &self.menu_id)
    }
}

let mut header = MenuItem::create_root(MenuItem::create().menu_id(1).title("Header")).await?;
header.create_child(MenuItem::create().menu_id(1).title("Blog")).await?;
```

A new child gets its parent's scope values, and a node can't move into another tree.

When the scope of a new root is known up front, as with one tree per comment thread,
`create_root_in` locks only that tree, so new roots of other trees don't wait for it:

```rust
let comment = Comment::create_root_in(
    Scope::new().by(Comment::thread_id, &thread.id),
    Comment::create().body("First!"),
)
.await?;
```

The scope's values fill the create, and the root goes after the tree's last one in one insert.
`create_root`, which learns the scope from the new row, has to lock the roots of the whole table
first. On MySQL and MariaDB, new roots take turns across the table either way, because a tree
without rows has nothing to lock.
Table-wide queries, such as `MenuItem::roots()` or `MenuItem::query()`, see every tree: filter
them by the scope columns yourself.

## Storing the depth

To filter by level, such as the top two levels of a menu, store each node's depth. Add the column
and return it from `depth_column`:

```rust
table.nested_set();
table.nested_set_depth(); // `depth`, default 0, indexed
```

```rust
impl NestedSet for Category {
    // lft_column, rgt_column, and parent_column, as above.

    fn depth_column() -> Option<Column<Self, i64>> {
        Some(Category::depth)
    }
}

let top_two_levels = Category::query()
    .filter(Category::depth.le(1))
    .scope(Category::default_order)
    .get()
    .await?;
```

Every create and move keeps the column current, `node.depth()` reads it without a query, and
`check_tree` and `fix_tree` check and repair it. On a table that already has rows, run
`fix_tree` once after adding the column.

## Checking and fixing a tree

`check_tree` checks every tree in the table and names the broken nodes:

```rust
let report = Category::check_tree().await?;
if report.is_broken() {
    println!("bad bounds: {:?}", report.oddness);
    println!("shared bounds: {:?}", report.duplicates);
    println!("parent_id doesn't match the bounds: {:?}", report.wrong_parent);
    println!("parent_id points nowhere: {:?}", report.missing_parent);
}
```

`fix_tree` rebuilds every bound from `parent_id`, in one transaction, and returns how many rows
it changed:

```rust
let changed = Category::fix_tree().await?;
```

From the console, register the models with the service provider:

```rust
use laravel_nestedset::NestedSetServiceProvider;

Application::configure().with_providers(|providers| {
    providers.add(NestedSetServiceProvider::new().model::<Category>().model::<MenuItem>());
});
```

```shell
laravel nestedset:check             # every registered table; exits with 1 when one is broken
laravel nestedset:check categories  # one table
laravel nestedset:fix categories    # rebuild its bounds from parent_id
```

`nestedset:check` in a scheduled task or a deploy script catches a tree that someone broke with
plain SQL.

Siblings keep their current order. A node whose parent is gone, or that sits in a `parent_id`
cycle, becomes a root. The same call turns an existing `parent_id` table into a nested set: add
the columns with `table.nested_set()` or, when `parent_id` is already there, with
`big_integer("lft").default(0)` and `big_integer("rgt").default(0)`, then run `fix_tree` once.

## Concurrency

Every write runs in a transaction on the model's connection and first locks the tree it changes:

| Database | Lock |
| --- | --- |
| PostgreSQL | `pg_advisory_xact_lock` on the table and scope values |
| MySQL, MariaDB | A named lock per tree (`GET_LOCK`), held until the commit |
| SQLite | The database write lock, taken before any bound is read |

The bounds of every node involved are read again under the lock, so a stale model in your hands
can't put a node in the wrong place. On PostgreSQL, writes to different trees of a scoped table
don't wait for each other. New roots and moves to root also take turns across the whole table,
because a new root's tree is only known once its row is in.

On MySQL and MariaDB, row locks in the default REPEATABLE READ mode also lock the gaps of the
index next to a tree, so writers in neighbouring trees, such as two comment threads, would
deadlock. There the package takes a named lock per tree instead, on a session of its own small
pool, and releases it once the outermost transaction commits; if the transaction rolls back,
the session closes and the server drops the lock. Under those locks it reads and writes rows by
primary key, which locks rows without gaps. Writes inside one transaction of yours share their
locks, so two replies in one thread don't wait for each other. Writes that don't create rows run
again by themselves after a deadlock, up to three times. Enable the package's `mysql` feature for this:

```toml
laravel-nestedset = { version = "0.3", features = ["mysql"] }
```

Without it, MySQL falls back to locking a tree's root rows with `FOR UPDATE`, which is correct
but lets writers in neighbouring trees deadlock.

The test suite runs concurrent writers on all three databases, and a property test runs random
sequences of every operation, checking the tree after each step.

## Performance

Every query is built to stay on an index:

- A subtree is a range on `lft` with both ends set, so the database reads just that part of the
  index, whatever the size of the table.
- With integer keys, ancestors follow `parent_id` in one recursive query: one primary key lookup
  per level, instead of a scan of every node to the left that the bounds alone need.
- Children, siblings, and roots use the `parent_id` index; a new root reads the last bound from
  the roots only.
- Writes shift bounds in one `UPDATE` per operation, and `fix_tree` and `arrange` write a
  thousand rows per statement.

Criterion benchmarks (`cargo bench`, or `NESTEDSET_BENCH_URL=postgres://...` for PostgreSQL) on a
tree of 100,000 nodes with ten children per node, in Docker on a developer machine. Your numbers
will differ; the proportions are what matter.

| Operation, 100,000 nodes | SQLite | PostgreSQL | MySQL |
| --- | --- | --- | --- |
| `children` | 0.18 ms | 0.35 ms | 0.47 ms |
| `ancestors` of a leaf | 0.15 ms | 0.40 ms | 0.51 ms |
| `with_ancestors` of 20 nodes | 0.24 ms | 0.56 ms | 0.62 ms |
| `descendants` of a second-level node: 1,110 rows | 2.1 ms | 2.1 ms | 2.7 ms |
| `descendants().count()` of a tenth of the tree | 0.62 ms | 1.9 ms | 3.2 ms |
| `create_child` in the middle of the tree | 75 ms | 560 ms | 420 ms |
| Move a 1,111-node subtree across the tree | 133 ms | 80–180 ms | 76 ms |
| `check_tree` | 261 ms | 159 ms | 160 ms |
| `fix_tree` on a table with only `parent_id` | 1.5 s | 4–6 s | 3.4 s |

The MySQL numbers were taken before 0.2.2 moved MySQL writes to the primary key; a write in the
middle of one large tree is somewhat slower there now, and a write in a small tree of a scoped
table, such as a comment thread, touches only that tree's rows.

Reads stay under a few milliseconds as the tree grows. A write in the middle shifts the bounds of
every node to its right, about half the table here: the price a nested set pays for its reads.
PostgreSQL pays more for it, because it writes a new version of every changed row, so keep
frequent writes near the end of a tree, or prefer a nested set for trees that are read far more
than they change: categories, menus, documentation.

## Nested set, adjacency list, or closure table?

| | Adjacency list (`parent_id` only) | Nested set (this package) | Closure table |
| --- | --- | --- | --- |
| Children | One query | One query | One query |
| Whole subtree, ancestors | Recursive CTE or one query per level | One indexed range query | One join |
| Insert | One row | One row plus shifting bounds to its right | One row plus one per ancestor |
| Move a subtree | One update | Two updates, touching the rows between old and new place | Delete and insert paths for the whole subtree |
| Extra storage | None | Two integers per row | One row per ancestor-descendant pair |
| Best for | Write-heavy trees, shallow reads | Read-heavy trees: categories, menus, breadcrumbs | Deep trees with frequent moves and reads |

Nested sets pay on writes to make reads cheap, which suits trees that are read on every page and
edited from an admin panel.

## Custom column names and UUID keys

The bound and parent columns can have any names: map the fields and return them from
`lft_column`, `rgt_column`, and `parent_column`. For a table whose bounds are `_lft` and `_rgt`:

```rust
#[model]
pub struct Category {
    pub id: i64,
    #[column("_lft")]
    pub lft: i64,
    #[column("_rgt")]
    pub rgt: i64,
    pub parent_id: Option<i64>,
}
```

Models with UUID keys work too: their `parent_id` is a UUID, which `table.nested_set_uuid()`
adds instead of `nested_set()`. Integer keys get two extra speedups, described under
[Performance](#performance): ancestors through a recursive query, and batched writes in
`fix_tree` and `arrange`.

## Testing

Tests run in Docker; nothing gets installed on the host. `run.sh` runs a command in `rust:1.99`
with rustfmt and clippy added. SQLite runs in memory:

```shell
./run.sh cargo test
```

PostgreSQL and MySQL run from `docker-compose.yml`:

```shell
docker compose up -d
DATABASE_ENV="-e NESTEDSET_TEST_POSTGRES_URL=postgres://postgres:secret@127.0.0.1:55432/postgres \
  -e NESTEDSET_TEST_MYSQL_URL=mysql://root:secret@127.0.0.1:53306/nestedset" \
  ./run.sh cargo test --features postgres,mysql
```

## License

Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE) or
[MIT license](LICENSE-MIT) at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion
in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above,
without any additional terms or conditions.

---

Made by [AxVi](https://axvi.dev) · part of [AxViLab](https://github.com/axvilab)