laravel-nestedset 0.2.1

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
//! 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, AnyTransaction, Driver, IntoExpr, Values, col};
use laravel::model::{__query, CreateBuilder, Model};

use crate::error::NestedSetError;
use crate::event::{TreeChange, changed};
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> {
    reload::<M>(key).await
}

/// Reads the node with `key` again, failing when it 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())).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 named = take_named_roots_lock::<M>(tx).await?;
            let result = place_new_root(tx, create).await;
            release_named_roots_lock::<M>(tx, named).await?;
            result
        })
        .await
}

async fn place_new_root<M: NestedSet>(tx: &mut AnyTransaction<'_>, create: CreateBuilder<M>) -> laravel::Result<M> {
    lock_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();
    lock_tree::<M>(tx, &scope).await?;
    // The last bound of a tree is its last root's: reading only roots uses the parent index.
    let last = scope
        .apply(__query::<M>())
        .filter(M::where_root() & M::META.key.ne(node.node_key().clone()))
        .max::<i64>(M::rgt_column())
        .await?
        .unwrap_or(0);
    // 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?;
    reload::<M>(node.node_key()).await
}

/// On MySQL and MariaDB, new roots take turns on a named lock: a tree without rows has nothing to
/// lock, and two new trees would deadlock on the same gap of the index. Returns whether it took
/// the lock. The lock goes with [`release_named_roots_lock`] before the transaction ends; the
/// rows the transaction wrote stay locked until it commits, so the next one waits for them.
async fn take_named_roots_lock<M: NestedSet>(tx: &mut AnyTransaction<'_>) -> laravel::Result<bool> {
    if !matches!(tx.driver(), Driver::MySql | Driver::MariaDb) {
        return Ok(false);
    }
    let name = format!("{}|roots", M::META.table);
    let locked: Option<i64> = db::query!(tx, "SELECT GET_LOCK({name}, 30)").scalar().await?;
    if locked != Some(1) {
        return Err(laravel::Error::msg(format!(
            "Timed out waiting for the lock on `{name}`."
        )));
    }
    Ok(true)
}

async fn release_named_roots_lock<M: NestedSet>(tx: &mut AnyTransaction<'_>, taken: bool) -> laravel::Result<()> {
    if taken {
        let name = format!("{}|roots", M::META.table);
        db::query!(tx, "SELECT RELEASE_LOCK({name})").select().await?;
    }
    Ok(())
}

/// 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 named = take_named_roots_lock::<M>(tx).await?;
            let result = insert_root(tx, &scope, create).await;
            release_named_roots_lock::<M>(tx, named).await?;
            result
        })
        .await
}

async fn insert_root<M: NestedSet>(
    tx: &mut AnyTransaction<'_>,
    scope: &Scope<M>,
    create: CreateBuilder<M>,
) -> laravel::Result<M> {
    lock_tree::<M>(tx, scope).await?;
    let last = scope
        .apply(__query::<M>())
        .filter(M::where_root())
        .lock_for_update()
        .max::<i64>(M::rgt_column())
        .await?
        .unwrap_or(0);
    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?;
    Ok(node)
}

/// 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| {
            lock_tree::<M>(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>(tx.driver(), &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?;
            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(async |tx| {
            if matches!(place, Place::Root) {
                lock_roots::<M>(tx).await?;
            }
            lock_tree::<M>(tx, &scope).await?;
            let fresh = reload::<M>(&key).await?;
            let (lft, rgt) = (fresh.lft(), fresh.rgt());

            let (position, parent, depth) = match &target_key {
                None => {
                    let last = scope
                        .apply(__query::<M>())
                        .filter(M::where_root())
                        .max::<i64>(M::rgt_column())
                        .await?;
                    (last.unwrap_or(0) + 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>(tx.driver(), &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();
                scope
                    .apply(__query::<M>())
                    .filter(M::lft_column().between(moved.lft(), moved.rgt()))
                    .update_values(untouched::<M>(Values::new().set(name, col(name) + shift)))
                    .await?;
                return reload::<M>(&key).await;
            }
            Ok(moved)
        })
        .await?;
    *node = fresh;
    Ok(())
}

/// 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(async |tx| {
            lock_tree::<M>(tx, &scope).await?;
            let fresh = reload::<M>(&key).await?;
            let (lft, rgt) = (fresh.lft(), fresh.rgt());
            let deleted = scope
                .apply(__query::<M>())
                .filter(M::lft_column().ge(lft) & M::rgt_column().le(rgt))
                .delete()
                .await?;
            shift::<M>(tx.driver(), &scope, rgt + 1, -(rgt - lft + 1)).await?;
            changed::<M>(TreeChange::Deleted, Some(&key)).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>(
    driver: Driver,
    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 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)));
    }
    scope
        .apply(__query::<M>())
        .filter(M::lft_column().between(low, high) | M::rgt_column().between(low, high))
        .update_values(untouched::<M>(values))
        .await?;
    Ok(())
}

/// 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>(driver: Driver, scope: &Scope<M>, position: i64, amount: i64) -> laravel::Result<()> {
    let (lft, rgt) = (M::lft_column().name(), M::rgt_column().name());
    let quoted = quote(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);
    scope
        .apply(__query::<M>())
        .filter(M::rgt_column().ge(position))
        .update_values(untouched::<M>(values))
        .await?;
    Ok(())
}

/// 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('"', "\"\"")),
    }
}

/// Makes every other root creation and move to root in the table wait until this transaction ends.
pub(crate) async fn lock_roots<M: NestedSet>(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
    match tx.driver() {
        Driver::Postgres => {
            let name = format!("{}|roots", M::META.table);
            db::query!(tx, "SELECT pg_advisory_xact_lock(hashtext({name}))")
                .select()
                .await?;
        }
        Driver::MySql | Driver::MariaDb => {
            __query::<M>()
                .filter(M::parent_column().is_null())
                .lock_for_update()
                .get()
                .await?;
        }
        Driver::Sqlite => take_write_lock::<M>().await?,
    }
    Ok(())
}

/// Makes every other write to the tree of `scope` wait until this transaction ends.
pub(crate) async fn lock_tree<M: NestedSet>(tx: &mut AnyTransaction<'_>, scope: &Scope<M>) -> laravel::Result<()> {
    match tx.driver() {
        Driver::Postgres => {
            let name = scope.lock_name();
            db::query!(tx, "SELECT pg_advisory_xact_lock(hashtext({name}))")
                .select()
                .await?;
        }
        Driver::MySql | Driver::MariaDb => {
            // Lock the tree's roots and, through the index's gap lock, the place a new root would
            // take.
            scope
                .apply(__query::<M>())
                .filter(M::parent_column().is_null())
                .lock_for_update()
                .get()
                .await?;
        }
        Driver::Sqlite => take_write_lock::<M>().await?,
    }
    Ok(())
}

/// SQLite has one writer at a time: take the write lock now, before reading any bound.
async fn take_write_lock<M: NestedSet>() -> laravel::Result<()> {
    let name = M::lft_column().name();
    __query::<M>()
        .filter(db::raw!("1 = 0"))
        .update_values(Values::new().set(name, col(name)))
        .await?;
    Ok(())
}