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,8 +526,18 @@ 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.
Returns a MigrationResult describing how many statements were executed
and whether the migration was skipped because the schema already exists.
"""
# 如果所有表已存在,则视为跳过
missing = _missing_tables()
if not missing:
return MigrationResult(executed=0, skipped=True, missing_tables=list(missing))
executed = 0
with db_session() as session: with db_session() as session:
cursor = session.cursor() cursor = session.cursor()
@ -535,6 +545,7 @@ def initialize_database() -> None:
for statement in SCHEMA_STATEMENTS: for statement in SCHEMA_STATEMENTS:
try: try:
cursor.execute(statement) cursor.execute(statement)
executed += 1
except Exception as e: # noqa: BLE001 except Exception as e: # noqa: BLE001
print(f"初始化数据库时出错: {e}") print(f"初始化数据库时出错: {e}")
raise raise
@ -550,8 +561,13 @@ def initialize_database() -> None:
WHERE id = NEW.id; WHERE id = NEW.id;
END; END;
""") """)
executed += 1
except Exception as e: # noqa: BLE001 except Exception as e: # noqa: BLE001
print(f"创建触发器时出错: {e}") print(f"创建触发器时出错: {e}")
raise raise
session.commit() session.commit()
# 返回执行摘要(创建后再次检查缺失表以报告)
remaining = _missing_tables()
return MigrationResult(executed=executed, skipped=False, missing_tables=remaining)