Skip to content
AXVI BUILD · WRITE · SHIP
Packages

SeaORM Soft Delete

Soft deletes for SeaORM: trash, restore, prune, and queries that skip the trash, with hooks, quiet variants, pruning and a guard against hard deletes.

SeaORM Soft Delete

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. Works with any SeaORM app, including Loco.

Features

  • Trash and restore: soft_delete, restore, force_delete, is_trashed on every model
  • Hooks before and after each operation; a before_* hook can cancel
  • Quiet variants 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, every documentation example compiled

Installation

cargo add sea-orm-soft-delete

Quick start

Add a nullable deleted_at column 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 model of the entity 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

Query without the trash:

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

SeaORM has no global query scopes, so a plain find() still returns trashed rows. You ask for live rows explicitly, which is easy to get right when all queries for an entity live in one repository module.

A unique slug that ignores the trash

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

A trashed hello no longer blocks a new hello, and two live rows still cannot share a slug.

Esc