From 0e0dedcdf786e6d5575ae789e96dc4e32c09fba0 Mon Sep 17 00:00:00 2001 From: minecraft1024a Date: Thu, 2 Oct 2025 17:08:30 +0800 Subject: [PATCH] =?UTF-8?q?fix(db):=20=E4=BF=AE=E5=A4=8D=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=BA=93=E4=BC=9A=E8=AF=9D=E8=8E=B7=E5=8F=96=E5=A4=B1=E8=B4=A5?= =?UTF-8?q?=E6=97=B6=E7=9A=84=E5=A4=84=E7=90=86=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 在 `db_query` 和 `db_save` 函数中,增加了对数据库会话(session)获取失败的检查。当无法获取会话时,记录错误日志并返回 None 或空列表,避免了后续操作因会话为空而引发的异常。 同时,修复了 `proactive_thinker_executor` 中因数据库查询返回 None 而导致处理 `action_history` 时出错的问题。 --- src/common/database/sqlalchemy_database_api.py | 9 ++++++++- .../proactive_thinker/proactive_thinker_executor.py | 4 +++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/common/database/sqlalchemy_database_api.py b/src/common/database/sqlalchemy_database_api.py index 7f740818c..210882dc8 100644 --- a/src/common/database/sqlalchemy_database_api.py +++ b/src/common/database/sqlalchemy_database_api.py @@ -124,6 +124,10 @@ async def db_query( raise ValueError("query_type must be 'get', 'create', 'update', 'delete' or 'count'") async with get_db_session() as session: + if not session: + logger.error("[SQLAlchemy] 无法获取数据库会话") + return None if single_result else [] + if query_type == "get": query = select(model_class) @@ -221,7 +225,7 @@ async def db_query( # 删除记录 affected_rows = 0 for record in records_to_delete: - session.delete(record) + await session.delete(record) affected_rows += 1 return affected_rows @@ -274,6 +278,9 @@ async def db_save( """ try: async with get_db_session() as session: + if not session: + logger.error("[SQLAlchemy] 无法获取数据库会话") + return None # 如果提供了key_field和key_value,尝试更新现有记录 if key_field and key_value is not None: if hasattr(model_class, key_field): diff --git a/src/plugins/built_in/proactive_thinker/proactive_thinker_executor.py b/src/plugins/built_in/proactive_thinker/proactive_thinker_executor.py index 4c61ce3e7..b5f280fee 100644 --- a/src/plugins/built_in/proactive_thinker/proactive_thinker_executor.py +++ b/src/plugins/built_in/proactive_thinker/proactive_thinker_executor.py @@ -128,7 +128,9 @@ class ProactiveThinkerExecutor: limit=3, order_by=["-time"] ) - action_history_context = "\n".join([f"- {a['action_data']}" for a in action_history]) if action_history else "无" + action_history_context = "无" + if isinstance(action_history, list): + action_history_context = "\n".join([f"- {a['action_data']}" for a in action_history if isinstance(a, dict)]) or "无" return { "person_id": person_id,