forked from mtusi2026/mtusi2026lab2
51 lines
1.7 KiB
Python
51 lines
1.7 KiB
Python
import uuid
|
|
|
|
from sqlalchemy import func, select, tuple_
|
|
from sqlalchemy.exc import IntegrityError
|
|
from sqlalchemy.orm import Session
|
|
|
|
from models import Chat, ChatMember, User
|
|
from utils.pagination import Position
|
|
|
|
|
|
def create_chat(db: Session, title: str, member_ids: list[uuid.UUID]) -> Chat | None:
|
|
"""Чат и участники — одна транзакция. None — есть несуществующий участник."""
|
|
found = db.scalar(select(func.count()).select_from(User).where(User.id.in_(member_ids)))
|
|
if found != len(member_ids):
|
|
return None
|
|
|
|
chat = Chat(title=title, members=[ChatMember(user_id=user_id) for user_id in sorted(member_ids)])
|
|
db.add(chat)
|
|
try:
|
|
db.commit()
|
|
except IntegrityError:
|
|
db.rollback()
|
|
return None
|
|
return chat
|
|
|
|
|
|
def is_chat_member(db: Session, chat_id: uuid.UUID, user_id: uuid.UUID) -> bool:
|
|
return db.get(ChatMember, (chat_id, user_id)) is not None
|
|
|
|
|
|
def get_member_chat(db: Session, chat_id: uuid.UUID, user_id: uuid.UUID) -> Chat | None:
|
|
query = (
|
|
select(Chat)
|
|
.join(ChatMember, ChatMember.chat_id == Chat.id)
|
|
.where(Chat.id == chat_id, ChatMember.user_id == user_id)
|
|
)
|
|
return db.scalar(query)
|
|
|
|
|
|
def list_user_chats(db: Session, user_id: uuid.UUID, limit: int, after: Position | None) -> list[Chat]:
|
|
query = (
|
|
select(Chat)
|
|
.join(ChatMember, ChatMember.chat_id == Chat.id)
|
|
.where(ChatMember.user_id == user_id)
|
|
.order_by(Chat.created_at, Chat.id)
|
|
.limit(limit + 1)
|
|
)
|
|
if after is not None:
|
|
query = query.where(tuple_(Chat.created_at, Chat.id) > tuple_(*after))
|
|
return list(db.scalars(query))
|