apply_user_consumption_migration.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. """
  2. 应用 user_consumption 表的迁移脚本
  3. 运行方式:
  4. python scripts/apply_user_consumption_migration.py
  5. """
  6. import sys
  7. from pathlib import Path
  8. from sqlalchemy import text
  9. # 确保可以导入 app 包(将项目根目录加入 sys.path)
  10. project_root = Path(__file__).parent.parent
  11. sys.path.insert(0, str(project_root))
  12. from app.database import engine
  13. def main():
  14. sql_file = project_root / "migrations" / "030_create_user_consumption.sql"
  15. if not sql_file.exists():
  16. print(f"❌ 迁移文件不存在: {sql_file}")
  17. sys.exit(1)
  18. sql_content = sql_file.read_text(encoding="utf-8")
  19. try:
  20. with engine.connect() as conn:
  21. # 直接一次性执行整个 SQL 文件,避免将包含 DO$$/函数块 的语句错误拆分
  22. conn.execute(text(sql_content))
  23. conn.commit()
  24. print("✅ 已成功创建/更新表: aigcspace.user_consumption")
  25. except Exception as e:
  26. print("❌ 执行迁移失败")
  27. print(f"错误信息: {e}")
  28. sys.exit(1)
  29. if __name__ == "__main__":
  30. main()