refactor initialize_database to return MigrationResult and handle existing schema

This commit is contained in:
Your Name 2025-10-07 22:04:00 +08:00
parent 14034f7a0c
commit d972b3fb8a

View File

@ -526,32 +526,48 @@ def _missing_tables() -> List[str]:
return [name for name in REQUIRED_TABLES if name not in existing] return [name for name in REQUIRED_TABLES if name not in existing]
def initialize_database() -> None: def initialize_database() -> MigrationResult:
"""Initialize the SQLite database with all required tables.""" """Initialize the SQLite database with all required tables.
with db_session() as session:
cursor = session.cursor() Returns a MigrationResult describing how many statements were executed
and whether the migration was skipped because the schema already exists.
# 创建表 """
for statement in SCHEMA_STATEMENTS: # 如果所有表已存在,则视为跳过
try: missing = _missing_tables()
cursor.execute(statement) if not missing:
except Exception as e: # noqa: BLE001 return MigrationResult(executed=0, skipped=True, missing_tables=list(missing))
print(f"初始化数据库时出错: {e}")
raise executed = 0
with db_session() as session:
# 添加触发器以自动更新 updated_at 字段 cursor = session.cursor()
try:
cursor.execute(""" # 创建表
CREATE TRIGGER IF NOT EXISTS update_fetch_jobs_timestamp for statement in SCHEMA_STATEMENTS:
AFTER UPDATE ON fetch_jobs try:
BEGIN cursor.execute(statement)
UPDATE fetch_jobs executed += 1
SET updated_at = CURRENT_TIMESTAMP except Exception as e: # noqa: BLE001
WHERE id = NEW.id; print(f"初始化数据库时出错: {e}")
END; raise
""")
except Exception as e: # noqa: BLE001 # 添加触发器以自动更新 updated_at 字段
print(f"创建触发器时出错: {e}") try:
raise cursor.execute("""
CREATE TRIGGER IF NOT EXISTS update_fetch_jobs_timestamp
session.commit() AFTER UPDATE ON fetch_jobs
BEGIN
UPDATE fetch_jobs
SET updated_at = CURRENT_TIMESTAMP
WHERE id = NEW.id;
END;
""")
executed += 1
except Exception as e: # noqa: BLE001
print(f"创建触发器时出错: {e}")
raise
session.commit()
# 返回执行摘要(创建后再次检查缺失表以报告)
remaining = _missing_tables()
return MigrationResult(executed=executed, skipped=False, missing_tables=remaining)