use std::future::Future;
use chrono::Utc;
use sea_orm::{
ColumnTrait, ConnectionTrait, DbErr, DeleteResult, EntityTrait, FromQueryResult, ModelTrait,
QueryFilter,
};
use crate::{
entity::SoftDelete,
row::{primary_key_condition, reload, set_deleted_at},
};
pub trait SoftDeleteModel:
ModelTrait<Entity: SoftDelete<Model = Self>> + FromQueryResult + Send + Sync
{
fn is_trashed(&self) -> bool {
self.get(<Self::Entity as SoftDelete>::deleted_at_column())
.is_some()
}
fn soft_delete<C: ConnectionTrait>(
self,
db: &C,
) -> impl Future<Output = Result<Self, DbErr>> + Send {
async move {
if self.is_trashed() {
return Ok(self);
}
Self::Entity::before_soft_delete(&self, db).await?;
let (model, changed) = write_deleted_at(self, db, true).await?;
if changed {
Self::Entity::after_soft_delete(&model, db).await?;
}
Ok(model)
}
}
fn soft_delete_quietly<C: ConnectionTrait>(
self,
db: &C,
) -> impl Future<Output = Result<Self, DbErr>> + Send {
async move {
if self.is_trashed() {
return Ok(self);
}
Ok(write_deleted_at(self, db, true).await?.0)
}
}
fn restore<C: ConnectionTrait>(
self,
db: &C,
) -> impl Future<Output = Result<Self, DbErr>> + Send {
async move {
if !self.is_trashed() {
return Ok(self);
}
Self::Entity::before_restore(&self, db).await?;
let (model, changed) = write_deleted_at(self, db, false).await?;
if changed {
Self::Entity::after_restore(&model, db).await?;
}
Ok(model)
}
}
fn restore_quietly<C: ConnectionTrait>(
self,
db: &C,
) -> impl Future<Output = Result<Self, DbErr>> + Send {
async move {
if !self.is_trashed() {
return Ok(self);
}
Ok(write_deleted_at(self, db, false).await?.0)
}
}
fn force_delete<C: ConnectionTrait>(
self,
db: &C,
) -> impl Future<Output = Result<DeleteResult, DbErr>> + Send {
async move {
Self::Entity::before_force_delete(&self, db).await?;
let result = delete_row(&self, db).await?;
if result.rows_affected > 0 {
Self::Entity::after_force_delete(&self, db).await?;
}
Ok(result)
}
}
fn force_delete_quietly<C: ConnectionTrait>(
self,
db: &C,
) -> impl Future<Output = Result<DeleteResult, DbErr>> + Send {
async move { delete_row(&self, db).await }
}
}
impl<M> SoftDeleteModel for M where
M: ModelTrait<Entity: SoftDelete<Model = M>> + FromQueryResult + Send + Sync
{
}
async fn write_deleted_at<M, C>(model: M, db: &C, trashed: bool) -> Result<(M, bool), DbErr>
where
M: SoftDeleteModel,
C: ConnectionTrait,
{
let row = primary_key_condition(&model);
let column = <M::Entity as SoftDelete>::deleted_at_column();
let still_other_state = if trashed {
column.is_null()
} else {
column.is_not_null()
};
let result = set_deleted_at(M::Entity::update_many(), Utc::now(), trashed)
.filter(row.clone())
.filter(still_other_state)
.exec(db)
.await?;
Ok((reload(db, row).await?, result.rows_affected > 0))
}
async fn delete_row<M, C>(model: &M, db: &C) -> Result<DeleteResult, DbErr>
where
M: SoftDeleteModel,
C: ConnectionTrait,
{
M::Entity::delete_many()
.filter(primary_key_condition(model))
.exec(db)
.await
}