54 lines
1.6 KiB
Python
54 lines
1.6 KiB
Python
"""Alembic 迁移环境。URL 从 server/config/settings.py 读取,支持 autogenerate。"""
|
|
from __future__ import annotations
|
|
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
from alembic import context
|
|
from sqlalchemy import create_engine, pool
|
|
|
|
# 让 `from config import ...` / `from db import ...` / `import models` 可解析
|
|
SERVER_DIR = Path(__file__).resolve().parents[1]
|
|
if str(SERVER_DIR) not in sys.path:
|
|
sys.path.insert(0, str(SERVER_DIR))
|
|
|
|
from config import get_settings # noqa: E402
|
|
from db import Base # noqa: E402
|
|
import models # noqa: E402,F401 确保所有模型注册到 Base.metadata
|
|
|
|
config = context.config
|
|
target_metadata = Base.metadata
|
|
|
|
|
|
def _sync_url(url: str) -> str:
|
|
"""异步 URL → 同步 URL(迁移用同步引擎跑更稳)。"""
|
|
return url.replace("+aiosqlite", "").replace("+asyncpg", "")
|
|
|
|
|
|
def run_migrations_offline() -> None:
|
|
context.configure(
|
|
url=_sync_url(get_settings().database_url),
|
|
target_metadata=target_metadata,
|
|
literal_binds=True,
|
|
dialect_opts={"paramstyle": "named"},
|
|
)
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
def run_migrations_online() -> None:
|
|
connectable = create_engine(
|
|
_sync_url(get_settings().database_url),
|
|
poolclass=pool.NullPool,
|
|
)
|
|
with connectable.connect() as connection:
|
|
context.configure(connection=connection, target_metadata=target_metadata)
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
if context.is_offline_mode():
|
|
run_migrations_offline()
|
|
else:
|
|
run_migrations_online()
|