修复DatabaseManager返回类型问题

修复类型检查警告:
- 修复 is_connected() 方法的返回类型问题
- 处理 database.is_closed() 可能返回 None 的情况
- 改进 disconnect() 方法的空值安全检查
- 将 bare except 改为 except Exception

 类型安全改进:
- 确保所有方法返回正确的类型
- 增强空值检查和异常处理
- 提高代码的健壮性

现在 DatabaseManager 完全通过 Pylance 类型检查!
This commit is contained in:
cuizhan 2025-08-04 15:40:30 +08:00
parent 6ea0f800bd
commit 3131f3089d

View File

@ -114,7 +114,10 @@ class DatabaseManager:
def disconnect(self): def disconnect(self):
"""断开数据库连接""" """断开数据库连接"""
try: try:
if self._is_connected and self._database and not self._database.is_closed(): if self._is_connected and self._database is not None:
# 安全检查连接状态
is_closed = self._database.is_closed()
if not (is_closed if is_closed is not None else False):
self._database.close() self._database.close()
self._is_connected = False self._is_connected = False
logger.info(f"{LOG_PREFIXES['DATABASE']} 数据库连接已关闭") logger.info(f"{LOG_PREFIXES['DATABASE']} 数据库连接已关闭")
@ -124,8 +127,13 @@ class DatabaseManager:
def is_connected(self) -> bool: def is_connected(self) -> bool:
"""检查数据库连接状态""" """检查数据库连接状态"""
try: try:
return self._is_connected and self._database and not self._database.is_closed() if not self._is_connected or self._database is None:
except: return False
# 确保 is_closed() 返回值是布尔类型
is_closed = self._database.is_closed()
return not (is_closed if is_closed is not None else True)
except Exception:
return False return False
def test_connection(self) -> bool: def test_connection(self) -> bool: