#!/usr/bin/env python3 """ 数据库迁移脚本 - 添加PDF拆题相关字段 """ import sqlite3 import os def migrate_database(): """迁移数据库,添加新字段""" db_path = "wordmaster.db" if not os.path.exists(db_path): print("❌ 数据库文件不存在") return False try: conn = sqlite3.connect(db_path) cursor = conn.cursor() print("🔄 开始数据库迁移...") # 检查是否已经存在新字段 cursor.execute("PRAGMA table_info(questions)") columns = [column[1] for column in cursor.fetchall()] new_fields = [ ('page_spans', 'JSON'), ('source_text', 'TEXT'), ('images', 'JSON'), ('formula', 'JSON'), ('score', 'REAL'), ('question_number', 'VARCHAR'), ('auto_extracted', 'BOOLEAN DEFAULT FALSE') ] # 添加缺失的字段 for field_name, field_type in new_fields: if field_name not in columns: sql = f"ALTER TABLE questions ADD COLUMN {field_name} {field_type}" print(f" 添加字段: {field_name}") cursor.execute(sql) else: print(f" 字段已存在: {field_name}") conn.commit() print("✅ 数据库迁移完成") # 验证新结构 cursor.execute("PRAGMA table_info(questions)") new_columns = [column[1] for column in cursor.fetchall()] print(f"📊 当前字段数量: {len(new_columns)}") return True except Exception as e: print(f"❌ 迁移失败: {e}") return False finally: if 'conn' in locals(): conn.close() if __name__ == "__main__": success = migrate_database() if success: print("\n🎉 数据库迁移成功完成!") else: print("\n💔 数据库迁移失败!")