chore: port lab 4 solution into the lab 5 skeleton
Source: mtusi2026lab4-safronov, solution/bvt2301-safronov, 2546deb. Contracts, public tests and evidence of lab 4 are not carried over. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,122 @@
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import Uuid, func, insert, select, tuple_
|
||||
from sqlalchemy.dialects.postgresql import ARRAY
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.infra.db.models import Message, MessageAttachment
|
||||
from src.schemas import dataclasses
|
||||
from src.utils.cursor import CursorKey
|
||||
|
||||
# вложения сообщения в порядке отправки: коррелированный подзапрос по
|
||||
# первичному ключу `(message_id, position)` на каждую строку страницы,
|
||||
# индекс истории прежний (design change `attachments`, решение 8). Нет
|
||||
# вложений — пустой массив, а не NULL
|
||||
_ATTACHMENT_IDS = func.array(
|
||||
select(MessageAttachment.attachment_id)
|
||||
.where(MessageAttachment.message_id == Message.id)
|
||||
.order_by(MessageAttachment.position)
|
||||
.scalar_subquery(),
|
||||
type_=ARRAY(Uuid()),
|
||||
).label("attachment_ids")
|
||||
|
||||
# колонки MessageFullDTO; их же выбирает чтение сохранённого результата
|
||||
# ключа идемпотентности
|
||||
MESSAGE_COLUMNS = (
|
||||
Message.id,
|
||||
Message.chat_id,
|
||||
Message.sender_id,
|
||||
Message.text,
|
||||
Message.created_at,
|
||||
_ATTACHMENT_IDS,
|
||||
)
|
||||
|
||||
|
||||
def to_message_dto(fields: Mapping[str, Any]) -> dataclasses.MessageFullDTO:
|
||||
"""DTO из колонок `MESSAGE_COLUMNS`."""
|
||||
return dataclasses.MessageFullDTO(
|
||||
id=fields["id"],
|
||||
chat_id=fields["chat_id"],
|
||||
sender_id=fields["sender_id"],
|
||||
text=fields["text"],
|
||||
created_at=fields["created_at"],
|
||||
attachment_ids=tuple(fields["attachment_ids"]),
|
||||
)
|
||||
|
||||
|
||||
async def insert_message(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
message: dataclasses.MessageFullDTO,
|
||||
instance_id: str,
|
||||
) -> dataclasses.MessageFullDTO:
|
||||
"""Строка сообщения; `instance_id` — реплика, которая его записала
|
||||
(колонка только для диагностики, в DTO и ответ не попадает). Связи с
|
||||
вложениями пишет `insert_message_attachments`."""
|
||||
await db_session.execute(
|
||||
insert(Message).values(
|
||||
id=message.id,
|
||||
chat_id=message.chat_id,
|
||||
sender_id=message.sender_id,
|
||||
text=message.text,
|
||||
created_at=message.created_at,
|
||||
instance_id=instance_id,
|
||||
),
|
||||
)
|
||||
return message
|
||||
|
||||
|
||||
async def insert_message_attachments(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
message: dataclasses.MessageFullDTO,
|
||||
) -> int:
|
||||
"""Все связи одной вставкой; `position` — место в `attachment_ids`.
|
||||
|
||||
Вызывается только с непустым `attachment_ids`. `created_at` связи —
|
||||
время сообщения.
|
||||
"""
|
||||
result = await db_session.execute(
|
||||
insert(MessageAttachment).values(
|
||||
[
|
||||
{
|
||||
"message_id": message.id,
|
||||
"position": position,
|
||||
"attachment_id": attachment_id,
|
||||
"created_at": message.created_at,
|
||||
}
|
||||
for position, attachment_id in enumerate(
|
||||
message.attachment_ids,
|
||||
)
|
||||
],
|
||||
),
|
||||
)
|
||||
return result.rowcount
|
||||
|
||||
|
||||
async def get_chat_messages_page(
|
||||
db_session: AsyncSession,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
after: CursorKey | None,
|
||||
limit: int,
|
||||
) -> list[dataclasses.MessageFullDTO]:
|
||||
"""До `limit + 1` сообщений чата строго после ключа `after`.
|
||||
|
||||
Keyset по индексу `(chat_id, created_at, id)`, без OFFSET: страница
|
||||
не просматривает историю до курсора.
|
||||
"""
|
||||
statement = (
|
||||
select(*MESSAGE_COLUMNS)
|
||||
.where(Message.chat_id == chat_id)
|
||||
.order_by(Message.created_at, Message.id)
|
||||
.limit(limit + 1)
|
||||
)
|
||||
if after is not None:
|
||||
statement = statement.where(
|
||||
tuple_(Message.created_at, Message.id) > tuple_(*after),
|
||||
)
|
||||
rows = (await db_session.execute(statement)).all()
|
||||
return [to_message_dto(row._mapping) for row in rows]
|
||||
Reference in New Issue
Block a user