laravel-nestedset 0.2.3

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
//! The writes: inserting, moving, and deleting nodes, each in a transaction that locks the tree.

use laravel::db::sqlx::AssertSqlSafe;
use laravel::db::{self, AnyConnection, Driver, IntoExpr, Values, col};

/// How many times a write without a create runs again after a deadlock.
pub(crate) const ATTEMPTS: u32 = 3;
use std::collections::HashMap;

use laravel::model::{__query, CreateBuilder, Model, Replica};

use crate::error::NestedSetError;
use crate::event::{TreeChange, changed};
use crate::locks::Locks;
use crate::node::NestedSet;
use crate::scope::Scope;

/// Where a new node goes, next to an existing one.
#[derive(Clone, Copy, Debug)]
pub(crate) enum NewPlace {
    FirstChild,
    LastChild,
    Before,
    After,
}

/// Where an existing node moves.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Place {
    Root,
    FirstChild,
    LastChild,
    Before,
    After,
}

/// The connection the model's queries run on.
pub(crate) fn connection<M: Model>() -> laravel::Result<AnyConnection> {
    match M::META.connection {
        Some(name) => db::connection(name),
        None => db::default_connection(),
    }
}

/// Reads the node with `key`, failing when there's no such node.
pub(crate) async fn find<M: NestedSet>(key: &M::Key) -> laravel::Result<M> {
    let node = __query::<M>().filter(M::META.key.eq(key.clone())).first().await?;
    Ok(node.ok_or_else(|| NestedSetError::NodeNotFound {
        model: M::META.name,
        key: key.to_string(),
    })?)
}

/// Reads the node with `key` again inside a write, locking its row by key, so it's the latest
/// committed version; fails when the node no longer exists.
async fn reload<M: NestedSet>(key: &M::Key) -> laravel::Result<M> {
    let node = __query::<M>()
        .filter(M::META.key.eq(key.clone()))
        .lock_for_update()
        .first()
        .await?;
    Ok(node.ok_or_else(|| NestedSetError::NodeNotFound {
        model: M::META.name,
        key: key.to_string(),
    })?)
}

/// Reads `node` again from the database.
pub(crate) async fn reload_fresh<M: NestedSet>(node: &M) -> laravel::Result<M> {
    reload::<M>(node.node_key()).await
}

pub(crate) async fn create_root<M: NestedSet>(create: CreateBuilder<M>) -> laravel::Result<M> {
    connection::<M>()?
        .transaction(async |tx| {
            // The scope lives in the new row's columns, so the row goes in before its tree is
            // known. Roots of every tree take turns first, then the new root locks its own tree
            // and takes the bounds after the tree's last root.
            let mut locks = Locks::open::<M>(tx).await?;
            locks.roots::<M>(tx).await?;
            let node = with_depth(create.set(M::lft_column(), 0).set(M::rgt_column(), 0), 0).await?;
            let scope = node.scope();
            locks.tree(tx, &scope).await?;
            // The insert read its row back before the tree's lock: on MySQL that started the
            // transaction's snapshot, so the last bound needs a read of the latest rows.
            let last = last_bound(&locks, &scope, Some(node.node_key()), true).await?;
            // A plain query: placing the new root isn't an update of it, so no hooks or events.
            let values = Values::new()
                .set(M::lft_column().name(), last + 1)
                .set(M::rgt_column().name(), last + 2);
            __query::<M>()
                .filter(M::META.key.eq(node.node_key().clone()))
                .update_values(untouched::<M>(values))
                .await?;
            changed::<M>(TreeChange::Created, Some(node.node_key())).await?;
            let node = reload::<M>(node.node_key()).await?;
            locks.release_after_commit(tx).await?;
            Ok(node)
        })
        .await
}

/// Inserts a new root into the tree of `scope`, locking only that tree: one insert, with the
/// bounds after the tree's last root.
pub(crate) async fn create_root_in<M: NestedSet>(scope: Scope<M>, create: CreateBuilder<M>) -> laravel::Result<M> {
    connection::<M>()?
        .transaction(async |tx| {
            let mut locks = Locks::open::<M>(tx).await?;
            locks.tree(tx, &scope).await?;
            let last = last_bound(&locks, &scope, None, false).await?;
            let create = scope
                .fill(create)
                .set(M::lft_column(), last + 1)
                .set(M::rgt_column(), last + 2);
            let node = with_depth(create, 0).await?;
            if node.scope().lock_name() != scope.lock_name() {
                return Err(NestedSetError::OutsideScope { model: M::META.name }.into());
            }
            changed::<M>(TreeChange::Created, Some(node.node_key())).await?;
            locks.release_after_commit(tx).await?;
            Ok(node)
        })
        .await
}

