from __future__ import annotations import uuid from datetime import datetime from typing import List, Optional from sqlalchemy import DateTime, ForeignKey, String, Text, Uuid from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship class Base(DeclarativeBase): pass class UserRow(Base): __tablename__ = "users" id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True) username: Mapped[str] = mapped_column(Text, nullable=False, unique=True) display_name: Mapped[str] = mapped_column(Text, nullable=False) password_hash: Mapped[str] = mapped_column(Text, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) class ChatRow(Base): __tablename__ = "chats" id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True) title: Mapped[str] = mapped_column(Text, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) members: Mapped[List["ChatMemberRow"]] = relationship(back_populates="chat") class ChatMemberRow(Base): __tablename__ = "chat_members" chat_id: Mapped[uuid.UUID] = mapped_column( Uuid, ForeignKey("chats.id"), primary_key=True ) user_id: Mapped[uuid.UUID] = mapped_column( Uuid, ForeignKey("users.id"), primary_key=True ) chat: Mapped[ChatRow] = relationship(back_populates="members") class MessageRow(Base): __tablename__ = "messages" id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True) chat_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("chats.id"), nullable=False) sender_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("users.id"), nullable=False) text: Mapped[str] = mapped_column(Text, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) class SessionRow(Base): __tablename__ = "sessions" token_hash: Mapped[str] = mapped_column(String, primary_key=True) user_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("users.id"), nullable=False) expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) revoked_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) class IdempotencyRow(Base): __tablename__ = "idempotency_records" scope_key: Mapped[str] = mapped_column(Text, primary_key=True) request_hash: Mapped[str] = mapped_column(Text, nullable=False) message_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("messages.id"), nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)