Files
Mutual_Fund/nl2sql/history.py

63 lines
1.8 KiB
Python

"""NL2SQL 查询历史归档适配器。"""
from __future__ import annotations
from collections.abc import Iterable
import logging
from model.nl2sql_permission import Nl2SqlQueryHistory
_STATUSES = {"success", "failed", "blocked", "timeout"}
logger = logging.getLogger("nl2sql.history")
async def archive_query(
db,
*,
query_id: str,
user_id: int,
question: str,
generated_sql: str | None = None,
access_tables: Iterable[str] = (),
status: str,
error_code: str | None = None,
error_message: str | None = None,
row_count: int = 0,
truncated: bool = False,
elapsed_ms: float | None = None,
trace_id: str | None = None,
session_id: str | None = None,
caller_agent: str | None = None,
) -> None:
"""归档查询元数据,明确不写入结果行。"""
if status not in _STATUSES:
raise ValueError("无效的查询历史状态")
history = Nl2SqlQueryHistory(
query_id=query_id,
user_id=user_id,
session_id=session_id,
caller_agent=caller_agent,
question=question,
generated_sql=generated_sql,
access_tables=sorted(set(access_tables)),
status=status,
error_code=error_code,
error_message=error_message,
row_count=row_count,
truncated=truncated,
elapsed_ms=elapsed_ms,
trace_id=trace_id,
)
db.add(history)
await db.commit()
async def archive_query_safely(db, **kwargs) -> bool:
"""尝试归档查询,归档存储异常时记录日志并返回 False。"""
try:
await archive_query(db, **kwargs)
except Exception: # noqa: BLE001 归档失败不能阻断查询主流程
logger.warning("NL2SQL 查询历史归档失败", exc_info=True)
return False
return True