67 lines
2.7 KiB
Python
67 lines
2.7 KiB
Python
from collections.abc import Sequence
|
|
from uuid import UUID
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.models.chat import Chat
|
|
from app.storage.types import Position
|
|
|
|
|
|
async def create_chat(
|
|
session: AsyncSession,
|
|
*,
|
|
title: str,
|
|
member_ids: Sequence[UUID],
|
|
) -> Chat:
|
|
"""INSERT chats + INSERT chat_members для каждого участника, затем flush.
|
|
|
|
Алгоритм:
|
|
1. chat = Chat(title=title); session.add(chat)
|
|
2. await session.flush() (нужен chat.id)
|
|
3. session.add_all(ChatMember(chat_id=chat.id, user_id=uid) for uid in member_ids)
|
|
4. await session.flush()
|
|
5. await session.refresh(chat, attribute_names=["members"])
|
|
— в async нельзя полагаться на ленивую загрузку chat.members
|
|
(MissingGreenlet), поэтому либо refresh, либо relationship(lazy="selectin").
|
|
6. return chat
|
|
Всё в одной транзакции domain: упадёт вставка участника — откатится и чат.
|
|
"""
|
|
raise NotImplementedError("TODO")
|
|
|
|
|
|
async def get_chat_for_member(
|
|
session: AsyncSession,
|
|
chat_id: UUID,
|
|
user_id: UUID,
|
|
) -> Chat | None:
|
|
"""Чат, только если user_id — его участник; иначе None.
|
|
|
|
Алгоритм:
|
|
1. stmt = select(Chat).join(ChatMember, ChatMember.chat_id == Chat.id)
|
|
.where(Chat.id == chat_id, ChatMember.user_id == user_id)
|
|
.options(selectinload(Chat.members))
|
|
2. result = await session.execute(stmt); return result.scalar_one_or_none()
|
|
Посторонний и несуществующий чат дают одинаковый None (-> 404).
|
|
"""
|
|
raise NotImplementedError("TODO")
|
|
|
|
|
|
async def list_chats_for_user(
|
|
session: AsyncSession,
|
|
user_id: UUID,
|
|
after: Position | None,
|
|
limit: int,
|
|
) -> list[Chat]:
|
|
"""Чаты пользователя по (created_at, id) по возрастанию, строго после `after`.
|
|
|
|
Алгоритм:
|
|
1. stmt = select(Chat).join(ChatMember, ChatMember.chat_id == Chat.id)
|
|
.where(ChatMember.user_id == user_id)
|
|
2. если after: stmt = stmt.where(tuple_(Chat.created_at, Chat.id) > tuple_(*after))
|
|
3. stmt = stmt.order_by(Chat.created_at, Chat.id).limit(limit)
|
|
.options(selectinload(Chat.members))
|
|
4. result = await session.execute(stmt); return list(result.scalars().all())
|
|
Вызывающий передаёт limit + 1, чтобы узнать, есть ли следующая страница.
|
|
"""
|
|
raise NotImplementedError("TODO")
|