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>
This commit is contained in:
@@ -5,14 +5,20 @@ from sqlalchemy import Column, DateTime, ForeignKey, Integer
|
|||||||
from app.core.database import Base
|
from app.core.database import Base
|
||||||
|
|
||||||
|
|
||||||
|
def _utc_now() -> datetime:
|
||||||
|
return datetime.now(UTC)
|
||||||
|
|
||||||
|
|
||||||
class TimestampMixin:
|
class TimestampMixin:
|
||||||
"""Mixin to add created_at and updated_at timestamps to models"""
|
"""Mixin to add created_at and updated_at timestamps to models"""
|
||||||
|
|
||||||
created_at = Column(DateTime, default=datetime.now(UTC), nullable=False)
|
# 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(
|
updated_at = Column(
|
||||||
DateTime,
|
DateTime,
|
||||||
default=datetime.now(UTC),
|
default=_utc_now,
|
||||||
onupdate=datetime.now(UTC),
|
onupdate=_utc_now,
|
||||||
nullable=False,
|
nullable=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user