|
|
|
@ -25,6 +25,7 @@ from app.log import logger |
|
|
|
|
from app.models.admin import Api, Menu, Role |
|
|
|
|
from app.schemas.menus import MenuType |
|
|
|
|
from app.settings.config import settings |
|
|
|
|
from tortoise.transactions import in_transaction |
|
|
|
|
|
|
|
|
|
from .middlewares import BackGroundTaskMiddleware, HttpAuditLogMiddleware |
|
|
|
|
|
|
|
|
@ -187,20 +188,34 @@ async def init_apis(): |
|
|
|
|
|
|
|
|
|
async def init_db(): |
|
|
|
|
command = Command(tortoise_config=settings.TORTOISE_ORM) |
|
|
|
|
|
|
|
|
|
try: |
|
|
|
|
await command.init_db(safe=True) |
|
|
|
|
except FileExistsError: |
|
|
|
|
pass |
|
|
|
|
|
|
|
|
|
await command.init() |
|
|
|
|
try: |
|
|
|
|
await command.migrate() |
|
|
|
|
except AttributeError: |
|
|
|
|
logger.warning("unable to retrieve model history from database, model history will be created from scratch") |
|
|
|
|
shutil.rmtree("migrations") |
|
|
|
|
await command.init_db(safe=True) |
|
|
|
|
|
|
|
|
|
await command.upgrade(run_in_transaction=True) |
|
|
|
|
# ✅ 检查是否已经有迁移记录(只迁移一次) |
|
|
|
|
async with in_transaction() as conn: |
|
|
|
|
try: |
|
|
|
|
result = await conn.execute_query("SELECT COUNT(*) FROM aerich") |
|
|
|
|
count = result[1][0][0] # [ (123,) ] -> count = 123 |
|
|
|
|
except Exception as e: |
|
|
|
|
count = 0 # 表不存在,视为未迁移 |
|
|
|
|
|
|
|
|
|
if count == 0: |
|
|
|
|
logger.info("📦 First-time migration, running migrate + upgrade...") |
|
|
|
|
try: |
|
|
|
|
await command.migrate() |
|
|
|
|
except AttributeError: |
|
|
|
|
logger.warning("unable to retrieve model history from database, model history will be created from scratch") |
|
|
|
|
shutil.rmtree("migrations") |
|
|
|
|
await command.init_db(safe=True) |
|
|
|
|
|
|
|
|
|
await command.upgrade(run_in_transaction=True) |
|
|
|
|
else: |
|
|
|
|
logger.info("✅ Migration already applied, skipping migrate + upgrade.") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def init_roles(): |
|
|
|
|