/// The last bound of the tree of `scope`: its last root's right bound, `0` for an empty tree.
/// Reading only roots uses the parent index. `except` leaves out a root being placed.
async fn last_bound<M: NestedSet>(
    locks: &Locks,
    scope: &Scope<M>,
    except: Option<&M::Key>,
    latest: bool,
) -> laravel::Result<i64> {
    let mut roots = scope.apply(__query::<M>()).filter(M::where_root());
    if let Some(except) = except {
        roots = roots.filter(M::META.key.ne(except.clone()));
    }
    let roots = if latest {
        locks.latest(roots)
    } else {
        locks.fresh(roots)
    };
    // The last root itself rather than `max`: an aggregate drops `FOR UPDATE`, and with it the
    // read of the latest rows.
    let last = roots.order_by(M::rgt_column().desc()).first().await?;
    Ok(last.map_or(0, |root| root.rgt()))
}

/// Inserts a new node next to `anchor`, and reloads `anchor`.
pub(crate) async fn create_near<M: NestedSet>(
    anchor: &mut M,
    create: CreateBuilder<M>,
    place: NewPlace,
) -> laravel::Result<M>
where
    Option<M::Key>: IntoExpr,
{
    let scope = anchor.scope();
    let key = anchor.node_key().clone();
    let (node, fresh) = connection::<M>()?
        .transaction(async |tx| {
            let mut locks = Locks::open::<M>(tx).await?;
            locks.tree(tx, &scope).await?;
            // The caller's copy of the anchor may be stale: read its bounds again under the lock.
            let fresh = reload::<M>(&key).await?;
            let (position, parent) = match place {
                NewPlace::FirstChild => (fresh.lft() + 1, Some(key.clone())),
                NewPlace::LastChild => (fresh.rgt(), Some(key.clone())),
                NewPlace::Before => (fresh.lft(), fresh.parent_key().cloned()),
                NewPlace::After => (fresh.rgt() + 1, fresh.parent_key().cloned()),
            };
            let depth = stored_depth(&fresh) + i64::from(matches!(place, NewPlace::FirstChild | NewPlace::LastChild));
            shift::<M>(&locks, &scope, position, 2).await?;
            let create = scope
                .fill(create)
                .set(M::lft_column(), position)
                .set(M::rgt_column(), position + 1)
                .set(M::parent_column(), parent);
            let node = with_depth(create, depth).await?;
            changed::<M>(TreeChange::Created, Some(node.node_key())).await?;
            let fresh = reload::<M>(&key).await?;
            locks.release_after_commit(tx).await?;
            Ok((node, fresh))
        })
        .await?;
    *anchor = fresh;
    Ok(node)
}

