46 lines
1.0 KiB
Python
46 lines
1.0 KiB
Python
|
|
"""SQLAlchemy 2.0 async base and session factory."""
|
||
|
|
from datetime import datetime, timezone
|
||
|
|
from uuid import uuid4
|
||
|
|
|
||
|
|
from sqlalchemy import DateTime, func
|
||
|
|
from sqlalchemy.dialects.postgresql import UUID
|
||
|
|
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||
|
|
|
||
|
|
|
||
|
|
class Base(DeclarativeBase):
|
||
|
|
"""Base class for all models."""
|
||
|
|
|
||
|
|
pass
|
||
|
|
|
||
|
|
|
||
|
|
class TimestampMixin:
|
||
|
|
"""Adds created_at and updated_at columns."""
|
||
|
|
|
||
|
|
created_at: Mapped[datetime] = mapped_column(
|
||
|
|
DateTime(timezone=True),
|
||
|
|
server_default=func.now(),
|
||
|
|
nullable=False,
|
||
|
|
)
|
||
|
|
updated_at: Mapped[datetime] = mapped_column(
|
||
|
|
DateTime(timezone=True),
|
||
|
|
server_default=func.now(),
|
||
|
|
onupdate=func.now(),
|
||
|
|
nullable=False,
|
||
|
|
)
|
||
|
|
|
||
|
|
|
||
|
|
class UUIDMixin:
|
||
|
|
"""Adds UUID primary key."""
|
||
|
|
|
||
|
|
id: Mapped[str] = mapped_column(
|
||
|
|
UUID(as_uuid=True),
|
||
|
|
primary_key=True,
|
||
|
|
default=uuid4,
|
||
|
|
index=True,
|
||
|
|
)
|
||
|
|
|
||
|
|
|
||
|
|
def utc_now() -> datetime:
|
||
|
|
"""Return timezone-aware UTC now."""
|
||
|
|
return datetime.now(timezone.utc)
|