sea-orm-soft-delete 0.1.0

Soft deletes for SeaORM: trash, restore, prune, and queries that skip trashed rows
Documentation
use std::future::Future;

use chrono::Utc;
use sea_orm::{
    ConnectionTrait, DbErr, DeleteResult, EntityTrait, FromQueryResult, ModelTrait, QueryFilter,
};

use crate::{
    entity::SoftDelete,
    row::{is_null, primary_key_condition, reload, set_deleted_at},
};

/// Trash operations on one row. Every `Model` of a [`SoftDelete`] entity gets them.
///
/// ```
/// # mod posts {
/// #     use sea_orm::entity::prelude::*;
/// #     #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
/// #     #[sea_orm(table_name = "posts")]
/// #     pub struct Model {
/// #         #[sea_orm(primary_key)]
/// #         pub id: i32,
/// #         pub category_id: i32,
/// #         pub slug: String,
/// #         pub deleted_at: Option<DateTimeWithTimeZone>,
/// #     }
/// #     #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
/// #     pub enum Relation {}
/// # }
/// # impl sea_orm::ActiveModelBehavior for posts::ActiveModel {}
/// # impl sea_orm_soft_delete::SoftDelete for posts::Entity {
/// #     fn deleted_at_column() -> Self::Column { posts::Column::DeletedAt }
/// # }
/// use sea_orm::{DatabaseConnection, DbErr};
/// use sea_orm_soft_delete::SoftDeleteModel;
///
/// async fn example(db: &DatabaseConnection, post: posts::Model) -> Result<(), DbErr> {
///     let post = post.soft_delete(db).await?;
///     assert!(post.is_trashed());
///     let post = post.restore(db).await?;
///     Ok(())
/// }
/// # fn main() {}
/// ```
///
/// The plain methods run the entity's hooks ([`SoftDelete::before_soft_delete`]
/// and friends); the `*_quietly` ones skip them, like Laravel's `deleteQuietly`.
/// Pass a `DatabaseTransaction` as `db` to make hooks and the change atomic.
pub trait SoftDeleteModel:
    ModelTrait<Entity: SoftDelete<Model = Self>> + FromQueryResult + Send + Sync
{
    /// Whether the row is in the trash.
    fn is_trashed(&self) -> bool {
        !is_null(&self.get(<Self::Entity as SoftDelete>::deleted_at_column()))
    }

    /// Moves the row to the trash and returns it as stored. A row already in the
    /// trash is returned unchanged, keeps its `deleted_at` and runs no hooks.
    ///
    /// # Errors
    ///
    /// When a query fails, the row no longer exists, or a hook returns an error.
    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 = write_deleted_at(self, db, true).await?;
            Self::Entity::after_soft_delete(&model, db).await?;
            Ok(model)
        }
    }

    /// [`soft_delete`](Self::soft_delete) without hooks.
    ///
    /// # Errors
    ///
    /// When a query fails or the row no longer exists.
    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);
            }
            write_deleted_at(self, db, true).await
        }
    }

    /// Takes the row out of the trash and returns it as stored. A row that is
    /// not trashed is returned unchanged and runs no hooks.
    ///
    /// # Errors
    ///
    /// When a query fails, the row no longer exists, or a hook returns an error.
    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 = write_deleted_at(self, db, false).await?;
            Self::Entity::after_restore(&model, db).await?;
            Ok(model)
        }
    }

    /// [`restore`](Self::restore) without hooks.
    ///
    /// # Errors
    ///
    /// When a query fails or the row no longer exists.
    fn restore_quietly<C: ConnectionTrait>(
        self,
        db: &C,
    ) -> impl Future<Output = Result<Self, DbErr>> + Send {
        async move {
            if !self.is_trashed() {
                return Ok(self);
            }
            write_deleted_at(self, db, false).await
        }
    }

    /// Deletes the row for good, trashed or not. It bypasses `ActiveModelBehavior`,
    /// so it still works when [`deny_hard_delete`](crate::deny_hard_delete) guards
    /// the plain `delete`.
    ///
    /// # Errors
    ///
    /// When the query fails or a hook returns an error.
    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?;
            Self::Entity::after_force_delete(&self, db).await?;
            Ok(result)
        }
    }

    /// [`force_delete`](Self::force_delete) without hooks.
    ///
    /// # Errors
    ///
    /// When the query fails.
    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, DbErr>
where
    M: SoftDeleteModel,
    C: ConnectionTrait,
{
    let row = primary_key_condition(&model);
    set_deleted_at(M::Entity::update_many(), Utc::now(), trashed)
        .filter(row.clone())
        .exec(db)
        .await?;
    reload(db, row).await
}

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
}