sea-orm-soft-delete 0.1.1

Soft deletes for SeaORM: trash, restore, prune, and queries that skip trashed rows
Documentation
<p align="center">
  <img src="https://raw.githubusercontent.com/axvilab/sea-orm-soft-delete/main/assets/logo.png" alt="sea-orm-soft-delete logo" width="128" height="128">
</p>

# sea-orm-soft-delete

**Soft deletes for [SeaORM](https://www.sea-ql.org/SeaORM/): trash, restore, prune, and queries that skip the trash.**

[![crates.io](https://img.shields.io/crates/v/sea-orm-soft-delete)](https://crates.io/crates/sea-orm-soft-delete)
[![docs.rs](https://img.shields.io/docsrs/sea-orm-soft-delete)](https://docs.rs/sea-orm-soft-delete)
[![CI](https://github.com/axvilab/sea-orm-soft-delete/actions/workflows/ci.yml/badge.svg)](https://github.com/axvilab/sea-orm-soft-delete/actions/workflows/ci.yml)
[![license](https://img.shields.io/crates/l/sea-orm-soft-delete)](#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.
Think Laravel's `SoftDeletes`, for SeaORM.

## Features

- **Trash and restore** — `soft_delete`, `restore`, `force_delete`, `is_trashed` on every model of the entity
- **Hooks** — before/after each operation, like Laravel's model events; 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

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

## Quick start

Add a nullable `deleted_at` column (see [Migrations](#migrations)) and mark the entity:

```rust
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:

```rust
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`, as Laravel does:

```rust
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

```rust
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. Laravel hides them automatically; here you ask for it 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 | Laravel event | Runs |
|---|---|---|
| `before_soft_delete` | `deleting` | before a row goes to the trash |
| `after_soft_delete` | `trashed` | after it went there |
| `before_restore` | `restoring` | before a row leaves the trash |
| `after_restore` | `restored` | after it left |
| `before_force_delete` | `forceDeleting` | before a row is deleted for good |
| `after_force_delete` | `forceDeleted` | after that |

```rust
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, as Laravel's mass deletes fire no events.
Pass a `DatabaseTransaction` as `db` to make a hook and its change atomic.

## Guarding against hard deletes

In Laravel `delete()` on a soft-deleting model is soft. 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:

```rust
#[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

```rust
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:

```rust
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):

```rust
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`:

```rust
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 cleaner than Laravel's usual `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.

## Coming from Laravel

| Laravel `SoftDeletes` | sea-orm-soft-delete |
|---|---|
| `use SoftDeletes` | `impl SoftDelete for Entity` |
| `$table->softDeletesTz()` | `deleted_at_column("deleted_at")` |
| `$post->delete()` | `post.soft_delete(db)` |
| `$post->restore()` | `post.restore(db)` |
| `$post->forceDelete()` | `post.force_delete(db)` |
| `$post->trashed()` | `post.is_trashed()` |
| `deleteQuietly()`, `restoreQuietly()` | `soft_delete_quietly`, `restore_quietly` |
| global scope hiding trashed rows | `find_without_trashed()`, `.without_trashed()` |
| `withTrashed()` | plain `find()` |
| `onlyTrashed()` | `find_only_trashed()`, `.only_trashed()` |
| `Post::where(...)->restore()` | `restore_many(db, condition)` |
| `deleting`, `trashed`, `restoring`, `restored`, `forceDeleting`, `forceDeleted` | `before_*` / `after_*` hooks |
| `Prunable`, `MassPrunable`, `model:prune --pretend` | `prune_trashed`, `mass_prune_trashed`, `count_prunable` |
| — | `deny_hard_delete()`, `unique_while_kept(...)` |

## Contributing

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

```sh
cargo test
```

## License

Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE) or
[MIT license](LICENSE-MIT) 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](https://axvi.dev) · part of [AxViLab](https://github.com/axvilab)