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};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TreeReport<K> {
pub oddness: Vec<K>,
pub duplicates: Vec<K>,
pub wrong_parent: Vec<K>,
pub missing_parent: Vec<K>,
}
impl<K> TreeReport<K> {
#[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())
}
}
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)
}
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;
}
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
}
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;
let starts: Vec<usize> = tops.into_iter().chain(0..nodes.len()).collect();
for start in starts {
if visited[start] {
continue;
}
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
}