add async with all functions
This commit is contained in:
+20
-12
@@ -1,41 +1,49 @@
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.message import Message
|
||||
from app.storage.types import Position
|
||||
|
||||
|
||||
def create_message(
|
||||
session: Session,
|
||||
async def create_message(
|
||||
session: AsyncSession,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
sender_id: UUID,
|
||||
text: str,
|
||||
) -> Message:
|
||||
"""INSERT сообщения и flush(); id и created_at назначает сервер, не клиент."""
|
||||
"""INSERT сообщения и flush; id и created_at назначает сервер, не клиент.
|
||||
|
||||
Алгоритм: message = Message(...); session.add(message); await session.flush(); return message.
|
||||
"""
|
||||
raise NotImplementedError("TODO")
|
||||
|
||||
|
||||
def list_messages(
|
||||
session: Session,
|
||||
async def list_messages(
|
||||
session: AsyncSession,
|
||||
chat_id: UUID,
|
||||
after: Position | None,
|
||||
limit: int,
|
||||
) -> list[Message]:
|
||||
"""Сообщения чата по (created_at, id) по возрастанию, строго после `after`.
|
||||
|
||||
Это keyset-запрос под индекс (chat_id, created_at, id): никакого OFFSET.
|
||||
Вызывающий передаёт limit + 1 (признак следующей страницы).
|
||||
Алгоритм:
|
||||
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")
|
||||
|
||||
|
||||
def count_messages(session: Session) -> int:
|
||||
async def count_messages(session: AsyncSession) -> int:
|
||||
"""Общее число сообщений — для лимита MAX_MESSAGES (503).
|
||||
|
||||
Решение для отчёта: SELECT count(*) честный, но O(n) на каждую отправку.
|
||||
Альтернативы: приблизительная оценка из pg_class.reltuples или отдельная
|
||||
таблица-счётчик, обновляемая в той же транзакции. Выберите и обоснуйте.
|
||||
Алгоритм (простой): result = await session.execute(select(func.count()).select_from(Message));
|
||||
return result.scalar_one().
|
||||
count(*) — O(n) на каждую отправку. Альтернативы: оценка из pg_class.reltuples
|
||||
или таблица-счётчик в той же транзакции. Выберите и обоснуйте в отчёте.
|
||||
"""
|
||||
raise NotImplementedError("TODO")
|
||||
|
||||
Reference in New Issue
Block a user