107 lines
4.2 KiB
Python
107 lines
4.2 KiB
Python
# app/repositories/chat_repository.py
|
|
"""
|
|
HealthSync AI 채팅 데이터 리포지토리
|
|
"""
|
|
from typing import Dict, Any, Optional, List
|
|
from datetime import datetime
|
|
from app.repositories.queries.chat_queries import ChatQueries
|
|
import logging
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class ChatRepository:
|
|
"""채팅 데이터 DB 조회/저장 리포지토리"""
|
|
|
|
@staticmethod
|
|
def _get_db():
|
|
"""simple_db를 lazy import로 가져오기 (순환 import 방지)"""
|
|
from app.utils.database_utils import simple_db
|
|
return simple_db
|
|
|
|
@staticmethod
|
|
async def save_chat_message(user_id: int, message_type: str,
|
|
message_content: Optional[str] = None,
|
|
response_content: Optional[str] = None) -> int:
|
|
"""채팅 메시지 저장 및 ID 반환"""
|
|
try:
|
|
simple_db = ChatRepository._get_db()
|
|
|
|
chat_data = {
|
|
"member_serial_number": user_id,
|
|
"message_type": message_type,
|
|
"message_content": message_content,
|
|
"response_content": response_content,
|
|
"created_at": datetime.now()
|
|
}
|
|
|
|
logger.info(f"채팅 메시지 저장 시도 - user_id: {user_id}, type: {message_type}")
|
|
|
|
# INSERT ... RETURNING 쿼리 실행
|
|
result = await simple_db.execute_insert_with_return(
|
|
ChatQueries.INSERT_CHAT_MESSAGE_WITH_RETURN,
|
|
chat_data
|
|
)
|
|
|
|
if result and "message_id" in result:
|
|
message_id = result["message_id"]
|
|
logger.info(f"채팅 메시지 저장 성공 - message_id: {message_id}, user_id: {user_id}")
|
|
return message_id
|
|
else:
|
|
raise Exception("INSERT RETURNING에서 message_id 반환되지 않음")
|
|
|
|
except Exception as e:
|
|
logger.error(f"채팅 메시지 저장 실패 - user_id: {user_id}, error: {str(e)}")
|
|
logger.error(f"저장 시도 데이터: {chat_data}")
|
|
raise Exception(f"채팅 메시지 저장 실패: {str(e)}")
|
|
|
|
@staticmethod
|
|
async def update_chat_message_response(message_id: int, response_content: str) -> bool:
|
|
"""채팅 메시지 응답 내용 업데이트"""
|
|
try:
|
|
simple_db = ChatRepository._get_db()
|
|
|
|
update_data = {
|
|
"message_id": message_id,
|
|
"response_content": response_content,
|
|
"updated_at": datetime.now()
|
|
}
|
|
|
|
logger.info(f"채팅 메시지 응답 업데이트 시도 - message_id: {message_id}")
|
|
|
|
# UPDATE 쿼리 실행
|
|
affected_rows = await simple_db.execute_insert_update(
|
|
ChatQueries.UPDATE_CHAT_MESSAGE_RESPONSE,
|
|
update_data
|
|
)
|
|
|
|
# None 체크 추가
|
|
if affected_rows is not None and affected_rows > 0:
|
|
logger.info(f"채팅 메시지 응답 업데이트 성공 - message_id: {message_id}, affected_rows: {affected_rows}")
|
|
return True
|
|
else:
|
|
logger.warning(
|
|
f"채팅 메시지 응답 업데이트 실패 - 영향받은 행이 없음: message_id={message_id}, affected_rows={affected_rows}")
|
|
return False
|
|
|
|
except Exception as e:
|
|
logger.error(f"채팅 메시지 응답 업데이트 실패 - message_id: {message_id}, error: {str(e)}")
|
|
# 업데이트 실패해도 예외를 발생시키지 않고 False만 반환
|
|
return False
|
|
|
|
@staticmethod
|
|
async def get_chat_history_by_user_id(user_id: int) -> List[Dict[str, Any]]:
|
|
"""사용자 ID로 채팅 이력 조회"""
|
|
try:
|
|
simple_db = ChatRepository._get_db()
|
|
result = await simple_db.execute_query(
|
|
ChatQueries.GET_CHAT_HISTORY_BY_USER,
|
|
{"user_id": user_id}
|
|
)
|
|
|
|
logger.info(f"채팅 이력 조회 성공 - user_id: {user_id}, count: {len(result)}")
|
|
return result if result else []
|
|
|
|
except Exception as e:
|
|
logger.error(f"채팅 이력 조회 실패 - user_id: {user_id}, error: {str(e)}")
|
|
raise Exception(f"채팅 이력 조회 실패: {str(e)}") |