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::{Duration, Utc};
use sea_orm::{
    ColumnTrait, Condition, ConnectionTrait, DbErr, EntityTrait, FromQueryResult, PaginatorTrait,
    QueryFilter, QuerySelect, Select,
};

use crate::{
    query::TrashedQuery,
    row::{primary_key_condition, set_deleted_at},
};

/// How many rows [`SoftDelete::prune_trashed`] loads at a time.
const PRUNE_CHUNK: u64 = 500;

/// Marks an entity as soft-deletable and adds table-wide trash operations.
///
/// The column must be a nullable timestamp, preferably with a time zone
/// (`timestamp with time zone` in Postgres). [`deleted_at_column`](crate::deleted_at_column)
/// builds it in a migration.
///
/// The `before_*` / `after_*` hooks mirror Laravel's model events (`deleting` /
/// `trashed`, `restoring` / `restored`, `forceDeleting` / `forceDeleted`). They run
/// for single rows: [`SoftDeleteModel`](crate::SoftDeleteModel) methods and
/// [`prune_trashed`](Self::prune_trashed), but not for the `*_quietly` methods or
/// bulk operations. An error from a `before_*` hook cancels the operation.
pub trait SoftDelete: EntityTrait<Model: FromQueryResult + Sync> {
    /// The `deleted_at` column: `NULL` while the row is kept, a timestamp once trashed.
    fn deleted_at_column() -> Self::Column;

    /// An `updated_at` column to set together with `deleted_at` on trash and
    /// restore, as Laravel does. Default: none.
    #[must_use]
    fn updated_at_column() -> Option<Self::Column> {
        None
    }

    /// Runs before a row goes to the trash. Return an error to keep it.
    fn before_soft_delete<C: ConnectionTrait>(
        _model: &Self::Model,
        _db: &C,
    ) -> impl Future<Output = Result<(), DbErr>> + Send {
        async { Ok(()) }
    }

    /// Runs after a row went to the trash; gets the row as stored.
    fn after_soft_delete<C: ConnectionTrait>(
        _model: &Self::Model,
        _db: &C,
    ) -> impl Future<Output = Result<(), DbErr>> + Send {
        async { Ok(()) }
    }

    /// Runs before a row leaves the trash. Return an error to keep it trashed.
    fn before_restore<C: ConnectionTrait>(
        _model: &Self::Model,
        _db: &C,
    ) -> impl Future<Output = Result<(), DbErr>> + Send {
        async { Ok(()) }
    }

    /// Runs after a row left the trash; gets the row as stored.
    fn after_restore<C: ConnectionTrait>(
        _model: &Self::Model,
        _db: &C,
    ) -> impl Future<Output = Result<(), DbErr>> + Send {
        async { Ok(()) }
    }

    /// Runs before a row is deleted for good, e.g. to remove its files.
    /// Return an error to keep it.
    fn before_force_delete<C: ConnectionTrait>(
        _model: &Self::Model,
        _db: &C,
    ) -> impl Future<Output = Result<(), DbErr>> + Send {
        async { Ok(()) }
    }

    /// Runs after a row was deleted for good.
    fn after_force_delete<C: ConnectionTrait>(
        _model: &Self::Model,
        _db: &C,
    ) -> impl Future<Output = Result<(), DbErr>> + Send {
        async { Ok(()) }
    }

    /// `find()` without trashed rows: what most queries want.
    #[must_use]
    fn find_without_trashed() -> Select<Self> {
        Self::find().without_trashed()
    }

    /// `find()` limited to trashed rows, e.g. for a trash view.
    #[must_use]
    fn find_only_trashed() -> Select<Self> {
        Self::find().only_trashed()
    }

    /// Moves every kept row matching `condition` to the trash in one query and
    /// returns how many moved. Rows already trashed keep their `deleted_at`.
    /// No hooks run, as with Laravel's mass deletes.
    ///
    /// # Errors
    ///
    /// When the database query fails.
    fn soft_delete_many<C: ConnectionTrait>(
        db: &C,
        condition: Condition,
    ) -> impl Future<Output = Result<u64, DbErr>> + Send {
        async move {
            let result = set_deleted_at(Self::update_many(), Utc::now(), true)
                .filter(condition)
                .filter(Self::deleted_at_column().is_null())
                .exec(db)
                .await?;
            Ok(result.rows_affected)
        }
    }

    /// Restores every trashed row matching `condition` in one query and returns
    /// how many came back. No hooks run.
    ///
    /// # Errors
    ///
    /// When the database query fails.
    fn restore_many<C: ConnectionTrait>(
        db: &C,
        condition: Condition,
    ) -> impl Future<Output = Result<u64, DbErr>> + Send {
        async move {
            let result = set_deleted_at(Self::update_many(), Utc::now(), false)
                .filter(condition)
                .filter(Self::deleted_at_column().is_not_null())
                .exec(db)
                .await?;
            Ok(result.rows_affected)
        }
    }

    /// How many rows [`prune_trashed`](Self::prune_trashed) would delete now,
    /// like `model:prune --pretend`.
    ///
    /// # Errors
    ///
    /// When the database query fails.
    fn count_prunable<C: ConnectionTrait>(
        db: &C,
        older_than: Duration,
    ) -> impl Future<Output = Result<u64, DbErr>> + Send {
        async move { prunable::<Self>(older_than).count(db).await }
    }

    /// Deletes for good every row trashed longer than `older_than` ago, one row at
    /// a time with the force-delete hooks, like Laravel's `Prunable`. Returns how
    /// many rows were removed. Use [`mass_prune_trashed`](Self::mass_prune_trashed)
    /// when no hook needs to run.
    ///
    /// # Errors
    ///
    /// When a query fails or a `before_force_delete` hook refuses; rows removed
    /// before that stay removed.
    fn prune_trashed<C: ConnectionTrait>(
        db: &C,
        older_than: Duration,
    ) -> impl Future<Output = Result<u64, DbErr>> + Send {
        async move {
            let cutoff = older_than;
            let mut removed = 0;
            loop {
                let rows = prunable::<Self>(cutoff).limit(PRUNE_CHUNK).all(db).await?;
                if rows.is_empty() {
                    return Ok(removed);
                }
                for row in rows {
                    Self::before_force_delete(&row, db).await?;
                    Self::delete_many()
                        .filter(primary_key_condition(&row))
                        .exec(db)
                        .await?;
                    Self::after_force_delete(&row, db).await?;
                    removed += 1;
                }
            }
        }
    }

    /// Deletes for good every row trashed longer than `older_than` ago in one
    /// query, like Laravel's `MassPrunable`. No hooks run.
    ///
    /// # Errors
    ///
    /// When the database query fails.
    fn mass_prune_trashed<C: ConnectionTrait>(
        db: &C,
        older_than: Duration,
    ) -> impl Future<Output = Result<u64, DbErr>> + Send {
        async move {
            let result = Self::delete_many()
                .filter(Self::deleted_at_column().lt(Utc::now() - older_than))
                .exec(db)
                .await?;
            Ok(result.rows_affected)
        }
    }
}

/// Trashed rows older than `older_than`.
fn prunable<E: SoftDelete>(older_than: Duration) -> Select<E> {
    E::find().filter(E::deleted_at_column().lt(Utc::now() - older_than))
}