Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add soft delete mixin #337

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions advanced_alchemy/mixins/softdelete.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from __future__ import annotations

from datetime import datetime, timezone

from sqlalchemy import mapped_column
from sqlalchemy.orm import Mapped, declarative_mixin, declared_attr
from sqlalchemy.types import DateTime


@declarative_mixin
class SoftDeleteMixin:
"""Mixin class that adds soft delete functionality to SQLAlchemy models.

Adds two columns:
- deleted_at: Timestamp when the record was deleted
"""

@declared_attr
def deleted_at(cls) -> Mapped[datetime | None]:
"""Timestamp when the record was soft deleted"""
return mapped_column(
DateTime(timezone=True),
default=None,
nullable=True,
index=True,
)

def set_deleted_at(self, timestamp: datetime | None = None) -> None:
"""Mark the record as soft deleted.

Args:
timestamp: Optional timestamp to use for the deletion. If not provided,
the current UTC timestamp will be used.
"""
self.deleted_at = timestamp or datetime.now(timezone.utc)

def restore(self) -> None:
"""Restore a soft-deleted record by clearing the deleted_at timestamp.

This method undeletes a previously soft-deleted record by setting the deleted_at
field to None, making it visible in normal queries again.
"""
self.deleted_at = None
Loading