use std::collections::{HashMap, HashSet};
use std::future::Future;
use laravel::db::{self, Condition, IntoCondition, col};
use laravel::model::{__query, Column, Model};
use serde::Serialize;
use crate::node::NestedSet;
use crate::tree::{IntoTree, TreeNode};
const CHUNK: usize = 200;
#[derive(Debug, Clone, Serialize)]
pub struct WithAncestors<M> {
#[serde(flatten)]
pub node: M,
pub ancestors: Vec<M>,
}
#[derive(Debug, Clone, Serialize)]
pub struct WithCount<M> {
#[serde(flatten)]
pub node: M,
pub count: u64,
}
pub trait LoadRelatives<M> {
fn with_ancestors(self) -> impl Future<Output = laravel::Result<Vec<WithAncestors<M>>>> + Send;
fn with_descendants(self) -> impl Future<Output = laravel::Result<Vec<TreeNode<M>>>> + Send;
fn with_subtree_counts<R, T>(
self,
foreign_key: Column<R, T>,
) -> impl Future<Output = laravel::Result<Vec<WithCount<M>>>> + Send
where
R: Model,
T: Send + Sync + 'static;
fn with_subtree_counts_where<R, T>(
self,
foreign_key: Column<R, T>,
filter: impl IntoCondition + Send,
) -> impl Future<Output = laravel::Result<Vec<WithCount<M>>>> + Send
where
R: Model,
T: Send + Sync + 'static;
}
impl<M: NestedSet> LoadRelatives<M> for Vec<M> {
async fn with_subtree_counts<R, T>(self, foreign_key: Column<R, T>) -> laravel::Result<Vec<WithCount<M>>>
where
R: Model,
T: Send + Sync + 'static,
{
self.with_subtree_counts_where(foreign_key, None::<Condition>).await
}
async fn with_subtree_counts_where<R, T>(
self,
foreign_key: Column<R, T>,
filter: impl IntoCondition + Send,
) -> laravel::Result<Vec<WithCount<M>>>
where
R: Model,
T: Send + Sync + 'static,
{
let filter = db::all([filter]);
let counts = subtree_counts(&self, foreign_key, filter).await?;
Ok(self
.into_iter()
.map(|node| {
let count = counts.get(node.node_key()).copied().unwrap_or(0);
WithCount { node, count }
})
.collect())
}
async fn with_ancestors(self) -> laravel::Result<Vec<WithAncestors<M>>> {
let starts: Option<Vec<crate::chain::ChainStart>> =
self.iter().map(|node| crate::chain::chain_start(node, false)).collect();
let found = match starts {
Some(starts) => {
let starts = crate::chain::chain_keys(starts);
__query::<M>()
.filter(crate::chain::chain::<M>(&starts))
.order_by(M::lft_column().asc())
.get()
.await?
}
None => load(&self, M::where_ancestor_of).await?,
};
Ok(self
.into_iter()
.map(|node| {
let ancestors = found
.iter()
.filter(|&candidate| same_tree(candidate, &node) && node.is_descendant_of(candidate))
.cloned()
.collect();
WithAncestors { node, ancestors }
})
.collect())
}
async fn with_descendants(self) -> laravel::Result<Vec<TreeNode<M>>> {
let found = load(&self, M::where_descendant_of).await?;
Ok(self
.into_iter()
.map(|node| {
let below = found
.iter()
.filter(|&candidate| same_tree(candidate, &node) && candidate.is_descendant_of(&node));
let subtree: Vec<M> = std::iter::once(node.clone()).chain(below.cloned()).collect();
subtree
.into_tree()
.into_iter()
.next()
.expect("the node tops its own subtree")
})
.collect())
}
}
async fn load<M: NestedSet>(nodes: &[M], relation: fn(&M) -> db::Condition) -> laravel::Result<Vec<M>> {
let mut found = Vec::new();
for chunk in nodes.chunks(CHUNK) {
let rows = __query::<M>()
.filter(db::any(chunk.iter().map(relation)))
.order_by(M::lft_column().asc())
.get()
.await?;
found.extend(rows);
}
let mut seen = HashSet::new();
found.retain(|node| seen.insert(node.node_key().clone()));
found.sort_by_key(NestedSet::lft);
Ok(found)
}
async fn subtree_counts<M: NestedSet, R: Model, T>(
nodes: &[M],
foreign_key: Column<R, T>,
filter: Condition,
) -> laravel::Result<HashMap<M::Key, u64>> {
let Some(first) = nodes.first() else {
return Ok(HashMap::new());
};
let (table, key) = (M::META.table, M::META.key.name());
let (lft, rgt) = (M::lft_column().name(), M::rgt_column().name());
let node = |column: &str| col(format!("nested_node.{column}"));
let below = |column: &str| col(format!("nested_below.{column}"));
let mut subtree = below(lft).ge(node(lft)) & below(lft).le(node(rgt));
for name in first.scope().names() {
subtree &= below(name).eq(node(name));
}
let related = R::META.table;
let points_below = col(format!("{related}.{}", foreign_key.name())).eq(below(key));
let mut counts = HashMap::new();
for chunk in nodes.chunks(CHUNK) {
let keys: Vec<M::Key> = chunk.iter().map(|node| node.node_key().clone()).collect();
let mut query = db::table(format!("{table} as nested_node"));
if let Some(connection) = M::META.connection {
query = query.connection(connection);
}
let rows = query
.join(format!("{table} as nested_below"), subtree.clone())
.join(related, points_below.clone())
.filter(node(key).is_in(keys) & filter.clone())
.select((node(key).alias("node_key"), col("*").count().alias("total")))
.group_by([format!("nested_node.{key}")])
.get::<(M::Key, i64)>()
.await?;
counts.extend(
rows.into_iter()
.map(|(key, total)| (key, u64::try_from(total).unwrap_or(0))),
);
}
Ok(counts)
}
fn same_tree<M: NestedSet>(a: &M, b: &M) -> bool {
a.scope().lock_name() == b.scope().lock_name()
}