acupedia-api/app/bootstrap/seed_media/repository.py

417 lines
12 KiB
Python

from __future__ import annotations
from dataclasses import dataclass
import json
from pathlib import PurePosixPath
from typing import Any
from uuid import UUID
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession
from ..seed_content.schema import CONTENT_SCHEMA, resolve_content_schema
@dataclass(frozen=True)
class ContentTarget:
content_id: UUID
source_key: str
module_code: str
template_code: str
@dataclass(frozen=True)
class MediaAssetRow:
id: UUID
storage_key: str
sha256: str | None
class ImageSeedRepository:
"""
Repository aligned with the AccuPedia four-schema architecture; all media and content tables are owned by the content schema.
Current schema notes:
- media_assets has no physical `sha256` column.
SHA-256 is persisted in media_assets.metadata["sha256"].
- media_assets has no physical `bucket` column.
Bucket name is persisted in media_assets.metadata["bucket"].
- content_media has no alt_text/metadata/updated_at columns.
alt_text is stored on media_assets.
- content_media v2 identity is:
(content_id, media_asset_id, usage_type)
"""
def __init__(
self,
session: AsyncSession,
*,
schema: str = CONTENT_SCHEMA,
) -> None:
self.session = session
self._schema = resolve_content_schema(schema)
async def resolve_content_target(
self,
*,
module_code: str,
template_code: str,
source_key: str,
) -> ContentTarget | None:
stmt = text(f"""
SELECT
ci.id AS content_id,
ci.source_key,
m.code AS module_code,
ads.code AS template_code
FROM {self._schema}.content_items ci
JOIN {self._schema}.module_contents mc
ON mc.content_id = ci.id
JOIN {self._schema}.modules m
ON m.id = mc.module_id
JOIN {self._schema}.attribute_definition_sets ads
ON ads.id = ci.attribute_definition_set_id
WHERE m.code = :module_code
AND ads.code = :template_code
AND ci.source_key = :source_key
LIMIT 2
""")
rows = (
await self.session.execute(
stmt,
{
"module_code": module_code,
"template_code": template_code,
"source_key": source_key,
},
)
).mappings().all()
if not rows:
return None
if len(rows) > 1:
raise RuntimeError(
"Content target resolution is ambiguous: "
f"{module_code}/{template_code}/{source_key}"
)
row = rows[0]
return ContentTarget(
content_id=row["content_id"],
source_key=row["source_key"],
module_code=row["module_code"],
template_code=row["template_code"],
)
async def get_media_asset_by_storage_key(
self,
storage_key: str,
) -> MediaAssetRow | None:
"""
Resolve one media asset by canonical object-storage key.
SHA-256 is stored inside media_assets.metadata JSONB because the
current production schema does not have a dedicated sha256 column.
"""
stmt = text(f"""
SELECT
id,
storage_key,
metadata ->> 'sha256' AS sha256
FROM {self._schema}.media_assets
WHERE storage_key = :storage_key
ORDER BY created_at, id
LIMIT 2
""")
rows = (
await self.session.execute(
stmt,
{"storage_key": storage_key},
)
).mappings().all()
if not rows:
return None
if len(rows) > 1:
raise RuntimeError(
"Multiple media_assets rows use the same storage_key: "
f"{storage_key!r}. Deduplicate before seeding."
)
row = rows[0]
return MediaAssetRow(
id=row["id"],
storage_key=row["storage_key"],
sha256=row["sha256"],
)
async def upsert_media_asset(
self,
*,
storage_key: str,
bucket: str,
original_filename: str,
mime_type: str,
file_size: int,
sha256: str,
width: int,
height: int,
alt_text: str | None,
metadata: dict[str, Any],
) -> MediaAssetRow:
"""
Idempotently create/update media_assets by storage_key.
We deliberately do not use ON CONFLICT(storage_key) because the
current canonical schema defines storage_key as TEXT but does not
guarantee a UNIQUE constraint/index in the base table definition.
"""
effective_metadata = dict(metadata)
effective_metadata.update(
{
"sha256": sha256,
"bucket": bucket,
}
)
lookup_stmt = text(f"""
SELECT
id,
storage_key,
metadata ->> 'sha256' AS sha256
FROM {self._schema}.media_assets
WHERE storage_key = :storage_key
ORDER BY created_at, id
FOR UPDATE
""")
existing_rows = (
await self.session.execute(
lookup_stmt,
{"storage_key": storage_key},
)
).mappings().all()
if len(existing_rows) > 1:
raise RuntimeError(
"Multiple media_assets rows use the same storage_key: "
f"{storage_key!r}. Deduplicate before seeding."
)
file_name = PurePosixPath(storage_key).name
metadata_json = json.dumps(effective_metadata)
if existing_rows:
media_asset_id = existing_rows[0]["id"]
update_stmt = text(f"""
UPDATE {self._schema}.media_assets
SET
media_kind = CAST('image' AS {self._schema}.media_kind_enum),
file_name = :file_name,
file_path = :storage_key,
original_filename = :original_filename,
storage_key = :storage_key,
mime_type = :mime_type,
file_size = :file_size,
file_size_bytes = :file_size,
width = :width,
width_px = :width,
height = :height,
height_px = :height,
alt_text = :alt_text,
status = 'active',
metadata = CAST(:metadata AS jsonb),
updated_at = now()
WHERE id = :media_asset_id
RETURNING
id,
storage_key,
metadata ->> 'sha256' AS sha256
""")
row = (
await self.session.execute(
update_stmt,
{
"media_asset_id": media_asset_id,
"file_name": file_name,
"storage_key": storage_key,
"original_filename": original_filename,
"mime_type": mime_type,
"file_size": file_size,
"width": width,
"height": height,
"alt_text": alt_text,
"metadata": metadata_json,
},
)
).mappings().one()
else:
insert_stmt = text(f"""
INSERT INTO {self._schema}.media_assets (
media_kind,
file_name,
file_path,
original_filename,
storage_key,
mime_type,
file_size,
file_size_bytes,
width,
width_px,
height,
height_px,
alt_text,
status,
metadata,
created_at,
updated_at
)
VALUES (
CAST('image' AS {self._schema}.media_kind_enum),
:file_name,
:storage_key,
:original_filename,
:storage_key,
:mime_type,
:file_size,
:file_size,
:width,
:width,
:height,
:height,
:alt_text,
'active',
CAST(:metadata AS jsonb),
now(),
now()
)
RETURNING
id,
storage_key,
metadata ->> 'sha256' AS sha256
""")
row = (
await self.session.execute(
insert_stmt,
{
"file_name": file_name,
"storage_key": storage_key,
"original_filename": original_filename,
"mime_type": mime_type,
"file_size": file_size,
"width": width,
"height": height,
"alt_text": alt_text,
"metadata": metadata_json,
},
)
).mappings().one()
return MediaAssetRow(
id=row["id"],
storage_key=row["storage_key"],
sha256=row["sha256"],
)
async def ensure_single_primary(
self,
*,
content_id: UUID,
media_asset_id: UUID,
) -> None:
stmt = text(f"""
SELECT media_asset_id
FROM {self._schema}.content_media
WHERE content_id = :content_id
AND media_role = 'primary'
AND media_asset_id IS NOT NULL
AND media_asset_id <> :media_asset_id
LIMIT 1
""")
existing = (
await self.session.execute(
stmt,
{
"content_id": content_id,
"media_asset_id": media_asset_id,
},
)
).scalar_one_or_none()
if existing is not None:
raise RuntimeError(
f"Content {content_id} already has a different primary media asset"
)
async def upsert_content_media(
self,
*,
content_id: UUID,
media_asset_id: UUID,
media_role: str,
usage_type: str,
sort_order: int,
alt_text: str | None,
caption: str | None,
metadata: dict[str, Any],
) -> None:
"""
Upsert the content/media association using the current v2 unique key.
`alt_text` and association `metadata` are intentionally not written
here because the current content_media table has no such columns.
alt_text is persisted on media_assets by upsert_media_asset().
"""
del alt_text
del metadata
stmt = text(f"""
INSERT INTO {self._schema}.content_media (
content_id,
media_asset_id,
media_role,
usage_type,
sort_order,
caption,
created_at
)
VALUES (
:content_id,
:media_asset_id,
:media_role,
:usage_type,
:sort_order,
:caption,
now()
)
ON CONFLICT (content_id, media_asset_id, usage_type)
DO UPDATE SET
media_role = EXCLUDED.media_role,
sort_order = EXCLUDED.sort_order,
caption = EXCLUDED.caption
""")
await self.session.execute(
stmt,
{
"content_id": content_id,
"media_asset_id": media_asset_id,
"media_role": media_role,
"usage_type": usage_type,
"sort_order": sort_order,
"caption": caption,
},
)