ai_v/db_manager.py

68 lines
2.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import sys
import os
from app import create_app, db
from flask_migrate import upgrade, migrate, init, stamp
def init_migrations():
"""初始化迁移环境 (如果 migrations 文件夹不存在)"""
if not os.path.exists('migrations'):
print("📂 初始化 migrations 文件夹...")
with app.app_context():
init()
else:
print("✅ migrations 文件夹已存在,跳过初始化。")
def make_migrations(message="Auto update"):
"""生成迁移脚本 (检测 models.py 的变动)"""
print(f"📝 正在生成迁移脚本 (备注: {message})...")
with app.app_context():
try:
migrate(message=message)
print("✅ 迁移脚本生成成功!")
except Exception as e:
print(f"⚠️ 生成失败 (可能是没有变动): {e}")
def apply_migrations():
"""应用迁移到数据库 (执行 SQL)"""
print("🚀 正在将变动应用到数据库...")
with app.app_context():
upgrade()
print("✅ 数据库结构已同步至最新版!")
def force_sync():
"""强制同步 (不仅是 Upgrade还包括 create_all)"""
print("🔧 正在进行全量同步检查...")
with app.app_context():
db.create_all()
# 标记当前状态为最新
stamp()
print("✅ 数据库表结构已确保存在。")
if __name__ == '__main__':
app = create_app()
if len(sys.argv) < 2:
print("\n🔧 数据库管理脚本使用说明:")
print(" python db_manager.py init -> 初始化迁移环境")
print(" python db_manager.py make -> 生成迁移文件 (检测 models.py 变动)")
print(" python db_manager.py up -> 执行更新 (修改数据库表结构)")
print(" python db_manager.py sync -> 一键同步模式 (生成 + 执行)")
sys.exit(0)
cmd = sys.argv[1]
if cmd == 'init':
init_migrations()
elif cmd == 'make':
msg = sys.argv[2] if len(sys.argv) > 2 else "schema_update"
make_migrations(msg)
elif cmd == 'up':
apply_migrations()
elif cmd == 'sync':
# 一键傻瓜模式
init_migrations()
make_migrations("auto_sync")
apply_migrations()
else:
print("❌ 未知命令")