use std::future::Future;
use laravel::db::{Builder, IntoExpr, col};
use laravel::model::{__query, Column, CreateBuilder, Model};
use crate::check::{self, TreeReport};
use crate::ops::{self, NewPlace, Place};
use crate::scope::Scope;
use crate::tree::NewNode;
pub trait NestedSet: Model {
fn lft_column() -> Column<Self, i64>;
fn rgt_column() -> Column<Self, i64>;
fn parent_column() -> Column<Self, Option<Self::Key>>;
fn scope(&self) -> Scope<Self> {
Scope::new()
}
fn lft(&self) -> i64 {
*Self::lft_column().get(self)
}
fn rgt(&self) -> i64 {
*Self::rgt_column().get(self)
}
fn parent_key(&self) -> Option<&Self::Key> {
Self::parent_column().get(self).as_ref()
}
fn node_key(&self) -> &Self::Key {
Self::META.key.get(self)
}
fn is_root(&self) -> bool {
self.parent_key().is_none()
}
fn is_leaf(&self) -> bool {
self.rgt() - self.lft() == 1
}
fn descendant_count(&self) -> i64 {
(self.rgt() - self.lft() - 1) / 2
}
fn is_descendant_of(&self, other: &Self) -> bool {
self.lft() > other.lft() && self.rgt() < other.rgt()
}
fn is_ancestor_of(&self, other: &Self) -> bool {
other.is_descendant_of(self)
}
fn tree_query(&self) -> Builder<Self> {
self.scope().apply(__query::<Self>())
}
fn roots() -> Builder<Self> {
__query::<Self>()
.filter(Self::parent_column().is_null())
.order_by(Self::lft_column().asc())
}
fn children(&self) -> Builder<Self> {
self.tree_query()
.filter(Self::parent_column().eq(self.node_key().clone()))
.order_by(Self::lft_column().asc())
}
fn descendants(&self) -> Builder<Self> {
self.tree_query()
.filter(Self::lft_column().gt(self.lft()) & Self::rgt_column().lt(self.rgt()))
.order_by(Self::lft_column().asc())
}
fn descendants_and_self(&self) -> Builder<Self> {
self.tree_query()
.filter(Self::lft_column().ge(self.lft()) & Self::rgt_column().le(self.rgt()))
.order_by(Self::lft_column().asc())
}
fn ancestors(&self) -> Builder<Self> {
self.tree_query()
.filter(Self::lft_column().lt(self.lft()) & Self::rgt_column().gt(self.rgt()))
.order_by(Self::lft_column().asc())
}
fn ancestors_and_self(&self) -> Builder<Self> {
self.tree_query()
.filter(Self::lft_column().le(self.lft()) & Self::rgt_column().ge(self.rgt()))
.order_by(Self::lft_column().asc())
}
fn parent(&self) -> impl Future<Output = laravel::Result<Option<Self>>> + Send {
let query = self
.parent_key()
.map(|parent| self.tree_query().filter(Self::META.key.eq(parent.clone())));
async move {
match query {
Some(query) => query.first().await,
None => Ok(None),
}
}
}
fn depth(&self) -> impl Future<Output = laravel::Result<u64>> + Send {
self.ancestors().count()
}
fn siblings(&self) -> Builder<Self> {
let parent = match self.parent_key() {
Some(parent) => Self::parent_column().eq(parent.clone()),
None => Self::parent_column().is_null(),
};
self.tree_query()
.filter(parent & Self::META.key.ne(self.node_key().clone()))
.order_by(Self::lft_column().asc())
}
fn next_siblings(&self) -> Builder<Self> {
self.siblings().filter(Self::lft_column().gt(self.lft()))
}
fn prev_siblings(&self) -> Builder<Self> {
self.siblings().filter(Self::lft_column().lt(self.lft()))
}
fn next_sibling(&self) -> impl Future<Output = laravel::Result<Option<Self>>> + Send {
self.next_siblings().first()
}
fn prev_sibling(&self) -> impl Future<Output = laravel::Result<Option<Self>>> + Send {
let parent = match self.parent_key() {
Some(parent) => Self::parent_column().eq(parent.clone()),
None => Self::parent_column().is_null(),
};
self.tree_query()
.filter(parent & Self::lft_column().lt(self.lft()))
.order_by(Self::lft_column().desc())
.first()
}
fn is_child_of(&self, other: &Self) -> bool {
self.parent_key() == Some(other.node_key())
}
fn is_sibling_of(&self, other: &Self) -> bool {
self.parent_key() == other.parent_key() && self.node_key() != other.node_key()
}
fn default_order(query: Builder<Self>) -> Builder<Self> {
query.order_by(Self::lft_column().asc())
}
fn reversed(query: Builder<Self>) -> Builder<Self> {
query.order_by(Self::lft_column().desc())
}
fn leaves() -> Builder<Self> {
let (lft, rgt) = (Self::lft_column().name(), Self::rgt_column().name());
__query::<Self>().filter(col(rgt).eq(col(lft) + 1))
}
fn create_root(
create: impl Into<CreateBuilder<Self>> + Send,
) -> impl Future<Output = laravel::Result<Self>> + Send {
ops::create_root(create.into())
}
fn create_child(
&mut self,
create: impl Into<CreateBuilder<Self>> + Send,
) -> impl Future<Output = laravel::Result<Self>> + Send
where
Option<Self::Key>: IntoExpr,
{
ops::create_near(self, create.into(), NewPlace::LastChild)
}
fn create_first_child(
&mut self,
create: impl Into<CreateBuilder<Self>> + Send,
) -> impl Future<Output = laravel::Result<Self>> + Send
where
Option<Self::Key>: IntoExpr,
{
ops::create_near(self, create.into(), NewPlace::FirstChild)
}
fn create_before(
&mut self,
create: impl Into<CreateBuilder<Self>> + Send,
) -> impl Future<Output = laravel::Result<Self>> + Send
where
Option<Self::Key>: IntoExpr,
{
ops::create_near(self, create.into(), NewPlace::Before)
}
fn create_after(
&mut self,
create: impl Into<CreateBuilder<Self>> + Send,
) -> impl Future<Output = laravel::Result<Self>> + Send
where
Option<Self::Key>: IntoExpr,
{
ops::create_near(self, create.into(), NewPlace::After)
}
fn create_tree(tree: NewNode<Self>) -> impl Future<Output = laravel::Result<Self>> + Send
where
Option<Self::Key>: IntoExpr,
{
async move {
let mut root = ops::create_root(tree.create).await?;
create_children(&mut root, tree.children).await?;
Ok(root)
}
}
fn create_child_tree(&mut self, tree: NewNode<Self>) -> impl Future<Output = laravel::Result<Self>> + Send
where
Option<Self::Key>: IntoExpr,
{
async move {
let mut top = ops::create_near(self, tree.create, NewPlace::LastChild).await?;
create_children(&mut top, tree.children).await?;
*self = ops::reload_fresh(self).await?;
Ok(top)
}
}
fn make_root(&mut self) -> impl Future<Output = laravel::Result<()>> + Send
where
Option<Self::Key>: IntoExpr,
{
ops::move_node(self, None, Place::Root)
}
fn append_to(&mut self, parent: &Self) -> impl Future<Output = laravel::Result<()>> + Send
where
Option<Self::Key>: IntoExpr,
{
ops::move_node(self, Some(parent), Place::LastChild)
}
fn prepend_to(&mut self, parent: &Self) -> impl Future<Output = laravel::Result<()>> + Send
where
Option<Self::Key>: IntoExpr,
{
ops::move_node(self, Some(parent), Place::FirstChild)
}
fn insert_before(&mut self, neighbor: &Self) -> impl Future<Output = laravel::Result<()>> + Send
where
Option<Self::Key>: IntoExpr,
{
ops::move_node(self, Some(neighbor), Place::Before)
}
fn insert_after(&mut self, neighbor: &Self) -> impl Future<Output = laravel::Result<()>> + Send
where
Option<Self::Key>: IntoExpr,
{
ops::move_node(self, Some(neighbor), Place::After)
}
fn up(&mut self, by: u64) -> impl Future<Output = laravel::Result<bool>> + Send
where
Option<Self::Key>: IntoExpr,
{
async move {
if by == 0 {
return Ok(false);
}
let parent = match self.parent_key() {
Some(parent) => Self::parent_column().eq(parent.clone()),
None => Self::parent_column().is_null(),
};
let neighbor = self
.tree_query()
.filter(parent & Self::lft_column().lt(self.lft()))
.order_by(Self::lft_column().desc())
.offset(by - 1)
.first()
.await?;
match neighbor {
Some(neighbor) => self.insert_before(&neighbor).await.map(|()| true),
None => Ok(false),
}
}
}
fn down(&mut self, by: u64) -> impl Future<Output = laravel::Result<bool>> + Send
where
Option<Self::Key>: IntoExpr,
{
async move {
if by == 0 {
return Ok(false);
}
let neighbor = self.next_siblings().offset(by - 1).first().await?;
match neighbor {
Some(neighbor) => self.insert_after(&neighbor).await.map(|()| true),
None => Ok(false),
}
}
}
fn delete_subtree(self) -> impl Future<Output = laravel::Result<u64>> + Send {
async move { ops::delete_subtree(&self).await }
}
fn check_tree() -> impl Future<Output = laravel::Result<TreeReport<Self::Key>>> + Send {
check::check_tree::<Self>()
}
fn fix_tree() -> impl Future<Output = laravel::Result<u64>> + Send
where
Option<Self::Key>: IntoExpr,
{
check::fix_tree::<Self>()
}
}
async fn create_children<M: NestedSet>(parent: &mut M, children: Vec<NewNode<M>>) -> laravel::Result<()>
where
Option<M::Key>: IntoExpr,
{
let mut stack: Vec<(M, std::vec::IntoIter<NewNode<M>>)> = vec![(parent.clone(), children.into_iter())];
while let Some((top, pending)) = stack.last_mut() {
let Some(next) = pending.next() else {
stack.pop();
continue;
};
let child = ops::create_near(top, next.create, NewPlace::LastChild).await?;
stack.push((child, next.children.into_iter()));
}
*parent = ops::reload_fresh(parent).await?;
Ok(())
}