74 lines
2.4 KiB
Python
74 lines
2.4 KiB
Python
"""Alembic 迁移环境配置
|
||
|
||
- 从 shared.config.settings 读取 DB 配置,构造同步 URL(psycopg2)供 alembic 使用
|
||
(项目运行时用 asyncpg,但 alembic 是同步库,需 psycopg2)
|
||
- target_metadata 指向 shared.models.database.Base.metadata
|
||
- 支持 ALEMBIC_URL 环境变量覆盖(用于离线/空库生成初始迁移,如 sqlite:///empty.db)
|
||
"""
|
||
from logging.config import fileConfig
|
||
from pathlib import Path
|
||
import os
|
||
import sys
|
||
|
||
from sqlalchemy import engine_from_config, pool
|
||
from alembic import context
|
||
|
||
# 让 alembic 能 import 项目模块(src 在项目根下)
|
||
project_root = Path(__file__).parent.parent
|
||
sys.path.insert(0, str(project_root / "src"))
|
||
|
||
from shared.config.settings import settings # noqa: E402
|
||
from shared.models.database import Base # noqa: E402
|
||
import shared.models.database # noqa: E402,F401 # 导入所有模型,确保 metadata 注册
|
||
|
||
config = context.config
|
||
|
||
if config.config_file_name is not None:
|
||
fileConfig(config.config_file_name)
|
||
|
||
# 构造同步 URL:asyncpg -> psycopg2
|
||
_sync_url = settings.DATABASE_URL.replace("postgresql+asyncpg://", "postgresql+psycopg2://")
|
||
# 支持 ALEMBIC_URL 覆盖(离线生成/测试用)
|
||
config.set_main_option("sqlalchemy.url", os.getenv("ALEMBIC_URL", _sync_url))
|
||
|
||
target_metadata = Base.metadata
|
||
|
||
|
||
def run_migrations_offline() -> None:
|
||
"""离线模式:生成 SQL 脚本,不连接 DB"""
|
||
url = config.get_main_option("sqlalchemy.url")
|
||
context.configure(
|
||
url=url,
|
||
target_metadata=target_metadata,
|
||
literal_binds=True,
|
||
dialect_opts={"paramstyle": "named"},
|
||
compare_type=True,
|
||
compare_server_default=True,
|
||
)
|
||
with context.begin_transaction():
|
||
context.run_migrations()
|
||
|
||
|
||
def run_migrations_online() -> None:
|
||
"""在线模式:连接 DB 执行迁移"""
|
||
connectable = engine_from_config(
|
||
config.get_section(config.config_ini_section, {}),
|
||
prefix="sqlalchemy.",
|
||
poolclass=pool.NullPool,
|
||
)
|
||
with connectable.connect() as connection:
|
||
context.configure(
|
||
connection=connection,
|
||
target_metadata=target_metadata,
|
||
compare_type=True,
|
||
compare_server_default=True,
|
||
)
|
||
with context.begin_transaction():
|
||
context.run_migrations()
|
||
|
||
|
||
if context.is_offline_mode():
|
||
run_migrations_offline()
|
||
else:
|
||
run_migrations_online()
|