rasa人机对话脚本生成

init_db.py 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import logging
  2. import os
  3. import sys
  4. from sqlalchemy import create_engine
  5. from sqlalchemy.exc import SQLAlchemyError
  6. # 添加项目根目录到Python路径
  7. sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  8. from config import config
  9. from db import Base
  10. # 初始化日志
  11. logging.basicConfig(level=logging.INFO)
  12. logger = logging.getLogger(__name__)
  13. def init_database():
  14. """初始化数据库:创建表结构并执行初始SQL脚本"""
  15. try:
  16. # 获取数据库连接字符串
  17. connection_string = config.get("database.connection_string")
  18. if not connection_string:
  19. raise ValueError("数据库连接字符串未配置")
  20. # 创建数据库引擎
  21. engine = create_engine(connection_string)
  22. # 创建所有表
  23. logger.info("开始创建数据库表结构...")
  24. Base.metadata.create_all(engine)
  25. logger.info("数据库表结构创建成功")
  26. # 执行SQL初始化脚本
  27. sql_script_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "sql", "schema.sql")
  28. if os.path.exists(sql_script_path):
  29. logger.info(f"开始执行初始化SQL脚本: {sql_script_path}")
  30. with engine.connect() as connection:
  31. with open(sql_script_path, 'r', encoding='utf-8') as f:
  32. # 读取并执行SQL脚本
  33. sql = f.read()
  34. # 分割SQL语句(简单处理,适用于大多数情况)
  35. statements = sql.split(';')
  36. for stmt in statements:
  37. stmt = stmt.strip()
  38. if stmt and not stmt.startswith('--'):
  39. connection.execute(stmt)
  40. connection.commit()
  41. logger.info("SQL初始化脚本执行成功")
  42. else:
  43. logger.warning(f"未找到SQL初始化脚本: {sql_script_path}")
  44. logger.info("数据库初始化完成")
  45. except SQLAlchemyError as e:
  46. logger.error(f"数据库操作错误: {str(e)}")
  47. sys.exit(1)
  48. except Exception as e:
  49. logger.error(f"初始化数据库失败: {str(e)}")
  50. sys.exit(1)
  51. if __name__ == "__main__":
  52. init_database()