sea-orm-soft-delete 0.1.2

Soft deletes for SeaORM: trash, restore, prune, and queries that skip trashed rows
Documentation

sea-orm-soft-delete

Soft deletes for SeaORM: trash, restore, prune, and queries that skip the trash.

crates.io docs.rs CI license

Mark an entity, and its rows go to the trash instead of disappearing: post.soft_delete(db) sets deleted_at, post.restore(db) brings the row back, old trash is pruned for good.

Features

  • Trash and restore — soft_delete, restore, force_delete, is_trashed on every model of the entity
  • Hooks — before/after each operation; a before_* hook can cancel
  • Quiet variants — *_quietly methods that skip the hooks
  • Queries — find_without_trashed(), find_only_trashed(), .without_trashed() on any query
  • Bulk and pruning — soft_delete_many, restore_many, Prunable- and MassPrunable-style pruning
  • Guard — turns SeaORM's hard delete() into an error, so data is never erased by accident
  • Migrations — the deleted_at column and a unique index that ignores trashed rows
  • Tested — against a real database (in-memory SQLite), every doc example compiled

Installation

[dependencies]
sea-orm-soft-delete = "0.1"

Quick start

Add a nullable deleted_at column (see Migrations) and mark the entity:

use sea_orm_soft_delete::SoftDelete;

impl SoftDelete for posts::Entity {
    fn deleted_at_column() -> Self::Column {
        posts::Column::DeletedAt
    }
}

Every posts::Model now has trash operations:

use sea_orm_soft_delete::SoftDeleteModel;

let post = post.soft_delete(&db).await?;   // deleted_at = now
assert!(post.is_trashed());

let post = post.restore(&db).await?;       // deleted_at = NULL
post.force_delete(&db).await?;            // DELETE, for good

Trashing a row twice keeps its original deleted_at, even through an out-of-date copy of the model: the state check is part of the UPDATE. If the table has an updated_at column, set it together with deleted_at:

impl SoftDelete for posts::Entity {
    fn deleted_at_column() -> Self::Column {
        posts::Column::DeletedAt
    }

    fn updated_at_column() -> Option<Self::Column> {
        Some(posts::Column::UpdatedAt)
    }
}

Queries

use sea_orm_soft_delete::{SoftDelete, TrashedQuery};

let live = posts::Entity::find_without_trashed().all(&db).await?;
let trash = posts::Entity::find_only_trashed().all(&db).await?;

let in_category = posts::Entity::find()
    .filter(posts::Column::CategoryId.eq(1))
    .without_trashed()
    .all(&db)
    .await?;

let by_id = posts::Entity::find_by_id(5).without_trashed().one(&db).await?;
let comments = post.find_related(comments::Entity).without_trashed().all(&db).await?;

Read this first. SeaORM has no global query scopes, so a plain posts::Entity::find() still returns trashed rows. You ask for live rows with find_without_trashed() or .without_trashed(). Keeping all queries for an entity in one place (a repository module) makes that easy to get right.

There is no with_trashed(): a plain query already includes trashed rows.

Hooks

Override any of them in the same impl SoftDelete block. An error from a before_* hook cancels the operation.

Hook Runs
before_soft_delete before a row goes to the trash
after_soft_delete after it went there
before_restore before a row leaves the trash
after_restore after it left
before_force_delete before a row is deleted for good
after_force_delete after that
impl SoftDelete for posts::Entity {
    fn deleted_at_column() -> Self::Column {
        posts::Column::DeletedAt
    }

    async fn before_force_delete<C: ConnectionTrait>(post: &posts::Model, db: &C) -> Result<(), DbErr> {
        remove_cover_image(post).await;
        Ok(())
    }
}

soft_delete_quietly, restore_quietly and force_delete_quietly skip the hooks. Bulk operations and mass_prune_trashed never run them. Pass a DatabaseTransaction as db to make a hook and its change atomic.

Guarding against hard deletes

In SeaORM post.delete(db) removes the row for good, and a hook cannot turn that into an update. So make it an error instead:

#[async_trait::async_trait]
impl ActiveModelBehavior for posts::ActiveModel {
    async fn before_delete<C: ConnectionTrait>(self, _db: &C) -> Result<Self, DbErr> {
        sea_orm_soft_delete::deny_hard_delete()?;
        Ok(self)
    }
}

force_delete keeps working: it does not go through ActiveModelBehavior. Neither do Entity::delete_many() and Entity::delete_by_id(...), so the guard cannot stop them; keep those out of code paths for soft-deleted entities.

Many rows at once

let condition = Condition::all().add(posts::Column::CategoryId.eq(1));

let trashed = posts::Entity::soft_delete_many(&db, condition.clone()).await?;  // count
let restored = posts::Entity::restore_many(&db, condition).await?;             // count

Pruning

Delete for good everything that has been in the trash longer than a given time, for example from a scheduled task:

use chrono::Duration;

// How many rows would go, like `model:prune --pretend`
let pending = posts::Entity::count_prunable(&db, Duration::days(30)).await?;

// Like `Prunable`: one row at a time, with the force-delete hooks (to remove files, ...)
let removed = posts::Entity::prune_trashed(&db, Duration::days(30)).await?;

// Like `MassPrunable`: one DELETE query, no hooks
let removed = posts::Entity::mass_prune_trashed(&db, Duration::days(30)).await?;

Migrations

The column, a nullable timestamp with time zone (a plain timestamp works too; it is written in UTC):

manager
    .alter_table(
        Table::alter()
            .table("posts")
            .add_column(sea_orm_soft_delete::deleted_at_column("deleted_at"))
            .to_owned(),
    )
    .await?;

A unique index that only covers rows outside the trash, so a trashed hello no longer blocks a new hello:

manager
    .create_index(sea_orm_soft_delete::unique_while_kept(
        "posts_slug_kept",
        "posts",
        ["slug"],
        "deleted_at",
    ))
    .await?;
// CREATE UNIQUE INDEX "posts_slug_kept" ON "posts" ("slug") WHERE "deleted_at" IS NULL

This is safer than a plain unique(slug, deleted_at), which lets two live rows share a slug because NULL never equals NULL. Partial indexes work in Postgres and SQLite; MySQL does not support them.

Contributing

Issues and pull requests are welcome. The tests need no database server:

cargo test

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.


Made by AxVi · part of AxViLab