# How to soft-delete rows

This page marks rows as deleted instead of removing them, so they can be audited or restored later: two fields on the model hold the mark, and a mixin supplies `soft_delete()`, `restore()` and `active()`.

## The `SoftDeleteMixin`

Declare `is_deleted` and `deleted_at` on the model, and put the mixin first among its bases:

```python
from datetime import UTC, datetime

from ferro import Field, Model, connect, engines
from ferro.query import Query


class SoftDeleteMixin:
    """Soft-delete behaviour as a plain class.

    Each model that uses it declares ``is_deleted`` and ``deleted_at``
    itself; the mixin supplies the methods.
    """

    async def soft_delete(self) -> None:
        self.is_deleted = True
        self.deleted_at = datetime.now(UTC)
        await self.save()

    async def restore(self) -> None:
        self.is_deleted = False
        self.deleted_at = None
        await self.save()

    @classmethod
    def active(cls) -> Query:
        return cls.where(lambda row: row.is_deleted == False)


class Invoice(SoftDeleteMixin, Model):
    id: int | None = Field(default=None, primary_key=True)
    number: str = Field(unique=True)
    is_deleted: bool = False
    deleted_at: datetime | None = None


await connect("sqlite::memory:", auto_migrate=True)

async with engines.session():
    invoice = await Invoice.create(number="INV-001")
    await Invoice.create(number="INV-002")
    await Invoice.create(number="INV-003")
```

```python
from datetime import UTC, datetime
from typing import Annotated

from ferro import Field, Model, connect, engines
from ferro.query import Query


class SoftDeleteMixin:
    """Soft-delete behaviour as a plain class.

    Each model that uses it declares ``is_deleted`` and ``deleted_at``
    itself; the mixin supplies the methods.
    """

    async def soft_delete(self) -> None:
        self.is_deleted = True
        self.deleted_at = datetime.now(UTC)
        await self.save()

    async def restore(self) -> None:
        self.is_deleted = False
        self.deleted_at = None
        await self.save()

    @classmethod
    def active(cls) -> Query:
        return cls.where(lambda row: row.is_deleted == False)


class Invoice(SoftDeleteMixin, Model):
    id: Annotated[int | None, Field(primary_key=True)] = None
    number: Annotated[str, Field(unique=True)]
    is_deleted: bool = False
    deleted_at: datetime | None = None


await connect("sqlite::memory:", auto_migrate=True)

async with engines.session():
    invoice = await Invoice.create(number="INV-001")
    await Invoice.create(number="INV-002")
    await Invoice.create(number="INV-003")
```

The table now holds three live invoices. The blocks below run inside this session; [Sessions](<https://ferro-orm.x54.sh/guide/connections/#sessions>) explains why every call needs one.

`soft_delete()` and `restore()` set the two fields and save. `active()` returns an ordinary `Query` filtered to rows that are not deleted, so it chains like any other query. Its lambda names its parameter `row` rather than after a model, because the mixin serves every model that uses it.

The mixin is a plain class, not a `Model` subclass, so every model that uses it declares the two fields itself. A `Model` base class would get a table of its own; [Fields on a model base class](<https://ferro-orm.x54.sh/guide/models-and-fields/#fields-on-a-model-base-class>) shows that table.

## Deleting and restoring

Soft-delete an invoice, count, then restore it:

```python
await invoice.soft_delete()
assert await Invoice.active().count() == 2
assert await Invoice.select().count() == 3

await invoice.restore()
assert await Invoice.active().count() == 3
```

After `soft_delete()`, `active()` counts two invoices while `select()` still counts three: the row stays in the table. `restore()` brings it back to `active()`.

## Querying live rows

Start every query that should skip deleted rows from `active()`, and chain from there. With INV-001 soft-deleted again:

```python
live = await (
    Invoice.active()
    .where(lambda invoice: invoice.number >= "INV-002")
    .order_by(lambda invoice: invoice.number)
    .all()
)
assert [invoice.number for invoice in live] == ["INV-002", "INV-003"]

trashed = await Invoice.where(lambda invoice: invoice.is_deleted == True).all()
assert [invoice.number for invoice in trashed] == ["INV-001"]
```

`live` holds the two live invoices from INV-002 on, and `trashed` holds only the soft-deleted INV-001.

> [!WARNING]
>
> **Nothing is filtered automatically**
>
> `Invoice.all()`, `Invoice.select()`, `Invoice.get(pk)` and relationship traversals still return soft-deleted rows. Only queries that start from `active()` skip them.

`await invoice.delete()` and `Invoice.where(...).delete()` still issue a real `DELETE`: the mixin adds `soft_delete()` beside them and changes neither.

## Trade-offs

**A unique column still holds a soft-deleted row's value.** `number` is unique, so while INV-001 is soft-deleted, a new invoice cannot take its number:

```python
from ferro import UniqueViolationError

try:
    await Invoice.create(number="INV-001")
except UniqueViolationError:
    print("INV-001 is still taken")
else:
    raise AssertionError("expected UniqueViolationError")
```

It prints `INV-001 is still taken`. When a flow must reuse the value, hard-delete the row in that flow, or change the value as part of the soft delete (append the primary key, for example). Checking for a live duplicate in application code before inserting is not safe: two requests can both pass the check and both insert.

**Soft-deleted rows keep their space.** They stay in the table and its indexes, so scans, backups and indexes grow. Pair soft deletes with a retention period, and a job that purges the rows past it with a real `DELETE`:

```python
soft_deleted = Invoice.where(lambda invoice: invoice.is_deleted == True)
purged = await soft_deleted.delete()
assert purged == 1
assert await Invoice.select().count() == 2
```

The purge removes INV-001 for good and leaves the two live invoices.

**Soft-deleted data is still stored.** If users expect deletion to remove their personal data, a soft delete does not do that; purge the row for real.

## See also

- [How to record created and updated times](<https://ferro-orm.x54.sh/howto/timestamps/index.md>): the same mixin pattern for timestamps.
- [Fields on a model base class](<https://ferro-orm.x54.sh/guide/models-and-fields/#fields-on-a-model-base-class>): why the fields go on each model.
- [Batch updates and deletes](<https://ferro-orm.x54.sh/guide/mutations/#batch-updates-and-deletes>) and `Query.delete()` in the API reference.
