import uuid from datetime import datetime from sqlalchemy import String, Integer, Float, DateTime, ForeignKey, Index, func from sqlalchemy import Uuid from sqlalchemy.orm import Mapped, mapped_column from app.database import Base, JSONType class UsageRecord(Base): __tablename__ = "usage_records" id: Mapped[uuid.UUID] = mapped_column( Uuid(as_uuid=True), primary_key=True, default=uuid.uuid4, ) user_id: Mapped[uuid.UUID] = mapped_column( Uuid(as_uuid=True), nullable=False, index=True, ) brand_id: Mapped[uuid.UUID | None] = mapped_column( Uuid(as_uuid=True), ForeignKey("brands.id", ondelete="SET NULL"), nullable=True, ) engine_type: Mapped[str] = mapped_column( String(20), nullable=False, ) query: Mapped[str] = mapped_column( String(500), nullable=False, ) input_tokens: Mapped[int] = mapped_column( Integer, default=0, ) output_tokens: Mapped[int] = mapped_column( Integer, default=0, ) cost: Mapped[float] = mapped_column( Float, default=0.0, ) extra_data: Mapped[dict] = mapped_column( JSONType, default=dict, ) timestamp: Mapped[datetime] = mapped_column( DateTime(timezone=True), default=func.now(), index=True, ) created_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), server_default=func.now(), nullable=False, ) __table_args__ = ( Index("idx_usage_records_user_engine", "user_id", "engine_type"), Index("idx_usage_records_user_timestamp", "user_id", "timestamp"), Index("idx_usage_records_engine_timestamp", "engine_type", "timestamp"), )