50 lines
1.9 KiB
Python
50 lines
1.9 KiB
Python
from uuid import UUID
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.models.message import Message
|
|
from app.storage.types import Position
|
|
|
|
|
|
async def create_message(
|
|
session: AsyncSession,
|
|
*,
|
|
chat_id: UUID,
|
|
sender_id: UUID,
|
|
text: str,
|
|
) -> Message:
|
|
"""INSERT сообщения и flush; id и created_at назначает сервер, не клиент.
|
|
|
|
Алгоритм: message = Message(...); session.add(message); await session.flush(); return message.
|
|
"""
|
|
raise NotImplementedError("TODO")
|
|
|
|
|
|
async def list_messages(
|
|
session: AsyncSession,
|
|
chat_id: UUID,
|
|
after: Position | None,
|
|
limit: int,
|
|
) -> list[Message]:
|
|
"""Сообщения чата по (created_at, id) по возрастанию, строго после `after`.
|
|
|
|
Алгоритм:
|
|
1. stmt = select(Message).where(Message.chat_id == chat_id)
|
|
2. если after: stmt = stmt.where(tuple_(Message.created_at, Message.id) > tuple_(*after))
|
|
3. stmt = stmt.order_by(Message.created_at, Message.id).limit(limit)
|
|
4. result = await session.execute(stmt); return list(result.scalars().all())
|
|
Keyset под индекс (chat_id, created_at, id), без OFFSET. Вызывающий передаёт limit + 1.
|
|
"""
|
|
raise NotImplementedError("TODO")
|
|
|
|
|
|
async def count_messages(session: AsyncSession) -> int:
|
|
"""Общее число сообщений — для лимита MAX_MESSAGES (503).
|
|
|
|
Алгоритм (простой): result = await session.execute(select(func.count()).select_from(Message));
|
|
return result.scalar_one().
|
|
count(*) — O(n) на каждую отправку. Альтернативы: оценка из pg_class.reltuples
|
|
или таблица-счётчик в той же транзакции. Выберите и обоснуйте в отчёте.
|
|
"""
|
|
raise NotImplementedError("TODO")
|