laravel-nestedset 0.2.0

Nested set trees for Laravel Rust models: fast subtree and ancestor queries, safe under concurrent writes.
Documentation
//! Checking a table's trees for broken bounds and rebuilding the bounds from `parent_id`.

use std::collections::{HashMap, HashSet};

use laravel::db::{IntoExpr, Values};
use laravel::model::__query;

use crate::node::NestedSet;
use crate::ops::{connection, lock_roots, lock_tree, untouched};

/// What [`NestedSet::check_tree`] found: the keys of the broken nodes, by kind of damage.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct TreeReport<K> {
    /// Nodes whose bounds can't be right: `lft` below 1, `lft >= rgt`, or an even width.
    pub oddness: Vec<K>,
    /// Nodes that share a bound with another node of their tree.
    pub duplicates: Vec<K>,
    /// Nodes whose `parent_id` isn't the nearest node around them.
    pub wrong_parent: Vec<K>,
    /// Nodes whose `parent_id` names a row that isn't in their tree.
    pub missing_parent: Vec<K>,
    /// Nodes whose stored depth doesn't match their place, when the model has a
    /// [`depth_column`](NestedSet::depth_column).
    pub wrong_depth: Vec<K>,
}

impl<K> TreeReport<K> {
    /// Whether any node is broken.
    #[must_use]
    pub fn is_broken(&self) -> bool {
        !(self.oddness.is_empty()
            && self.duplicates.is_empty()
            && self.wrong_parent.is_empty()
            && self.missing_parent.is_empty()
            && self.wrong_depth.is_empty())
    }
}

/// Splits the table's rows into their trees, each in bound order.
async fn trees<M: NestedSet>() -> laravel::Result<Vec<Vec<M>>> {
    let rows = __query::<M>()
        .order_by(M::lft_column().asc())
        .order_by(M::META.key.asc())
        .get()
        .await?;
    let mut order: Vec<String> = Vec::new();
    let mut trees: HashMap<String, Vec<M>> = HashMap::new();
    for row in rows {
        let name = row.scope().lock_name();
        if !trees.contains_key(&name) {
            order.push(name.clone());
        }
        trees.entry(name).or_default().push(row);
    }
    Ok(order.into_iter().filter_map(|name| trees.remove(&name)).collect())
}

pub(crate) async fn check_tree<M: NestedSet>() -> laravel::Result<TreeReport<M::Key>> {
    let mut report = TreeReport {
        oddness: Vec::new(),
        duplicates: Vec::new(),
        wrong_parent: Vec::new(),
        missing_parent: Vec::new(),
        wrong_depth: Vec::new(),
    };
    for tree in trees::<M>().await? {
        check(&tree, &mut report);
    }
    Ok(report)
}

/// Checks one tree, whose nodes are in bound order.
fn check<M: NestedSet>(nodes: &[M], report: &mut TreeReport<M::Key>) {
    let keys: HashSet<&M::Key> = nodes.iter().map(NestedSet::node_key).collect();
    let mut seen: HashMap<i64, usize> = HashMap::new();
    for node in nodes {
        *seen.entry(node.lft()).or_default() += 1;
        *seen.entry(node.rgt()).or_default() += 1;
    }

    // The nodes still open around the current one, innermost last.
    let mut open: Vec<&M> = Vec::new();
    for node in nodes {
        let key = node.node_key();
        let odd = node.lft() < 1 || node.lft() >= node.rgt() || (node.rgt() - node.lft()) % 2 == 0;
        if odd {
            report.oddness.push(key.clone());
        }
        if seen[&node.lft()] > 1 || seen[&node.rgt()] > 1 {
            report.duplicates.push(key.clone());
        }
        while open.last().is_some_and(|around| around.rgt() < node.lft()) {
            open.pop();
        }
        let around = open
            .last()
            .filter(|around| around.rgt() > node.rgt())
            .map(|around| around.node_key());
        match node.parent_key() {
            Some(parent) if !keys.contains(parent) => report.missing_parent.push(key.clone()),
            parent if !odd && around != parent => report.wrong_parent.push(key.clone()),
            _ => {}
        }
        if let Some(column) = M::depth_column() {
            let depth = open.iter().filter(|around| around.rgt() > node.rgt()).count();
            if !odd && usize::try_from(*column.get(node)).ok() != Some(depth) {
                report.wrong_depth.push(key.clone());
            }
        }
        if !odd {
            open.push(node);
        }
    }
}

