Перенести реализацию лабораторной 4
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
from .attachments import AttachmentRepository
|
||||
from .chats import ChatRepository
|
||||
from .messages import MessageRepository
|
||||
from .users import UserRepository
|
||||
|
||||
__all__ = ['AttachmentRepository', 'ChatRepository', 'MessageRepository', 'UserRepository']
|
||||
@@ -0,0 +1,93 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from ..domain.models import Attachment
|
||||
from ..models.attachment import AttachmentRow
|
||||
from ..models.chat import ChatMemberRow, ChatRow
|
||||
|
||||
|
||||
class AttachmentRepository:
|
||||
def __init__(self, sessions: async_sessionmaker[AsyncSession]) -> None:
|
||||
self._sessions = sessions
|
||||
|
||||
@staticmethod
|
||||
def _to_domain(row: AttachmentRow) -> Attachment:
|
||||
return Attachment(
|
||||
id=row.id,
|
||||
chat_id=row.chat_id,
|
||||
owner_id=row.owner_id,
|
||||
filename=row.filename,
|
||||
object_key=row.object_key,
|
||||
content_type=row.content_type,
|
||||
size_bytes=row.size_bytes,
|
||||
sha256=row.sha256,
|
||||
width=row.width,
|
||||
height=row.height,
|
||||
status=row.status,
|
||||
error_code=row.error_code,
|
||||
created_at=row.created_at,
|
||||
updated_at=row.updated_at,
|
||||
)
|
||||
|
||||
async def chat_exists_for_member(self, chat_id: UUID, user_id: UUID) -> bool:
|
||||
async with self._sessions() as session:
|
||||
found = await session.scalar(
|
||||
select(ChatRow.id)
|
||||
.join(ChatMemberRow, ChatMemberRow.chat_id == ChatRow.id)
|
||||
.where(ChatRow.id == chat_id, ChatMemberRow.user_id == user_id)
|
||||
)
|
||||
return found is not None
|
||||
|
||||
async def create(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
chat_id: UUID,
|
||||
owner_id: UUID,
|
||||
filename: str,
|
||||
object_key: str,
|
||||
content_type: str,
|
||||
size_bytes: int,
|
||||
sha256: str,
|
||||
width: int,
|
||||
height: int,
|
||||
now: datetime,
|
||||
) -> Attachment:
|
||||
row = AttachmentRow(
|
||||
id=attachment_id,
|
||||
chat_id=chat_id,
|
||||
owner_id=owner_id,
|
||||
filename=filename,
|
||||
object_key=object_key,
|
||||
content_type=content_type,
|
||||
size_bytes=size_bytes,
|
||||
sha256=sha256,
|
||||
width=width,
|
||||
height=height,
|
||||
status='ready',
|
||||
error_code=None,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
async with self._sessions() as session:
|
||||
async with session.begin():
|
||||
session.add(row)
|
||||
await session.flush()
|
||||
return self._to_domain(row)
|
||||
|
||||
async def get_for_member(self, attachment_id: UUID, user_id: UUID) -> Attachment | None:
|
||||
async with self._sessions() as session:
|
||||
row = await session.scalar(
|
||||
select(AttachmentRow)
|
||||
.join(ChatMemberRow, ChatMemberRow.chat_id == AttachmentRow.chat_id)
|
||||
.where(
|
||||
AttachmentRow.id == attachment_id,
|
||||
ChatMemberRow.user_id == user_id,
|
||||
)
|
||||
)
|
||||
return self._to_domain(row) if row is not None else None
|
||||
@@ -0,0 +1,69 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Sequence
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import select, tuple_
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from ..domain.errors import Invalid
|
||||
from ..domain.models import Chat, Keyset
|
||||
from ..models.chat import ChatMemberRow, ChatRow
|
||||
from ..models.user import UserRow
|
||||
|
||||
|
||||
class ChatRepository:
|
||||
def __init__(self, sessions: async_sessionmaker[AsyncSession]) -> None:
|
||||
self._sessions = sessions
|
||||
|
||||
@staticmethod
|
||||
def _to_domain(row: ChatRow, member_ids: Sequence[UUID]) -> Chat:
|
||||
return Chat(id=row.id, title=row.title, member_ids=tuple(member_ids), created_at=row.created_at)
|
||||
|
||||
@staticmethod
|
||||
async def _members(session: AsyncSession, chat_id: UUID) -> tuple[UUID, ...]:
|
||||
result = await session.scalars(
|
||||
select(ChatMemberRow.user_id)
|
||||
.where(ChatMemberRow.chat_id == chat_id)
|
||||
.order_by(ChatMemberRow.user_id)
|
||||
)
|
||||
return tuple(result)
|
||||
|
||||
async def create(self, chat_id: UUID, title: str, member_ids: Sequence[UUID], created_at: datetime) -> Chat:
|
||||
async with self._sessions() as session:
|
||||
async with session.begin():
|
||||
found = set(await session.scalars(select(UserRow.id).where(UserRow.id.in_(member_ids))))
|
||||
if len(found) != len(member_ids):
|
||||
raise Invalid(f'member_ids содержит неизвестных участников: {len(member_ids) - len(found)}')
|
||||
row = ChatRow(id=chat_id, title=title, created_at=created_at)
|
||||
session.add(row)
|
||||
await session.flush()
|
||||
session.add_all(ChatMemberRow(chat_id=chat_id, user_id=user_id) for user_id in member_ids)
|
||||
await session.flush()
|
||||
return self._to_domain(row, member_ids)
|
||||
|
||||
async def get_for_member(self, chat_id: UUID, user_id: UUID) -> Chat | None:
|
||||
async with self._sessions() as session:
|
||||
row = await session.scalar(
|
||||
select(ChatRow)
|
||||
.join(ChatMemberRow, ChatMemberRow.chat_id == ChatRow.id)
|
||||
.where(ChatRow.id == chat_id, ChatMemberRow.user_id == user_id)
|
||||
)
|
||||
if row is None:
|
||||
return None
|
||||
return self._to_domain(row, await self._members(session, row.id))
|
||||
|
||||
async def page_for_member(self, user_id: UUID, after: Keyset | None, limit: int) -> list[Chat]:
|
||||
async with self._sessions() as session:
|
||||
query = (
|
||||
select(ChatRow)
|
||||
.join(ChatMemberRow, ChatMemberRow.chat_id == ChatRow.id)
|
||||
.where(ChatMemberRow.user_id == user_id)
|
||||
.order_by(ChatRow.created_at, ChatRow.id)
|
||||
.limit(limit)
|
||||
)
|
||||
if after is not None:
|
||||
query = query.where(tuple_(ChatRow.created_at, ChatRow.id) > tuple_(after.created_at, after.id))
|
||||
rows = list((await session.scalars(query)).all())
|
||||
return [self._to_domain(row, await self._members(session, row.id)) for row in rows]
|
||||
@@ -0,0 +1,149 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Sequence
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import select, tuple_
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from ..domain.errors import Conflict, NotFound
|
||||
from ..domain.models import Keyset, Message
|
||||
from ..models.attachment import AttachmentRow, MessageAttachmentRow
|
||||
from ..models.chat import ChatMemberRow, ChatRow
|
||||
from ..models.message import MessageRow
|
||||
|
||||
|
||||
class MessageRepository:
|
||||
def __init__(self, sessions: async_sessionmaker[AsyncSession]) -> None:
|
||||
self._sessions = sessions
|
||||
|
||||
@staticmethod
|
||||
def _to_domain(row: MessageRow, attachment_ids: Sequence[UUID]) -> Message:
|
||||
return Message(
|
||||
id=row.id,
|
||||
chat_id=row.chat_id,
|
||||
sender_id=row.sender_id,
|
||||
text=row.text,
|
||||
created_at=row.created_at,
|
||||
attachment_ids=tuple(attachment_ids),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
async def _attachment_ids(session: AsyncSession, message_id: UUID) -> tuple[UUID, ...]:
|
||||
result = await session.scalars(
|
||||
select(MessageAttachmentRow.attachment_id)
|
||||
.where(MessageAttachmentRow.message_id == message_id)
|
||||
.order_by(MessageAttachmentRow.position)
|
||||
)
|
||||
return tuple(result)
|
||||
|
||||
@staticmethod
|
||||
async def _accessible_chat_id(session: AsyncSession, chat_id: UUID, user_id: UUID) -> UUID | None:
|
||||
return await session.scalar(
|
||||
select(ChatRow.id)
|
||||
.join(ChatMemberRow, ChatMemberRow.chat_id == ChatRow.id)
|
||||
.where(ChatRow.id == chat_id, ChatMemberRow.user_id == user_id)
|
||||
)
|
||||
|
||||
async def create_for_member(
|
||||
self,
|
||||
message_id: UUID,
|
||||
chat_id: UUID,
|
||||
sender_id: UUID,
|
||||
text: str,
|
||||
attachment_ids: Sequence[UUID],
|
||||
created_at: datetime,
|
||||
idempotency_key: str,
|
||||
) -> Message | None:
|
||||
async with self._sessions() as session:
|
||||
async with session.begin():
|
||||
accessible_chat_id = await self._accessible_chat_id(session, chat_id, sender_id)
|
||||
if accessible_chat_id is None:
|
||||
return None
|
||||
|
||||
if attachment_ids:
|
||||
found = {
|
||||
attachment_id: status
|
||||
for attachment_id, status in (
|
||||
await session.execute(
|
||||
select(AttachmentRow.id, AttachmentRow.status).where(
|
||||
AttachmentRow.id.in_(attachment_ids),
|
||||
AttachmentRow.chat_id == accessible_chat_id,
|
||||
)
|
||||
)
|
||||
).all()
|
||||
}
|
||||
if set(found) != set(attachment_ids):
|
||||
raise NotFound('вложение не найдено')
|
||||
if any(status != 'ready' for status in found.values()):
|
||||
raise Conflict('оригинал вложения недоступен')
|
||||
|
||||
statement = (
|
||||
insert(MessageRow)
|
||||
.values(
|
||||
id=message_id,
|
||||
chat_id=accessible_chat_id,
|
||||
sender_id=sender_id,
|
||||
text=text,
|
||||
created_at=created_at,
|
||||
idempotency_key=idempotency_key,
|
||||
)
|
||||
.on_conflict_do_nothing(
|
||||
index_elements=[
|
||||
MessageRow.sender_id,
|
||||
MessageRow.chat_id,
|
||||
MessageRow.idempotency_key,
|
||||
]
|
||||
)
|
||||
.returning(MessageRow.id)
|
||||
)
|
||||
created_id = await session.scalar(statement)
|
||||
if created_id is not None:
|
||||
row = await session.get(MessageRow, created_id)
|
||||
session.add_all(
|
||||
MessageAttachmentRow(
|
||||
message_id=created_id,
|
||||
attachment_id=attachment_id,
|
||||
position=position,
|
||||
)
|
||||
for position, attachment_id in enumerate(attachment_ids)
|
||||
)
|
||||
await session.flush()
|
||||
result_attachment_ids = tuple(attachment_ids)
|
||||
else:
|
||||
row = await session.scalar(
|
||||
select(MessageRow).where(
|
||||
MessageRow.sender_id == sender_id,
|
||||
MessageRow.chat_id == accessible_chat_id,
|
||||
MessageRow.idempotency_key == idempotency_key,
|
||||
)
|
||||
)
|
||||
if row is None:
|
||||
raise RuntimeError('результат идемпотентной операции не найден')
|
||||
result_attachment_ids = await self._attachment_ids(session, row.id)
|
||||
if row.text != text or result_attachment_ids != tuple(attachment_ids):
|
||||
raise Conflict('Idempotency-Key уже использован с другим сообщением')
|
||||
return self._to_domain(row, result_attachment_ids)
|
||||
|
||||
async def page_for_member(
|
||||
self, chat_id: UUID, user_id: UUID, after: Keyset | None, limit: int
|
||||
) -> list[Message] | None:
|
||||
async with self._sessions() as session:
|
||||
accessible_chat_id = await self._accessible_chat_id(session, chat_id, user_id)
|
||||
if accessible_chat_id is None:
|
||||
return None
|
||||
query = (
|
||||
select(MessageRow)
|
||||
.where(MessageRow.chat_id == accessible_chat_id)
|
||||
.order_by(MessageRow.created_at, MessageRow.id)
|
||||
.limit(limit)
|
||||
)
|
||||
if after is not None:
|
||||
query = query.where(tuple_(MessageRow.created_at, MessageRow.id) > tuple_(after.created_at, after.id))
|
||||
rows = list((await session.scalars(query)).all())
|
||||
return [
|
||||
self._to_domain(row, await self._attachment_ids(session, row.id))
|
||||
for row in rows
|
||||
]
|
||||
@@ -0,0 +1,53 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from ..domain.errors import Conflict
|
||||
from ..domain.models import User
|
||||
from ..models.user import UserRow
|
||||
|
||||
|
||||
class UserRepository:
|
||||
def __init__(self, sessions: async_sessionmaker[AsyncSession]) -> None:
|
||||
self._sessions = sessions
|
||||
|
||||
@staticmethod
|
||||
def _to_domain(row: UserRow) -> User:
|
||||
return User(id=row.id, username=row.username, display_name=row.display_name, created_at=row.created_at)
|
||||
|
||||
async def register(
|
||||
self, user_id: UUID, username: str, display_name: str, password_hash: str, created_at: datetime
|
||||
) -> User:
|
||||
row = UserRow(
|
||||
id=user_id,
|
||||
username=username,
|
||||
display_name=display_name,
|
||||
password_hash=password_hash,
|
||||
created_at=created_at,
|
||||
)
|
||||
try:
|
||||
async with self._sessions() as session:
|
||||
async with session.begin():
|
||||
session.add(row)
|
||||
await session.flush()
|
||||
except IntegrityError as exc:
|
||||
raise Conflict('username уже занят') from exc
|
||||
return self._to_domain(row)
|
||||
|
||||
async def get_by_id(self, user_id: UUID) -> User | None:
|
||||
async with self._sessions() as session:
|
||||
row = await session.get(UserRow, user_id)
|
||||
return self._to_domain(row) if row is not None else None
|
||||
|
||||
async def get_credentials(self, username: str) -> UserRow | None:
|
||||
async with self._sessions() as session:
|
||||
return await session.scalar(select(UserRow).where(UserRow.username == username))
|
||||
|
||||
@classmethod
|
||||
def to_domain(cls, row: UserRow) -> User:
|
||||
return cls._to_domain(row)
|
||||
Reference in New Issue
Block a user