Files
mtusi2026lab2/app/repositories/messages.py
T

44 lines
1.2 KiB
Python

from datetime import datetime
from uuid import UUID
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from ..db.models import Message
async def create(
db: AsyncSession, chat_id: UUID, sender_id: UUID, text: str
) -> Message:
msg = Message(chat_id=chat_id, sender_id=sender_id, text=text)
db.add(msg)
await db.commit()
await db.refresh(msg)
return msg
async def list_page(
db: AsyncSession,
chat_id: UUID,
limit: int,
cursor: tuple[datetime, UUID] | None,
) -> tuple[list[Message], tuple[datetime, UUID] | None]:
stmt = (
select(Message)
.where(Message.chat_id == chat_id)
.order_by(Message.created_at.asc(), Message.id.asc())
.limit(limit + 1)
)
if cursor is not None:
c_created, c_id = cursor
stmt = stmt.where(
(Message.created_at > c_created)
| ((Message.created_at == c_created) & (Message.id > c_id))
)
rows = list((await db.execute(stmt)).scalars().all())
next_cursor = None
if len(rows) > limit:
rows = rows[:limit]
last = rows[-1]
next_cursor = (last.created_at, last.id)
return rows, next_cursor