sea-orm-soft-delete 0.1.2

Soft deletes for SeaORM: trash, restore, prune, and queries that skip trashed rows
Documentation
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},
};

/// 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.
/// 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 {
        self.get(<Self::Entity as SoftDelete>::deleted_at_column())
            .is_some()
    }

    /// Moves the row to the trash and returns it as stored. A row already in the
    /// trash, even if this copy of it is out of date, keeps its `deleted_at` and runs
    /// no `after_soft_delete` hook.
    ///
    /// # 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, changed) = write_deleted_at(self, db, true).await?;
            if changed {
                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);
            }
            Ok(write_deleted_at(self, db, true).await?.0)
        }
    }

    /// Takes the row out of the trash and returns it as stored. A row that is not
    /// trashed, even if this copy of it is out of date, runs no `after_restore` hook.
    ///
    /// With [`unique_while_kept`](crate::unique_while_kept), restoring fails with a
    /// unique violation when a kept row has taken the value meanwhile.
    ///
    /// # 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, changed) = write_deleted_at(self, db, false).await?;
            if changed {
                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);
            }
            Ok(write_deleted_at(self, db, false).await?.0)
        }
    }

    /// 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?;
            if result.rows_affected > 0 {
                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
{
}

/// Trashes or restores the row if it is still in the other state; returns it as
/// stored and whether it changed. The state check is in the `UPDATE` itself, so an
/// out-of-date copy cannot overwrite `deleted_at` or run the after-hook twice.
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
}