sea-orm-soft-delete 0.1.0

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::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 `now` is `None`) 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 = if trashed { Some(now) } else { None };
    let update = update.col_expr(E::deleted_at_column(), Expr::value(deleted_at));
    match E::updated_at_column() {
        Some(column) => update.col_expr(column, Expr::value(now)),
        None => update,
    }
}

/// 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()))
}

/// SQL `NULL` in a timestamp column, whichever chrono type the entity uses.
pub const fn is_null(value: &Value) -> bool {
    matches!(
        value,
        Value::ChronoDateTime(None)
            | Value::ChronoDateTimeUtc(None)
            | Value::ChronoDateTimeLocal(None)
            | Value::ChronoDateTimeWithTimeZone(None)
    )
}