sea-orm-soft-delete 0.1.2

Soft deletes for SeaORM: trash, restore, prune, and queries that skip trashed rows
Documentation
use sea_orm::sea_query::{
    ColumnDef, ConditionalStatement, Expr, ExprTrait, Index, IndexCreateStatement, IntoIden,
    IntoIndexColumn, IntoTableRef,
};

/// The `deleted_at` column for a migration: nullable `timestamp with time zone`.
///
/// ```
/// use sea_orm::sea_query::{PostgresQueryBuilder, Table};
/// use sea_orm_soft_delete::deleted_at_column;
///
/// // In a SeaORM migration, pass this to `manager.alter_table(...)`.
/// let statement = Table::alter()
///     .table("posts")
///     .add_column(deleted_at_column("deleted_at"))
///     .to_owned();
///
/// assert_eq!(
///     statement.to_string(PostgresQueryBuilder),
///     r#"ALTER TABLE "posts" ADD COLUMN "deleted_at" timestamp with time zone NULL"#
/// );
/// ```
pub fn deleted_at_column(name: impl IntoIden) -> ColumnDef {
    ColumnDef::new(name)
        .timestamp_with_time_zone()
        .null()
        .to_owned()
}

/// A unique index that only covers rows outside the trash:
/// `CREATE UNIQUE INDEX ... WHERE deleted_at IS NULL`.
///
/// A trashed `hello` then no longer blocks a new `hello`. This is cleaner than the
/// usual `UNIQUE (slug, deleted_at)`, which lets two live rows share a slug in
/// databases where `NULL` values never conflict. Works in Postgres and SQLite;
/// MySQL has no partial indexes.
///
/// ```
/// use sea_orm::sea_query::PostgresQueryBuilder;
/// use sea_orm_soft_delete::unique_while_kept;
///
/// // In a SeaORM migration, pass this to `manager.create_index(...)`.
/// let index = unique_while_kept("posts_slug_kept", "posts", ["slug"], "deleted_at");
///
/// assert_eq!(
///     index.to_string(PostgresQueryBuilder),
///     r#"CREATE UNIQUE INDEX "posts_slug_kept" ON "posts" ("slug") WHERE "deleted_at" IS NULL"#
/// );
/// ```
pub fn unique_while_kept<C>(
    name: &str,
    table: impl IntoTableRef,
    columns: impl IntoIterator<Item = C>,
    deleted_at: impl IntoIden,
) -> IndexCreateStatement
where
    C: IntoIndexColumn,
{
    let mut index = Index::create();
    index.name(name).table(table).unique();
    for column in columns {
        index.col(column);
    }
    index.and_where(Expr::col(deleted_at.into_iden()).is_null());
    index
}