enhance database initialization handling with fallback stub and improved logging

This commit is contained in:
Your Name 2025-10-07 22:06:03 +08:00
parent d972b3fb8a
commit f355d1ca09
2 changed files with 23 additions and 6 deletions

View File

@ -24,12 +24,22 @@ def render_tests() -> None:
LOGGER.info("点击测试数据库初始化按钮", extra=LOG_EXTRA)
with st.spinner("正在检查数据库..."):
result = initialize_database()
if result.skipped:
# Defensive: some environments may provide a stub or return None.
if result is None:
LOGGER.warning("initialize_database 返回 None可能为 stub无法读取执行详情", extra=LOG_EXTRA)
st.warning("数据库初始化返回空结果,已跳过详细检查。")
else:
skipped = getattr(result, "skipped", False)
executed = getattr(result, "executed", None)
if skipped:
LOGGER.info("数据库已存在,无需初始化", extra=LOG_EXTRA)
st.success("数据库已存在,检查通过。")
else:
LOGGER.info("数据库初始化完成,执行语句数=%s", result.executed, extra=LOG_EXTRA)
st.success(f"数据库初始化完成,共执行 {result.executed} 条语句。")
LOGGER.info("数据库初始化完成,执行语句数=%s", executed, extra=LOG_EXTRA)
if executed is None:
st.success("数据库初始化完成。")
else:
st.success(f"数据库初始化完成,共执行 {executed} 条语句。")
st.divider()

View File

@ -11,6 +11,7 @@ from datetime import date, datetime, timedelta
from typing import Any, Callable, ClassVar, Dict, Iterable, List, Optional, Sequence, Set, Tuple
from .config import get_config
import types
from .db import db_session
from .logging import get_logger
from app.core.indicators import momentum, normalize, rolling_mean, volatility
@ -35,7 +36,13 @@ if initialize_database is None:
except ImportError:
# 导入失败时,提供一个空实现
def initialize_database():
pass
"""Fallback stub used when the real initializer cannot be imported.
Return a lightweight object with the attributes callers expect
(executed, skipped, missing_tables) so code that calls
`initialize_database()` can safely inspect the result.
"""
return types.SimpleNamespace(executed=0, skipped=True, missing_tables=[])
LOGGER = get_logger(__name__)
LOG_EXTRA = {"stage": "data_broker"}