249 行
7.8 KiB
Python
249 行
7.8 KiB
Python
"""Repository for character_profiles."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from typing import Any
|
|
|
|
from backend.dto.profile_dto import CharacterProfile, ProfileListResult
|
|
from database.db_helper import Database
|
|
|
|
|
|
PROFILE_COLUMNS = """
|
|
profile_id,
|
|
name,
|
|
description,
|
|
base_prompt,
|
|
appearance_prompt,
|
|
style_prompt,
|
|
negative_prompt,
|
|
default_model_route,
|
|
owner_platform,
|
|
owner_context_id,
|
|
owner_user_id,
|
|
owner_session_key,
|
|
avatar_image_uri,
|
|
status,
|
|
metadata_json,
|
|
created_at,
|
|
updated_at
|
|
"""
|
|
|
|
|
|
class ProfileRepository:
|
|
def __init__(self, database: Database):
|
|
self.database = database
|
|
|
|
@property
|
|
def placeholder(self) -> str:
|
|
return self.database._placeholder
|
|
|
|
def create(self, payload: dict[str, Any]) -> CharacterProfile:
|
|
placeholder = self.placeholder
|
|
sql = f"""
|
|
INSERT INTO character_profiles (
|
|
profile_id,
|
|
name,
|
|
description,
|
|
base_prompt,
|
|
appearance_prompt,
|
|
style_prompt,
|
|
negative_prompt,
|
|
default_model_route,
|
|
owner_platform,
|
|
owner_context_id,
|
|
owner_user_id,
|
|
owner_session_key,
|
|
avatar_image_uri,
|
|
status,
|
|
metadata_json
|
|
) VALUES (
|
|
{placeholder}, {placeholder}, {placeholder}, {placeholder},
|
|
{placeholder}, {placeholder}, {placeholder}, {placeholder},
|
|
{placeholder}, {placeholder}, {placeholder}, {placeholder},
|
|
{placeholder}, {placeholder}, {placeholder}
|
|
)
|
|
"""
|
|
params = (
|
|
payload["profile_id"],
|
|
payload["name"],
|
|
payload.get("description"),
|
|
payload.get("base_prompt"),
|
|
payload.get("appearance_prompt"),
|
|
payload.get("style_prompt"),
|
|
payload.get("negative_prompt"),
|
|
payload.get("default_model_route"),
|
|
payload["owner_platform"],
|
|
payload.get("owner_context_id"),
|
|
payload["owner_user_id"],
|
|
payload.get("owner_session_key"),
|
|
payload.get("avatar_image_uri"),
|
|
payload.get("status", "active"),
|
|
_json_or_none(payload.get("metadata")),
|
|
)
|
|
conn = self.database.connect()
|
|
try:
|
|
conn.execute(sql, params)
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
profile = self.get(payload["profile_id"])
|
|
if profile is None:
|
|
raise RuntimeError("profile was inserted but could not be read back")
|
|
return profile
|
|
|
|
def get(self, profile_id: str) -> CharacterProfile | None:
|
|
placeholder = self.placeholder
|
|
conn = self.database.connect()
|
|
try:
|
|
row = conn.execute(
|
|
f"SELECT {PROFILE_COLUMNS} FROM character_profiles WHERE profile_id = {placeholder}",
|
|
(profile_id,),
|
|
).fetchone()
|
|
finally:
|
|
conn.close()
|
|
return _row_to_profile(row) if row else None
|
|
|
|
def list(
|
|
self,
|
|
*,
|
|
owner_user_id: str | None = None,
|
|
keyword: str | None = None,
|
|
status: str | None = "active",
|
|
page: int = 1,
|
|
page_size: int = 30,
|
|
) -> ProfileListResult:
|
|
where, params = self._build_filters(
|
|
owner_user_id=owner_user_id,
|
|
keyword=keyword,
|
|
status=status,
|
|
)
|
|
offset = max(page - 1, 0) * page_size
|
|
conn = self.database.connect()
|
|
try:
|
|
count_row = conn.execute(
|
|
f"SELECT COUNT(*) AS total FROM character_profiles {where}",
|
|
tuple(params),
|
|
).fetchone()
|
|
rows = conn.execute(
|
|
f"""
|
|
SELECT {PROFILE_COLUMNS}
|
|
FROM character_profiles
|
|
{where}
|
|
ORDER BY updated_at DESC, created_at DESC
|
|
LIMIT {int(page_size)} OFFSET {int(offset)}
|
|
""",
|
|
tuple(params),
|
|
).fetchall()
|
|
finally:
|
|
conn.close()
|
|
return ProfileListResult(
|
|
items=[_row_to_profile(row) for row in rows],
|
|
page=page,
|
|
page_size=page_size,
|
|
total=int(count_row["total"] if count_row else 0),
|
|
)
|
|
|
|
def update(self, profile_id: str, payload: dict[str, Any]) -> CharacterProfile | None:
|
|
allowed = {
|
|
"name",
|
|
"description",
|
|
"base_prompt",
|
|
"appearance_prompt",
|
|
"style_prompt",
|
|
"negative_prompt",
|
|
"default_model_route",
|
|
"owner_context_id",
|
|
"owner_session_key",
|
|
"avatar_image_uri",
|
|
"status",
|
|
"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 = _json_or_none(payload[key]) if key == "metadata" else payload[key]
|
|
assignments.append(f"{column} = {placeholder}")
|
|
params.append(value)
|
|
if not assignments:
|
|
return self.get(profile_id)
|
|
assignments.append("updated_at = CURRENT_TIMESTAMP")
|
|
params.append(profile_id)
|
|
conn = self.database.connect()
|
|
try:
|
|
conn.execute(
|
|
f"""
|
|
UPDATE character_profiles
|
|
SET {", ".join(assignments)}
|
|
WHERE profile_id = {placeholder}
|
|
""",
|
|
tuple(params),
|
|
)
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
return self.get(profile_id)
|
|
|
|
def soft_delete(self, profile_id: str) -> CharacterProfile | None:
|
|
return self.update(profile_id, {"status": "deleted"})
|
|
|
|
def _build_filters(
|
|
self,
|
|
*,
|
|
owner_user_id: str | None,
|
|
keyword: str | None,
|
|
status: str | None,
|
|
) -> tuple[str, list[Any]]:
|
|
placeholder = self.placeholder
|
|
clauses: list[str] = []
|
|
params: list[Any] = []
|
|
if owner_user_id:
|
|
clauses.append(f"owner_user_id = {placeholder}")
|
|
params.append(owner_user_id)
|
|
if status:
|
|
clauses.append(f"status = {placeholder}")
|
|
params.append(status)
|
|
if keyword:
|
|
clauses.append(
|
|
f"(name LIKE {placeholder} OR description LIKE {placeholder})"
|
|
)
|
|
like_value = f"%{keyword}%"
|
|
params.extend([like_value, like_value])
|
|
if not clauses:
|
|
return "", params
|
|
return "WHERE " + " AND ".join(clauses), params
|
|
|
|
|
|
def _row_to_profile(row) -> CharacterProfile:
|
|
metadata = {}
|
|
if row["metadata_json"]:
|
|
metadata = json.loads(row["metadata_json"])
|
|
return CharacterProfile(
|
|
profile_id=row["profile_id"],
|
|
name=row["name"],
|
|
description=row["description"],
|
|
base_prompt=row["base_prompt"],
|
|
appearance_prompt=row["appearance_prompt"],
|
|
style_prompt=row["style_prompt"],
|
|
negative_prompt=row["negative_prompt"],
|
|
default_model_route=row["default_model_route"],
|
|
owner_platform=row["owner_platform"],
|
|
owner_context_id=row["owner_context_id"],
|
|
owner_user_id=row["owner_user_id"],
|
|
owner_session_key=row["owner_session_key"],
|
|
avatar_image_uri=row["avatar_image_uri"],
|
|
status=row["status"],
|
|
metadata=metadata,
|
|
created_at=str(row["created_at"]),
|
|
updated_at=str(row["updated_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)
|