61 lines
2.6 KiB
Python
61 lines
2.6 KiB
Python
from datetime import datetime
|
|
from uuid import uuid4
|
|
|
|
from sqlalchemy import BigInteger, CheckConstraint, DateTime, ForeignKey, Index, Text, Uuid, func
|
|
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
|
|
|
|
|
class Base(DeclarativeBase):
|
|
pass
|
|
|
|
|
|
class User(Base):
|
|
__tablename__ = 'users'
|
|
__table_args__ = (
|
|
CheckConstraint("username ~ '^[a-z0-9_]{3,32}$'"),
|
|
CheckConstraint('char_length(display_name) BETWEEN 1 AND 100'),
|
|
)
|
|
id: Mapped[str] = mapped_column(Uuid(as_uuid=False), primary_key=True, default=lambda: str(uuid4()))
|
|
username: Mapped[str] = mapped_column(Text, unique=True)
|
|
display_name: Mapped[str] = mapped_column(Text)
|
|
password_hash: Mapped[str] = mapped_column(Text)
|
|
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.clock_timestamp())
|
|
|
|
|
|
class Chat(Base):
|
|
__tablename__ = 'chats'
|
|
__table_args__ = (
|
|
CheckConstraint('char_length(title) BETWEEN 1 AND 100'),
|
|
Index('chats_order_idx', 'created_at', 'id'),
|
|
)
|
|
id: Mapped[str] = mapped_column(Uuid(as_uuid=False), primary_key=True, default=lambda: str(uuid4()))
|
|
title: Mapped[str] = mapped_column(Text)
|
|
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.clock_timestamp())
|
|
history_version: Mapped[int] = mapped_column(BigInteger, server_default='0')
|
|
|
|
|
|
class ChatMember(Base):
|
|
__tablename__ = 'chat_members'
|
|
__table_args__ = (Index('chat_members_user_idx', 'user_id', 'chat_id'),)
|
|
chat_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), ForeignKey('chats.id', ondelete='CASCADE'), primary_key=True)
|
|
user_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), ForeignKey('users.id'), primary_key=True)
|
|
|
|
|
|
class Message(Base):
|
|
__tablename__ = 'messages'
|
|
__table_args__ = (
|
|
CheckConstraint('char_length(text) BETWEEN 1 AND 4000'),
|
|
Index('messages_history_idx', 'chat_id', 'created_at', 'id'),
|
|
)
|
|
id: Mapped[str] = mapped_column(Uuid(as_uuid=False), primary_key=True, default=lambda: str(uuid4()))
|
|
chat_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), ForeignKey('chats.id', ondelete='CASCADE'))
|
|
sender_id: Mapped[str] = mapped_column(Uuid(as_uuid=False), ForeignKey('users.id'))
|
|
text: Mapped[str] = mapped_column(Text)
|
|
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.clock_timestamp())
|
|
|
|
|
|
class SchemaMigration(Base):
|
|
__tablename__ = 'schema_migrations'
|
|
version: Mapped[str] = mapped_column(Text, primary_key=True)
|
|
applied_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=True)
|