laravel-nestedset 0.3.0

Nested set trees for Laravel Rust models: fast subtree and ancestor queries, safe under concurrent writes.
Documentation
//! Ancestors through `parent_id`: a recursive query that reads one row per level, where the bounds
//! alone make the database scan every node to the left of the start.

use laravel::db::sqlx::AssertSqlSafe;
use laravel::db::{self, Condition, Driver, Value};
use laravel::model::Model;

use crate::node::NestedSet;
use crate::ops::{connection, quote};

/// What an integer column of a row holds.
enum Integer {
    Value(i64),
    Null,
}

/// What `node`'s `column` holds, or `None` when the column doesn't hold integers.
fn integer_value<M: Model>(node: &M, column: &str) -> Option<Integer> {
    let field = M::META.columns.iter().find(|field| field.name == column)?;
    let value = match (field.value)(node) {
        Value::BigInteger(value) => value,
        Value::Integer(value) => value.map(i64::from),
        Value::SmallInteger(value) => value.map(i64::from),
        Value::UnsignedInteger(Some(value)) => Some(i64::try_from(value).ok()?),
        Value::UnsignedInteger(None) => None,
        _ => return None,
    };
    Some(value.map_or(Integer::Null, Integer::Value))
}

/// The node's key, when it's an integer.
pub(crate) fn integer_key<M: NestedSet>(node: &M) -> Option<i64> {
    match integer_value(node, M::META.key.name())? {
        Integer::Value(key) => Some(key),
        Integer::Null => None,
    }
}

/// Where the chain of a node's ancestors starts.
pub(crate) enum ChainStart {
    /// At the node with this key.
    At(i64),
    /// Nowhere: a root has nothing above it.
    Nowhere,
}

/// Where the chain of `node`'s ancestors starts: its parent, or the node itself with
/// `include_self`. `None` when the keys aren't integers and the bounds have to do.
pub(crate) fn chain_start<M: NestedSet>(node: &M, include_self: bool) -> Option<ChainStart> {
    let key = integer_key(node)?;
    if include_self {
        return Some(ChainStart::At(key));
    }
    match integer_value(node, M::parent_column().name())? {
        Integer::Value(parent) => Some(ChainStart::At(parent)),
        Integer::Null => Some(ChainStart::Nowhere),
    }
}

/// The keys the chains that start at `starts` begin with.
pub(crate) fn chain_keys(starts: impl IntoIterator<Item = ChainStart>) -> Vec<i64> {
    starts
        .into_iter()
        .filter_map(|start| match start {
            ChainStart::At(key) => Some(key),
            ChainStart::Nowhere => None,
        })
        .collect()
}

/// Matches the nodes on the `parent_id` chains that start at `starts`, the starts included: one
/// index lookup per level. Only integers go into the SQL.
pub(crate) fn chain<M: NestedSet>(starts: &[i64]) -> Condition {
    if starts.is_empty() {
        return db::any(Vec::<Condition>::new());
    }
    let driver = connection::<M>().map_or(Driver::Postgres, |connection| connection.driver());
    let table = quote(driver, M::META.table);
    let key = quote(driver, M::META.key.name());
    let parent = quote(driver, M::parent_column().name());
    let starts = starts.iter().map(i64::to_string).collect::<Vec<_>>().join(", ");
    db::raw!(AssertSqlSafe(format!(
        "{table}.{key} IN (WITH RECURSIVE nested_chain (nested_key, nested_parent) AS (\
         SELECT {key}, {parent} FROM {table} WHERE {key} IN ({starts}) \
         UNION SELECT {table}.{key}, {table}.{parent} FROM {table} \
         JOIN nested_chain ON {table}.{key} = nested_chain.nested_parent) \
         SELECT nested_key FROM nested_chain)"
    )))
    .into()
}