chongming/scripts/migrate.py
2026-01-26 09:50:55 +08:00

61 lines
1.6 KiB
Python
Raw Permalink 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.

#!/usr/bin/env python3
"""
数据库迁移脚本
"""
import asyncio
import sys
import os
# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
async def main():
from app.core.config import get_settings
from aerich import Command
settings = get_settings()
# Aerich 配置
TORTOISE_ORM = {
"connections": {
"default": settings.database_url
},
"apps": {
"models": {
"models": ["app.models", "aerich.models"],
"default_connection": "default",
}
},
"use_tz": False,
"timezone": "UTC",
}
command = Command(tortoise_config=TORTOISE_ORM, app="models")
# 初始化 Aerich首次运行
if not os.path.exists("./migrations"):
print("🔧 初始化数据库迁移...")
await command.init()
print("✅ 迁移初始化完成")
# 生成迁移文件
print("📝 生成迁移文件...")
try:
migration_name = sys.argv[1] if len(sys.argv) > 1 else "update"
await command.migrate(name=migration_name)
print(f"✅ 迁移文件生成成功: {migration_name}")
except Exception as e:
print(f"⚠️ 生成迁移文件失败: {e}")
# 尝试升级
pass
# 应用迁移
print("🔄 应用数据库迁移...")
try:
await command.upgrade()
print("✅ 迁移应用成功")
except Exception as e:
print(f"❌ 迁移应用失败: {e}")
if __name__ == "__main__":
asyncio.run(main())