/// Moves `node` with its subtree to `place` relative to `target` (ignored for `Place::Root`),
/// and reloads `node`.
pub(crate) async fn move_node<M: NestedSet>(node: &mut M, target: Option<&M>, place: Place) -> laravel::Result<()>
where
    Option<M::Key>: IntoExpr,
{
    let scope = node.scope();
    if let Some(target) = target
        && target.scope().lock_name() != scope.lock_name()
    {
        return Err(NestedSetError::ScopeMismatch {
            model: M::META.name,
            key: node.node_key().to_string(),
            target: target.node_key().to_string(),
        }
        .into());
    }
    let key = node.node_key().clone();
    let target_key = target.map(|target| target.node_key().clone());
    let fresh = connection::<M>()?
        .transaction_with_attempts(ATTEMPTS, async |tx| {
            let mut locks = Locks::open::<M>(tx).await?;
            if matches!(place, Place::Root) {
                locks.roots::<M>(tx).await?;
            }
            locks.tree(tx, &scope).await?;
            let fresh = reload::<M>(&key).await?;
            let (lft, rgt) = (fresh.lft(), fresh.rgt());

            let (position, parent, depth) = match &target_key {
                None => (last_bound(&locks, &scope, None, false).await? + 1, None, 0),
                Some(target_key) => {
                    let target = reload::<M>(target_key).await?;
                    if target.lft() >= lft && target.lft() <= rgt {
                        return Err(NestedSetError::MoveIntoOwnSubtree {
                            model: M::META.name,
                            key: key.to_string(),
                            target: target_key.to_string(),
                        }
                        .into());
                    }
                    let depth = stored_depth(&target);
                    match place {
                        Place::FirstChild => (target.lft() + 1, Some(target_key.clone()), depth + 1),
                        Place::LastChild => (target.rgt(), Some(target_key.clone()), depth + 1),
                        Place::Before => (target.lft(), target.parent_key().cloned(), depth),
                        Place::After | Place::Root => (target.rgt() + 1, target.parent_key().cloned(), depth),
                    }
                }
            };

            if position != lft && position != rgt + 1 {
                move_bounds::<M>(&locks, &scope, lft, rgt, position).await?;
            }
            if parent.as_ref() != fresh.parent_key() {
                let name = M::parent_column().name();
                __query::<M>()
                    .filter(M::META.key.eq(key.clone()))
                    .update_values(untouched::<M>(Values::new().set(name, parent)))
                    .await?;
            }
            changed::<M>(TreeChange::Moved, Some(&key)).await?;
            let moved = reload::<M>(&key).await?;
            let shift = depth - stored_depth(&fresh);
            if let Some(column) = M::depth_column()
                && shift != 0
            {
                let name = column.name();
                let subtree = M::lft_column().between(moved.lft(), moved.rgt());
                let values = untouched::<M>(Values::new().set(name, col(name) + shift));
                locks.update(&scope, subtree, values).await?;
            }
            let moved = reload::<M>(&key).await?;
            locks.release_after_commit(tx).await?;
            Ok(moved)
        })
        .await?;
    *node = fresh;
    Ok(())
}

/// Copies `node` with its subtree: as the last child of `target`, or as the last root of `node`'s
/// tree when `target` is `None`. Returns the copy of `node`.
pub(crate) async fn copy_subtree<M: NestedSet>(node: &M, target: Option<&M>) -> laravel::Result<M>
where
    Option<M::Key>: IntoExpr,
{
    let source_key = node.node_key().clone();
    let target_key = target.map(|target| target.node_key().clone());
    let source_scope = node.scope();
    let scope = target.map_or_else(|| node.scope(), NestedSet::scope);
    connection::<M>()?
        .transaction(async |tx| {
            let mut locks = Locks::open::<M>(tx).await?;
            if target_key.is_none() {
                locks.roots::<M>(tx).await?;
            }
            locks.tree(tx, &scope).await?;
            if source_scope.lock_name() != scope.lock_name() {
                locks.tree(tx, &source_scope).await?;
            }
            let source = reload::<M>(&source_key).await?;
            let rows = locks
                .fresh(__query::<M>().filter(M::where_descendant_or_self(&source)))
                .order_by(M::lft_column().asc())
                .get()
                .await?;

            let (position, top_parent, top_depth) = match &target_key {
                Some(target_key) => {
                    let target = reload::<M>(target_key).await?;
                    (target.rgt(), Some(target_key.clone()), stored_depth(&target) + 1)
                }
                None => (last_bound(&locks, &scope, None, false).await? + 1, None, 0),
            };
            shift::<M>(&locks, &scope, position, source.rgt() - source.lft() + 1).await?;

            // Rows come in tree order, so every parent is copied before its children.
            let offset = position - source.lft();
            let depth_offset = top_depth - stored_depth(&source);
            let mut copies: HashMap<M::Key, M::Key> = HashMap::new();
            let mut top = None;
            for row in &rows {
                let parent = if row.node_key() == source.node_key() {
                    top_parent.clone()
                } else {
                    row.parent_key().and_then(|parent| copies.get(parent)).cloned()
                };
                let create = scope
                    .fill(CreateBuilder::<M>::new().fill(Replica::__new(row)))
                    .set(M::lft_column(), row.lft() + offset)
                    .set(M::rgt_column(), row.rgt() + offset)
                    .set(M::parent_column(), parent);
                let copy = with_depth(create, stored_depth(row) + depth_offset).await?;
                copies.insert(row.node_key().clone(), copy.node_key().clone());
                top.get_or_insert(copy);
            }
            let top = top.expect("a subtree holds its own top");
            changed::<M>(TreeChange::Copied, Some(top.node_key())).await?;
            locks.release_after_commit(tx).await?;
            Ok(top)
        })
        .await
}

