import uuid from datetime import datetime from sqlalchemy import ( CheckConstraint, DateTime, ForeignKey, Index, String, Text, func, ) from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.orm import Mapped, mapped_column, relationship from src.db.base import Base class User(Base): __tablename__ = "users" id: Mapped[uuid.UUID] = mapped_column( UUID(as_uuid=True), primary_key=True, default=uuid.uuid4 ) username: Mapped[str] = mapped_column( String(32), unique=True, nullable=False, index=True ) display_name: Mapped[str] = mapped_column(String(100), nullable=False) password_hash: Mapped[str] = mapped_column(Text, nullable=False) created_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), server_default=func.now(), nullable=False ) __table_args__ = ( CheckConstraint( "username ~ '^[a-z0-9_]{3,32}$'", name="ck_users_username_format", ), ) class Chat(Base): __tablename__ = "chats" id: Mapped[uuid.UUID] = mapped_column( UUID(as_uuid=True), primary_key=True, default=uuid.uuid4 ) title: Mapped[str] = mapped_column(String(100), nullable=False) created_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), server_default=func.now(), nullable=False ) members: Mapped[list["ChatMember"]] = relationship( back_populates="chat", cascade="all, delete-orphan" ) class ChatMember(Base): __tablename__ = "chat_members" chat_id: Mapped[uuid.UUID] = mapped_column( UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), primary_key=True, ) user_id: Mapped[uuid.UUID] = mapped_column( UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), primary_key=True, ) chat: Mapped["Chat"] = relationship(back_populates="members") class Message(Base): __tablename__ = "messages" id: Mapped[uuid.UUID] = mapped_column( UUID(as_uuid=True), primary_key=True, default=uuid.uuid4 ) chat_id: Mapped[uuid.UUID] = mapped_column( UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), nullable=False, ) sender_id: Mapped[uuid.UUID] = mapped_column( UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False, ) text: Mapped[str] = mapped_column(Text, nullable=False) created_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), server_default=func.now(), nullable=False ) __table_args__ = ( # Ключевой индекс для пагинации истории (оценка 4). Index( "idx_messages_chat_created_id", "chat_id", "created_at", "id", ), )