mirror of
https://github.com/d3vyce/fastapi-toolsets.git
synced 2026-04-16 06:36:26 +02:00
48 lines
1.1 KiB
Python
48 lines
1.1 KiB
Python
"""SQLAlchemy model mixins for common column patterns."""
|
|
|
|
import uuid
|
|
from datetime import datetime
|
|
|
|
from sqlalchemy import DateTime, Uuid, func, text
|
|
from sqlalchemy.orm import Mapped, mapped_column
|
|
|
|
__all__ = [
|
|
"UUIDMixin",
|
|
"CreatedAtMixin",
|
|
"UpdatedAtMixin",
|
|
"TimestampMixin",
|
|
]
|
|
|
|
|
|
class UUIDMixin:
|
|
"""Mixin that adds a UUID primary key auto-generated by the database."""
|
|
|
|
id: Mapped[uuid.UUID] = mapped_column(
|
|
Uuid,
|
|
primary_key=True,
|
|
server_default=text("gen_random_uuid()"),
|
|
)
|
|
|
|
|
|
class CreatedAtMixin:
|
|
"""Mixin that adds a ``created_at`` timestamp column."""
|
|
|
|
created_at: Mapped[datetime] = mapped_column(
|
|
DateTime(timezone=True),
|
|
server_default=func.now(),
|
|
)
|
|
|
|
|
|
class UpdatedAtMixin:
|
|
"""Mixin that adds an ``updated_at`` timestamp column."""
|
|
|
|
updated_at: Mapped[datetime] = mapped_column(
|
|
DateTime(timezone=True),
|
|
server_default=func.now(),
|
|
onupdate=func.now(),
|
|
)
|
|
|
|
|
|
class TimestampMixin(CreatedAtMixin, UpdatedAtMixin):
|
|
"""Mixin that combines ``created_at`` and ``updated_at`` timestamp columns."""
|