add async with all functions
This commit is contained in:
+31
-16
@@ -1,51 +1,66 @@
|
||||
from collections.abc import Sequence
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.chat import Chat
|
||||
from app.storage.types import Position
|
||||
|
||||
|
||||
def create_chat(
|
||||
session: Session,
|
||||
async def create_chat(
|
||||
session: AsyncSession,
|
||||
*,
|
||||
title: str,
|
||||
member_ids: Sequence[UUID],
|
||||
) -> Chat:
|
||||
"""INSERT chats + INSERT chat_members для каждого участника, затем flush().
|
||||
"""INSERT chats + INSERT chat_members для каждого участника, затем flush.
|
||||
|
||||
Всё в одной транзакции domain: если упадёт вставка участника — откатится и чат
|
||||
(требование «составная операция создания чата выполняется атомарно»).
|
||||
Возвращённый Chat должен иметь доступные участники (chat.members).
|
||||
Алгоритм:
|
||||
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")
|
||||
|
||||
|
||||
def get_chat_for_member(
|
||||
session: Session,
|
||||
async def get_chat_for_member(
|
||||
session: AsyncSession,
|
||||
chat_id: UUID,
|
||||
user_id: UUID,
|
||||
) -> Chat | None:
|
||||
"""Чат, только если user_id — его участник; иначе None.
|
||||
|
||||
Один запрос (JOIN/EXISTS), а не «загрузить чат, потом проверить в Python».
|
||||
Для постороннего и для несуществующего чата результат одинаков (None -> 404),
|
||||
чтобы не раскрывать существование чужого чата.
|
||||
Алгоритм:
|
||||
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")
|
||||
|
||||
|
||||
def list_chats_for_user(
|
||||
session: Session,
|
||||
async def list_chats_for_user(
|
||||
session: AsyncSession,
|
||||
user_id: UUID,
|
||||
after: Position | None,
|
||||
limit: int,
|
||||
) -> list[Chat]:
|
||||
"""Чаты пользователя по (created_at, id) по возрастанию, строго после `after`.
|
||||
|
||||
Keyset: WHERE (created_at, id) > (:t, :i) — sqlalchemy.tuple_(Chat.created_at, Chat.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, чтобы узнать, есть ли следующая страница.
|
||||
Участников грузите selectinload (без N+1).
|
||||
"""
|
||||
raise NotImplementedError("TODO")
|
||||
|
||||
Reference in New Issue
Block a user