/// Deletes the node and its subtree, and closes the gap they leave. Returns the number of rows
/// deleted.
pub(crate) async fn delete_subtree<M: NestedSet>(node: &M) -> laravel::Result<u64> {
    let scope = node.scope();
    let key = node.node_key().clone();
    connection::<M>()?
        .transaction_with_attempts(ATTEMPTS, async |tx| {
            let mut locks = Locks::open::<M>(tx).await?;
            locks.tree(tx, &scope).await?;
            let fresh = reload::<M>(&key).await?;
            let (lft, rgt) = (fresh.lft(), fresh.rgt());
            let deleted = locks.delete(&scope, M::lft_column().between(lft, rgt)).await?;
            shift::<M>(&locks, &scope, rgt + 1, -(rgt - lft + 1)).await?;
            changed::<M>(TreeChange::Deleted, Some(&key)).await?;
            locks.release_after_commit(tx).await?;
            Ok(deleted)
        })
        .await
}

/// Moves the block `lft..=rgt` so that it starts at `position`, shifting the nodes between the
/// two places the other way: one `UPDATE`, whatever the size of the subtree.
async fn move_bounds<M: NestedSet>(
    locks: &Locks,
    scope: &Scope<M>,
    lft: i64,
    rgt: i64,
    position: i64,
) -> laravel::Result<()> {
    let width = rgt - lft + 1;
    // The other block that changes, and how far each of the two moves.
    let (from, to, node_shift, other_shift) = if position > rgt {
        (rgt + 1, position - 1, position - 1 - rgt, -width)
    } else {
        (position, lft - 1, position - lft, width)
    };
    let (low, high) = (from.min(lft), to.max(rgt));
    let driver = locks.driver();

    let mut values = Values::new();
    for name in [M::lft_column().name(), M::rgt_column().name()] {
        let column = quote(driver, name);
        // Only integers go into the SQL, so the expression can't carry anything else.
        let case = format!(
            "CASE WHEN {column} BETWEEN {lft} AND {rgt} THEN {column} + ({node_shift}) \
             WHEN {column} BETWEEN {from} AND {to} THEN {column} + ({other_shift}) \
             ELSE {column} END"
        );
        values = values.set(name, db::raw!(AssertSqlSafe(case)));
    }
    let rows = M::lft_column().between(low, high) | M::rgt_column().between(low, high);
    locks.update(scope, rows, untouched::<M>(values)).await
}

/// Adds `amount` to every bound at or after `position`: a positive amount opens a gap there, a
/// negative one closes it. One `UPDATE` over the rows whose right bound moves.
async fn shift<M: NestedSet>(locks: &Locks, scope: &Scope<M>, position: i64, amount: i64) -> laravel::Result<()> {
    let (lft, rgt) = (M::lft_column().name(), M::rgt_column().name());
    let quoted = quote(locks.driver(), lft);
    // Only integers go into the SQL, so the expression can't carry anything else.
    let case = format!("CASE WHEN {quoted} >= {position} THEN {quoted} + ({amount}) ELSE {quoted} END");
    let values = Values::new()
        .set(lft, db::raw!(AssertSqlSafe(case)))
        .set(rgt, col(rgt) + amount);
    locks
        .update(scope, M::rgt_column().ge(position), untouched::<M>(values))
        .await
}

/// The node's stored depth, `0` when the model has no depth column.
fn stored_depth<M: NestedSet>(node: &M) -> i64 {
    M::depth_column().map_or(0, |column| *column.get(node))
}

/// Sets the depth column of a create, when the model has one.
fn with_depth<M: NestedSet>(create: CreateBuilder<M>, depth: i64) -> CreateBuilder<M> {
    match M::depth_column() {
        Some(column) => create.set(column, depth),
        None => create,
    }
}

/// Keeps `updated_at` as it is: moving bounds doesn't change the rows' content.
pub(crate) fn untouched<M: Model>(values: Values) -> Values {
    match M::META.updated_at {
        Some(stamp) => values.set(stamp.name, col(stamp.name)),
        None => values,
    }
}

/// Quotes a column name for `driver`.
pub(crate) fn quote(driver: Driver, name: &str) -> String {
    match driver {
        Driver::MySql | Driver::MariaDb => format!("`{}`", name.replace('`', "``")),
        _ => format!("\"{}\"", name.replace('"', "\"\"")),
    }
}