forked from mtusi2026/mtusi2026lab3
71 lines
1.6 KiB
Python
71 lines
1.6 KiB
Python
import uuid
|
|
|
|
from datetime import datetime
|
|
|
|
from sqlalchemy import and_, or_, select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.db.models import Message
|
|
|
|
|
|
class MessageRepository:
|
|
|
|
def __init__(self, db: Session):
|
|
self.db = db
|
|
|
|
def get_by_id(
|
|
self,
|
|
message_id: uuid.UUID,
|
|
) -> Message | None:
|
|
statement = select(Message).where(
|
|
Message.id == message_id
|
|
)
|
|
|
|
return self.db.scalar(statement)
|
|
|
|
def create(
|
|
self,
|
|
chat_id: uuid.UUID,
|
|
sender_id: uuid.UUID,
|
|
text: str,
|
|
) -> Message:
|
|
message = Message(
|
|
chat_id=chat_id,
|
|
sender_id=sender_id,
|
|
text=text,
|
|
)
|
|
|
|
self.db.add(message)
|
|
self.db.flush()
|
|
|
|
return message
|
|
|
|
def get_history(
|
|
self,
|
|
chat_id: uuid.UUID,
|
|
limit: int = 50,
|
|
cursor_created_at: datetime | None = None,
|
|
cursor_id: uuid.UUID | None = None,
|
|
) -> list[Message]:
|
|
statement = select(Message).where(
|
|
Message.chat_id == chat_id
|
|
)
|
|
|
|
if cursor_created_at is not None and cursor_id is not None:
|
|
statement = statement.where(
|
|
or_(
|
|
Message.created_at > cursor_created_at,
|
|
and_(
|
|
Message.created_at == cursor_created_at,
|
|
Message.id > cursor_id,
|
|
),
|
|
)
|
|
)
|
|
|
|
statement = (
|
|
statement
|
|
.order_by(Message.created_at.asc(), Message.id.asc())
|
|
.limit(limit)
|
|
)
|
|
|
|
return list(self.db.scalars(statement).all()) |