import uuid from datetime import datetime, timezone from sqlalchemy import DateTime, ForeignKey, String, UniqueConstraint from sqlalchemy.orm import Mapped, mapped_column from app.db import Base class UnlockRecord(Base): """A permanent unlock a seeker has purchased with essence (e.g. the listening tool). One row per (user, unlock_key). The unique constraint is defense-in-depth: today, idempotency (no double charge for an already-owned unlock) is enforced entirely by `app.inventory.purchase_unlock`'s row-locked check-then-insert. This constraint means any *other* code path that ever inserts an UnlockRecord without going through that lock still can't create a duplicate row for the same (user, unlock_key). """ __tablename__ = "unlocks" __table_args__ = (UniqueConstraint("user_id", "unlock_key", name="uq_unlocks_user_key"),) id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4) user_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("users.id"), index=True) unlock_key: Mapped[str] = mapped_column(String(64), index=True) unlocked_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), default=lambda: datetime.now(timezone.utc) )