This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
CheckConstraint,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
ForeignKeyConstraint,
|
||||
Index,
|
||||
String,
|
||||
Text,
|
||||
false,
|
||||
)
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
__table_args__ = (
|
||||
CheckConstraint("username ~ '^[a-z0-9_]{3,32}$'"),
|
||||
CheckConstraint("length(trim(display_name)) > 0"),
|
||||
)
|
||||
|
||||
id: Mapped[UUID] = mapped_column(primary_key=True)
|
||||
username: Mapped[str] = mapped_column(String(32), unique=True)
|
||||
display_name: Mapped[str] = mapped_column(String(100))
|
||||
password_hash: Mapped[str] = mapped_column(Text)
|
||||
is_admin: Mapped[bool] = mapped_column(Boolean, default=False, server_default=false())
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
|
||||
class Chat(Base):
|
||||
__tablename__ = "chats"
|
||||
__table_args__ = (CheckConstraint("length(trim(title)) > 0"),)
|
||||
|
||||
id: Mapped[UUID] = mapped_column(primary_key=True)
|
||||
title: Mapped[str] = mapped_column(String(100))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
members: Mapped[list["ChatMember"]] = relationship(order_by="ChatMember.user_id")
|
||||
|
||||
|
||||
class ChatMember(Base):
|
||||
__tablename__ = "chat_members"
|
||||
__table_args__ = (Index("chat_members_user_idx", "user_id", "chat_id"),)
|
||||
|
||||
chat_id: Mapped[UUID] = mapped_column(
|
||||
ForeignKey("chats.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
user_id: Mapped[UUID] = mapped_column(ForeignKey("users.id"), primary_key=True)
|
||||
|
||||
|
||||
class Message(Base):
|
||||
__tablename__ = "messages"
|
||||
__table_args__ = (
|
||||
ForeignKeyConstraint(
|
||||
["chat_id", "sender_id"], ["chat_members.chat_id", "chat_members.user_id"]
|
||||
),
|
||||
CheckConstraint("length(trim(text)) > 0"),
|
||||
Index("messages_history_idx", "chat_id", "created_at", "id"),
|
||||
)
|
||||
|
||||
id: Mapped[UUID] = mapped_column(primary_key=True)
|
||||
chat_id: Mapped[UUID] = mapped_column(ForeignKey("chats.id"))
|
||||
sender_id: Mapped[UUID] = mapped_column(ForeignKey("users.id"))
|
||||
text: Mapped[str] = mapped_column(String(4000))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
Reference in New Issue
Block a user