Skip to content

Commit 17b59e5

Browse files
Kumzycofin
authored andcommitted
feat: add softdelete mixin
1 parent c0ae8f4 commit 17b59e5

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
from __future__ import annotations
2+
3+
from datetime import datetime, timezone
4+
5+
from sqlalchemy import mapped_column
6+
from sqlalchemy.orm import Mapped, declarative_mixin, declared_attr
7+
from sqlalchemy.types import DateTime
8+
9+
10+
@declarative_mixin
11+
class SoftDeleteMixin:
12+
"""Mixin class that adds soft delete functionality to SQLAlchemy models.
13+
14+
Adds two columns:
15+
- deleted_at: Timestamp when the record was deleted
16+
"""
17+
18+
@declared_attr
19+
def deleted_at(cls) -> Mapped[datetime | None]:
20+
"""Timestamp when the record was soft deleted"""
21+
return mapped_column(
22+
DateTime(timezone=True),
23+
default=None,
24+
nullable=True,
25+
index=True,
26+
)
27+
28+
def set_deleted_at(self, timestamp: datetime | None = None) -> None:
29+
"""Mark the record as soft deleted.
30+
31+
Args:
32+
timestamp: Optional timestamp to use for the deletion. If not provided,
33+
the current UTC timestamp will be used.
34+
"""
35+
self.deleted_at = timestamp or datetime.now(timezone.utc)
36+
37+
def restore(self) -> None:
38+
self.deleted_at = None

0 commit comments

Comments
 (0)