28 lines
898 B
Python
28 lines
898 B
Python
import uuid
|
|
|
|
from sqlalchemy import select, tuple_
|
|
from sqlalchemy.orm import Session
|
|
|
|
from models import Message
|
|
from utils.pagination import Position
|
|
|
|
|
|
def create_message(db: Session, chat_id: uuid.UUID, sender_id: uuid.UUID, text: str) -> Message:
|
|
message = Message(chat_id=chat_id, sender_id=sender_id, text=text)
|
|
db.add(message)
|
|
db.commit()
|
|
return message
|
|
|
|
|
|
def list_messages(db: Session, chat_id: uuid.UUID, limit: int, after: Position | None) -> list[Message]:
|
|
# Keyset-пагинация по индексу messages_chat_history_idx (chat_id, created_at, id).
|
|
query = (
|
|
select(Message)
|
|
.where(Message.chat_id == chat_id)
|
|
.order_by(Message.created_at, Message.id)
|
|
.limit(limit + 1)
|
|
)
|
|
if after is not None:
|
|
query = query.where(tuple_(Message.created_at, Message.id) > tuple_(*after))
|
|
return list(db.scalars(query))
|