pub(crate) async fn fix_tree<M: NestedSet>() -> laravel::Result<u64>
where
    Option<M::Key>: IntoExpr,
{
    connection::<M>()?
        .transaction(async |tx| {
            lock_roots::<M>(tx).await?;
            let trees = trees::<M>().await?;
            let mut fixed = 0;
            for tree in &trees {
                lock_tree::<M>(tx, &tree[0].scope()).await?;
                let parents: Vec<Option<M::Key>> = tree.iter().map(|node| node.parent_key().cloned()).collect();
                fixed += write_rebuilt(tree, &parents).await?;
            }
            Ok(fixed)
        })
        .await
}

/// Writes the bounds, parent, and depth [`rebuild`] works out for one tree to the rows that
/// differ, and returns how many it changed. `parents[i]` is the parent `nodes[i]` should have;
/// siblings keep the order of `nodes`.
pub(crate) async fn write_rebuilt<M: NestedSet>(nodes: &[M], parents: &[Option<M::Key>]) -> laravel::Result<u64>
where
    Option<M::Key>: IntoExpr,
{
    let mut changed = 0;
    for (node, rebuilt) in rebuild(nodes, parents) {
        let depth = M::depth_column().map(|column| (column, rebuilt.depth));
        let same = (rebuilt.lft, rebuilt.rgt, rebuilt.parent.as_ref()) == (node.lft(), node.rgt(), node.parent_key())
            && depth.is_none_or(|(column, depth)| *column.get(node) == depth);
        if same {
            continue;
        }
        let mut values = Values::new()
            .set(M::lft_column().name(), rebuilt.lft)
            .set(M::rgt_column().name(), rebuilt.rgt)
            .set(M::parent_column().name(), rebuilt.parent);
        if let Some((column, depth)) = depth {
            values = values.set(column.name(), depth);
        }
        __query::<M>()
            .filter(M::META.key.eq(node.node_key().clone()))
            .update_values(untouched::<M>(values))
            .await?;
        changed += 1;
    }
    Ok(changed)
}

/// Where a node belongs, as [`rebuild`] works it out.
struct Rebuilt<K> {
    lft: i64,
    rgt: i64,
    depth: i64,
    parent: Option<K>,
}

/// The bounds and parent each node of one tree should have, from `parent_id`. Siblings keep their
/// current order. A node whose parent is missing, or that sits in a `parent_id` cycle, becomes a
/// root.
fn rebuild<'a, M: NestedSet>(nodes: &'a [M], parents: &[Option<M::Key>]) -> Vec<(&'a M, Rebuilt<M::Key>)> {
    let positions: HashMap<&M::Key, usize> = nodes
        .iter()
        .enumerate()
        .map(|(index, node)| (node.node_key(), index))
        .collect();
    let mut children: HashMap<usize, Vec<usize>> = HashMap::new();
    let mut tops = Vec::new();
    for (index, parent) in parents.iter().enumerate() {
        match parent.as_ref().and_then(|parent| positions.get(parent)) {
            Some(&parent) if parent != index => children.entry(parent).or_default().push(index),
            _ => tops.push(index),
        }
    }

    let mut result = Vec::with_capacity(nodes.len());
    let mut visited = vec![false; nodes.len()];
    let mut bound = 0;
    // Nodes no top reaches sit in a cycle: each one left over starts a tree of its own.
    let starts: Vec<usize> = tops.into_iter().chain(0..nodes.len()).collect();
    for start in starts {
        if visited[start] {
            continue;
        }
        // Depth-first: (node, parent, whether its children are done).
        let mut stack = vec![(start, None::<usize>, false)];
        let mut lfts: HashMap<usize, (i64, i64)> = HashMap::new();
        while let Some((index, parent, done)) = stack.pop() {
            if done {
                bound += 1;
                let parent_key = parent.map(|parent| nodes[parent].node_key().clone());
                let (lft, depth) = lfts[&index];
                result.push((
                    &nodes[index],
                    Rebuilt {
                        lft,
                        rgt: bound,
                        depth,
                        parent: parent_key,
                    },
                ));
                continue;
            }
            if visited[index] {
                continue;
            }
            visited[index] = true;
            bound += 1;
            let depth = parent.map_or(0, |parent| lfts[&parent].1 + 1);
            lfts.insert(index, (bound, depth));
            stack.push((index, parent, true));
            if let Some(below) = children.get(&index) {
                for &child in below.iter().rev() {
                    if !visited[child] {
                        stack.push((child, Some(index), false));
                    }
                }
            }
        }
    }
    result
}