init_db.py 3.83 KB
import yaml
from sqlalchemy import create_engine, text
import os

def init_database(db_key="device_detail_db"):
    # 获取当前脚本所在目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    project_root = os.path.dirname(current_dir)
    
    # 1. 读取 config.yaml (在项目根目录)
    config_path = os.path.join(project_root, "config.yaml")
    if not os.path.exists(config_path):
        print(f"错误: 找不到配置文件 {config_path}")
        return

    with open(config_path, "r", encoding="utf-8") as f:
        config = yaml.safe_load(f)

    # 获取数据库配置
    db_config = config.get("database", {}).get(db_key)
    if not db_config:
        print(f"错误: config.yaml 中缺少 {db_key} 配置")
        return

    # 2. 构建连接字符串
    connection_str = (
        f"mysql+pymysql://{db_config['user']}:{db_config['password']}@"
        f"{db_config['host']}:{db_config['port']}/{db_config['db_name']}?"
        f"charset={db_config['charset']}"
    )

    try:
        # 3. 创建引擎并连接
        engine = create_engine(connection_str)
        
        # 4. 读取 schema.sql (在当前目录)
        schema_path = os.path.join(current_dir, "schema.sql")
        if not os.path.exists(schema_path):
            print(f"错误: 找不到架构文件 {schema_path}")
            return

        with open(schema_path, "r", encoding="utf-8") as f:
            # 按分号分割 SQL 语句
            sql_commands = f.read().split(';')

        # 5. 执行 SQL 语句
        with engine.begin() as connection:
            print(f"正在连接到数据库 [{db_key}]: {db_config['host']}:{db_config['port']}/{db_config['db_name']}...")
            
            # 定义高危指令拦截列表
            dangerous_keywords = ['DROP ', 'TRUNCATE ', 'DELETE FROM ']
            
            for command in sql_commands:
                # 1. 预处理:按行分割并过滤掉纯注释行 (-- 或 # 开头的行)
                lines = command.split('\n')
                non_comment_lines = []
                for line in lines:
                    stripped_line = line.strip()
                    # 排除空行、以 -- 开头的注释行、以 # 开头的注释行
                    if stripped_line and not (stripped_line.startswith('--') or stripped_line.startswith('#')):
                        non_comment_lines.append(line)
                
                # 2. 重新组合并清理两端空白
                clean_command = "\n".join(non_comment_lines).strip()
                
                # 3. 如果清理后为空,则跳过
                if not clean_command:
                    continue
                
                # 安全检查:拦截可能导致数据丢失的指令
                is_dangerous = any(keyword in clean_command.upper() for keyword in dangerous_keywords)
                if is_dangerous:
                    print(f"警告: 拦截到潜在的危险指令,已跳过执行: \n{clean_command[:100]}...")
                    continue

                # 记录正在执行的指令
                if "CREATE TABLE" in clean_command.upper():
                    table_name = clean_command.split('`')[1] if '`' in clean_command else "未知表"
                    print(f"检查/创建表: {table_name}")
                elif "ALTER TABLE" in clean_command.upper():
                    table_name = clean_command.split('`')[1] if '`' in clean_command else "未知表"
                    print(f"更新表结构: {table_name}")

                # 使用 exec_driver_sql 直接执行原始 SQL,避免 SQLAlchemy 对冒号(:)等字符的参数解析
                connection.exec_driver_sql(clean_command)
            
            print("数据库表检查/更新任务完成!")

    except Exception as e:
        print(f"连接数据库失败: {e}")

if __name__ == "__main__":
    init_database()