laravel-nestedset 0.1.0

Nested set trees for Laravel Rust models: fast subtree and ancestor queries, safe under concurrent writes.
Documentation
//! 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, UpdateBuilder};

use crate::error::NestedSetError;
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` 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.
            lock_roots::<M>(tx).await?;
            let mut node = create.set(M::lft_column(), 0).set(M::rgt_column(), 0).await?;
            let scope = node.scope();
            lock_tree::<M>(tx, &scope).await?;
            let last = scope
                .apply(__query::<M>())
                .filter(M::META.key.ne(node.node_key().clone()))
                .max::<i64>(M::rgt_column())
                .await?
                .unwrap_or(0);
            UpdateBuilder::new(&mut node)
                .set(M::lft_column(), last + 1)
                .set(M::rgt_column(), last + 2)
                .await?;
            Ok(node)
        })
        .await
}

/// 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()),
            };
            shift::<M>(&scope, position, 2).await?;
            let node = scope
                .fill(create)
                .set(M::lft_column(), position)
                .set(M::rgt_column(), position + 1)
                .set(M::parent_column(), parent)
                .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) = match &target_key {
                None => {
                    let last = scope.apply(__query::<M>()).max::<i64>(M::rgt_column()).await?;
                    (last.unwrap_or(0) + 1, None)
                }
                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());
                    }
                    match place {
                        Place::FirstChild => (target.lft() + 1, Some(target_key.clone())),
                        Place::LastChild => (target.rgt(), Some(target_key.clone())),
                        Place::Before => (target.lft(), target.parent_key().cloned()),
                        Place::After | Place::Root => (target.rgt() + 1, target.parent_key().cloned()),
                    }
                }
            };

            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?;
            }
            reload::<M>(&key).await
        })
        .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>(&scope, rgt + 1, -(rgt - lft + 1)).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.
async fn shift<M: NestedSet>(scope: &Scope<M>, position: i64, amount: i64) -> laravel::Result<()> {
    for column in [M::rgt_column(), M::lft_column()] {
        let name = column.name();
        scope
            .apply(__query::<M>())
            .filter(column.ge(position))
            .update_values(untouched::<M>(Values::new().set(name, col(name) + amount)))
            .await?;
    }
    Ok(())
}

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