sea-orm-soft-delete 0.1.2

Soft deletes for SeaORM: trash, restore, prune, and queries that skip trashed rows
Documentation
//! Small building blocks shared by the entity and model operations.

use chrono::{DateTime, Utc};
use sea_orm::{
    sea_query::{ColumnType, Expr},
    ColumnTrait, Condition, ConnectionTrait, DbErr, EntityTrait, FromQueryResult, Iterable,
    ModelTrait, PrimaryKeyToColumn, QueryFilter, UpdateMany, Value,
};

use crate::entity::SoftDelete;

/// `WHERE pk = <this row's pk>`, for any primary key shape.
pub fn primary_key_condition<M: ModelTrait>(model: &M) -> Condition {
    <<M::Entity as EntityTrait>::PrimaryKey as Iterable>::iter().fold(
        Condition::all(),
        |condition, key| {
            let column = key.into_column();
            condition.add(column.eq(model.get(column)))
        },
    )
}

/// Sets `deleted_at` (to `now`, or `NULL` when `trashed` is false) and, when the
/// entity has one, `updated_at`.
pub fn set_deleted_at<E: SoftDelete>(
    update: UpdateMany<E>,
    now: DateTime<Utc>,
    trashed: bool,
) -> UpdateMany<E> {
    let deleted_at = E::deleted_at_column();
    let value = if trashed {
        timestamp(deleted_at, now)
    } else {
        timestamp(deleted_at, now).as_null()
    };
    let update = update.col_expr(deleted_at, Expr::value(value));
    match E::updated_at_column() {
        Some(column) => update.col_expr(column, Expr::value(timestamp(column, now))),
        None => update,
    }
}

/// `at` as a value of the type `column` stores: a naive UTC timestamp for
/// `timestamp without time zone`, so Postgres does not shift it by the session's time
/// zone, and a UTC timestamp for anything else.
pub fn timestamp<C: ColumnTrait>(column: C, at: DateTime<Utc>) -> Value {
    match column.def().get_column_type() {
        ColumnType::DateTime | ColumnType::Timestamp => Value::ChronoDateTime(Some(at.naive_utc())),
        _ => Value::ChronoDateTimeUtc(Some(at)),
    }
}

/// The row matching `row`, as stored now.
pub async fn reload<M, C>(db: &C, row: Condition) -> Result<M, DbErr>
where
    M: ModelTrait<Entity: EntityTrait<Model = M>> + FromQueryResult,
    C: ConnectionTrait,
{
    M::Entity::find()
        .filter(row)
        .one(db)
        .await?
        .ok_or_else(|| DbErr::RecordNotFound("the soft-deleted row no longer exists".to_string()))
}