laravel-nestedset 0.1.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)]
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>,
}

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())
    }
}

/// 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(),
    };
    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());
        }
        match node.parent_key() {
            Some(parent) if !keys.contains(parent) => report.missing_parent.push(key.clone()),
            parent => {
                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());
                if !odd && around != parent {
                    report.wrong_parent.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?;
                for (node, lft, rgt, parent) in rebuild(tree) {
                    if (lft, rgt, parent.as_ref()) == (node.lft(), node.rgt(), node.parent_key()) {
                        continue;
                    }
                    let values = Values::new()
                        .set(M::lft_column().name(), lft)
                        .set(M::rgt_column().name(), rgt)
                        .set(M::parent_column().name(), parent);
                    __query::<M>()
                        .filter(M::META.key.eq(node.node_key().clone()))
                        .update_values(untouched::<M>(values))
                        .await?;
                    fixed += 1;
                }
            }
            Ok(fixed)
        })
        .await
}

/// 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<M: NestedSet>(nodes: &[M]) -> Vec<(&M, i64, i64, Option<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, node) in nodes.iter().enumerate() {
        match node.parent_key().and_then(|parent| positions.get(parent)) {
            Some(&parent) => children.entry(parent).or_default().push(index),
            None => 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> = 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());
                result.push((&nodes[index], lfts[&index], bound, parent_key));
                continue;
            }
            if visited[index] {
                continue;
            }
            visited[index] = true;
            bound += 1;
            lfts.insert(index, bound);
            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
}