"""Repository for generation_images.""" from __future__ import annotations import json from typing import Any from backend.dto.image_dto import GenerationImage from database.db_helper import Database IMAGE_COLUMNS = """ image_id, profile_id, workflow_id, node_id, task_id, batch_id, version_tag, image_uri, thumbnail_uri, positive_prompt, negative_prompt, model_used, model_route, seed, width, height, is_selected, is_archived, metadata_json, created_at """ class ImageRepository: def __init__(self, database: Database): self.database = database @property def placeholder(self) -> str: return self.database._placeholder def create(self, payload: dict[str, Any]) -> GenerationImage: placeholder = self.placeholder conn = self.database.connect() try: conn.execute( f""" INSERT INTO generation_images ( image_id, profile_id, workflow_id, node_id, task_id, batch_id, version_tag, image_uri, thumbnail_uri, positive_prompt, negative_prompt, model_used, model_route, seed, width, height, is_selected, is_archived, metadata_json ) VALUES ( {placeholder}, {placeholder}, {placeholder}, {placeholder}, {placeholder}, {placeholder}, {placeholder}, {placeholder}, {placeholder}, {placeholder}, {placeholder}, {placeholder}, {placeholder}, {placeholder}, {placeholder}, {placeholder}, {placeholder}, {placeholder}, {placeholder} ) """, ( payload["image_id"], payload.get("profile_id"), payload.get("workflow_id"), payload.get("node_id"), payload.get("task_id"), payload.get("batch_id"), payload.get("version_tag"), payload["image_uri"], payload.get("thumbnail_uri"), payload.get("positive_prompt"), payload.get("negative_prompt"), payload.get("model_used"), payload.get("model_route"), payload.get("seed"), payload.get("width"), payload.get("height"), _bool_to_db(payload.get("is_selected", False)), _bool_to_db(payload.get("is_archived", False)), _json_or_none(payload.get("metadata")), ), ) conn.commit() finally: conn.close() image = self.get(payload["image_id"]) if image is None: raise RuntimeError("image was inserted but could not be read back") return image def get(self, image_id: str) -> GenerationImage | None: placeholder = self.placeholder conn = self.database.connect() try: row = conn.execute( f"SELECT {IMAGE_COLUMNS} FROM generation_images WHERE image_id = {placeholder}", (image_id,), ).fetchone() finally: conn.close() return _row_to_image(row) if row else None def list_by_node(self, node_id: str, include_archived: bool = False) -> list[GenerationImage]: placeholder = self.placeholder clauses = [f"node_id = {placeholder}"] params: list[Any] = [node_id] if not include_archived: clauses.append("is_archived = 0") conn = self.database.connect() try: rows = conn.execute( f""" SELECT {IMAGE_COLUMNS} FROM generation_images WHERE {" AND ".join(clauses)} ORDER BY created_at DESC """, tuple(params), ).fetchall() finally: conn.close() return [_row_to_image(row) for row in rows] def list_images( self, *, profile_id: str | None = None, workflow_id: str | None = None, include_archived: bool = True, page: int = 1, page_size: int = 60, ) -> tuple[list[GenerationImage], int]: placeholder = self.placeholder clauses: list[str] = [] params: list[Any] = [] if profile_id: clauses.append(f"profile_id = {placeholder}") params.append(profile_id) if workflow_id: clauses.append(f"workflow_id = {placeholder}") params.append(workflow_id) if not include_archived: clauses.append("is_archived = 0") where_clause = f"WHERE {' AND '.join(clauses)}" if clauses else "" normalized_page = max(page, 1) normalized_page_size = min(max(page_size, 1), 100) offset = (normalized_page - 1) * normalized_page_size conn = self.database.connect() try: total_row = conn.execute( f"SELECT COUNT(*) AS total FROM generation_images {where_clause}", tuple(params), ).fetchone() rows = conn.execute( f""" SELECT {IMAGE_COLUMNS} FROM generation_images {where_clause} ORDER BY is_archived ASC, created_at DESC, image_id DESC LIMIT {placeholder} OFFSET {placeholder} """, tuple(params + [normalized_page_size, offset]), ).fetchall() finally: conn.close() return [_row_to_image(row) for row in rows], int(total_row["total"] if total_row else 0) def update(self, image_id: str, payload: dict[str, Any]) -> GenerationImage | None: allowed = { "thumbnail_uri", "positive_prompt", "negative_prompt", "model_used", "model_route", "seed", "width", "height", "is_selected", "is_archived", "metadata", } assignments: list[str] = [] params: list[Any] = [] placeholder = self.placeholder for key in allowed: if key not in payload: continue column = "metadata_json" if key == "metadata" else key value = payload[key] if key == "metadata": value = _json_or_none(value) elif key in {"is_selected", "is_archived"}: value = _bool_to_db(value) assignments.append(f"{column} = {placeholder}") params.append(value) if not assignments: return self.get(image_id) params.append(image_id) conn = self.database.connect() try: conn.execute( f""" UPDATE generation_images SET {", ".join(assignments)} WHERE image_id = {placeholder} """, tuple(params), ) conn.commit() finally: conn.close() return self.get(image_id) def select_exclusive(self, image: GenerationImage) -> GenerationImage | None: placeholder = self.placeholder conn = self.database.connect() try: conn.execute( f""" UPDATE generation_images SET is_selected = 0 WHERE node_id = {placeholder} """, (image.node_id,), ) conn.execute( f""" UPDATE generation_images SET is_selected = 1 WHERE image_id = {placeholder} """, (image.image_id,), ) conn.commit() finally: conn.close() return self.get(image.image_id) def delete_metadata(self, image_id: str) -> GenerationImage | None: before = self.get(image_id) if before is None: return None placeholder = self.placeholder conn = self.database.connect() try: conn.execute( f"DELETE FROM generation_images WHERE image_id = {placeholder}", (image_id,), ) conn.commit() finally: conn.close() return before def _row_to_image(row) -> GenerationImage: return GenerationImage( image_id=row["image_id"], profile_id=row["profile_id"], workflow_id=row["workflow_id"], node_id=row["node_id"], task_id=row["task_id"], batch_id=row["batch_id"], version_tag=row["version_tag"], image_uri=row["image_uri"], thumbnail_uri=row["thumbnail_uri"], positive_prompt=row["positive_prompt"], negative_prompt=row["negative_prompt"], model_used=row["model_used"], model_route=row["model_route"], seed=int(row["seed"]) if row["seed"] is not None else None, width=int(row["width"]) if row["width"] is not None else None, height=int(row["height"]) if row["height"] is not None else None, is_selected=bool(row["is_selected"]), is_archived=bool(row["is_archived"]), metadata=_json_loads(row["metadata_json"]), created_at=str(row["created_at"]), ) def _json_or_none(value: Any | None) -> str | None: if value is None: return None return json.dumps(value, ensure_ascii=False, sort_keys=True) def _json_loads(value: str | None) -> dict[str, Any]: if not value: return {} return json.loads(value) def _bool_to_db(value: Any) -> int: return 1 if bool(value) else 0