import sqlite3 import os import logging import json # 设置日志 logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # 数据库路径 DB_DIR = "data" DB_PATH = os.path.join(DB_DIR, "app.db") def check_and_alter_table(): # 检查数据库文件是否存在 if not os.path.exists(DB_PATH): logger.error(f"数据库文件 {DB_PATH} 不存在") return conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() # 检查talents表是否存在idcode字段 cursor.execute("PRAGMA table_info(talents)") columns = [column[1] for column in cursor.fetchall()] if 'idcode' not in columns: logger.info("talents表中添加idcode字段") cursor.execute("ALTER TABLE talents ADD COLUMN idcode TEXT") conn.commit() else: logger.info("talents表已包含idcode字段,无需修改") # 检查talents表是否存在educationBackground字段 if 'educationBackground' not in columns: logger.info("talents表中添加educationBackground字段") cursor.execute("ALTER TABLE talents ADD COLUMN educationBackground TEXT") conn.commit() else: logger.info("talents表已包含educationBackground字段,无需修改") # 检查labs表是否存在idcode字段 cursor.execute("PRAGMA table_info(labs)") labs_columns = [column[1] for column in cursor.fetchall()] if 'idcode' not in labs_columns: logger.info("labs表中添加idcode字段") cursor.execute("ALTER TABLE labs ADD COLUMN idcode TEXT") conn.commit() else: logger.info("labs表已包含idcode字段,无需修改") # 检查dimensions表是否存在sub_dimensions字段 cursor.execute("PRAGMA table_info(dimensions)") columns = [column[1] for column in cursor.fetchall()] if 'sub_dimensions' not in columns: logger.info("dimensions表中添加sub_dimensions字段") cursor.execute("ALTER TABLE dimensions ADD COLUMN sub_dimensions JSON") conn.commit() else: logger.info("dimensions表已包含sub_dimensions字段,无需修改") # 检查dimensions表是否存在parent_id字段 if 'parent_id' not in columns: logger.info("dimensions表中添加parent_id字段") cursor.execute("ALTER TABLE dimensions ADD COLUMN parent_id INTEGER REFERENCES dimensions(id)") conn.commit() else: logger.info("dimensions表已包含parent_id字段,无需修改") # 检查labs表是否存在sub_dimension_evaluations字段 if 'sub_dimension_evaluations' not in labs_columns: logger.info("labs表中添加sub_dimension_evaluations字段") cursor.execute("ALTER TABLE labs ADD COLUMN sub_dimension_evaluations TEXT") conn.commit() else: logger.info("labs表已包含sub_dimension_evaluations字段,无需修改") conn.close() if __name__ == "__main__": check_and_alter_table()