Files
orion/models/database/base.py
Samir Boulahtit bdb613581c fix(timestamps): callable default so each row gets a fresh timestamp
TimestampMixin was setting default=datetime.now(UTC) — calling the
function once at module import time. Every INSERT (and every UPDATE
via onupdate) since the app last restarted got stamped with the same
process-start timestamp, silently breaking created_at / updated_at on
every table that uses the mixin (customers, stores, cards, users,
orders, etc.).

Pass the _utc_now callable instead so SQLAlchemy invokes it per row.
Forward fix only — historical rows on prod since the most recent app
restart all read as the start-time microsecond and will need a
separate decision on whether to backfill.

Found while debugging why a customer + their loyalty card had
microsecond-identical created_at timestamps despite being created
through separate service calls.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 19:44:35 +02:00

41 lines
1.1 KiB
Python

from datetime import UTC, datetime
from sqlalchemy import Column, DateTime, ForeignKey, Integer
from app.core.database import Base
def _utc_now() -> datetime:
return datetime.now(UTC)
class TimestampMixin:
"""Mixin to add created_at and updated_at timestamps to models"""
# Pass the callable, not its result. Otherwise the default is evaluated
# once at module import and every row gets the same timestamp.
created_at = Column(DateTime, default=_utc_now, nullable=False)
updated_at = Column(
DateTime,
default=_utc_now,
onupdate=_utc_now,
nullable=False,
)
class SoftDeleteMixin:
"""Mixin for soft-deletable models.
Adds deleted_at and deleted_by_id columns. Records with deleted_at set
are automatically excluded from queries via the do_orm_execute event
in app.core.database. Use execution_options={"include_deleted": True}
to bypass the filter.
"""
deleted_at = Column(DateTime, nullable=True, index=True)
deleted_by_id = Column(
Integer,
ForeignKey("users.id", ondelete="SET NULL"),
nullable=True,
)