forked from mtusi2026/mtusi2026lab4
48 lines
2.2 KiB
Python
48 lines
2.2 KiB
Python
import json
|
|
from uuid import UUID
|
|
import asyncpg
|
|
from domain import AttachmentSchema, VariantSchema
|
|
from infrastructure.utils import Pool, repository_logs
|
|
from interfaces import AttachmentRepository
|
|
|
|
class PostgresAttachmentRepository(AttachmentRepository):
|
|
def __init__(self, pool: Pool) -> None:
|
|
self._pool = pool
|
|
|
|
@repository_logs
|
|
async def create(self, attachment: AttachmentSchema) -> AttachmentSchema:
|
|
query = """
|
|
INSERT INTO attachments
|
|
(id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, error_code, variants)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10::jsonb)
|
|
RETURNING created_at, updated_at;
|
|
"""
|
|
variants_json = json.dumps([v.model_dump(mode="json") for v in attachment.variants])
|
|
async with self._pool.acquire() as conn:
|
|
row = await conn.fetchrow(
|
|
query, attachment.id, attachment.chat_id, attachment.owner_id,
|
|
attachment.filename, attachment.content_type, attachment.size_bytes,
|
|
attachment.sha256, attachment.status, attachment.error_code, variants_json
|
|
)
|
|
assert row is not None
|
|
return attachment.model_copy(update={"created_at": row["created_at"], "updated_at": row["updated_at"]})
|
|
|
|
@repository_logs
|
|
async def get_by_id(self, attachment_id: UUID) -> AttachmentSchema | None:
|
|
query = """
|
|
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, error_code, variants, created_at, updated_at
|
|
FROM attachments WHERE id = $1;
|
|
"""
|
|
async with self._pool.acquire() as conn:
|
|
row = await conn.fetchrow(query, attachment_id)
|
|
if row is None:
|
|
return None
|
|
|
|
variants = [VariantSchema(**v) for v in json.loads(row["variants"])]
|
|
return AttachmentSchema(
|
|
id=row["id"], chat_id=row["chat_id"], owner_id=row["owner_id"],
|
|
filename=row["filename"], content_type=row["content_type"],
|
|
size_bytes=row["size_bytes"], sha256=row["sha256"], status=row["status"],
|
|
error_code=row["error_code"], variants=variants,
|
|
created_at=row["created_at"], updated_at=row["updated_at"]
|
|
) |