""" Alembic 迁移环境配置 支持异步数据库连接 """ from logging.config import fileConfig from alembic import context from sqlalchemy import engine_from_config, pool # 导入所有 ORM 模型以确保 Base.metadata 包含完整的表定义 from app.models.base import Base # Alembic Config 对象 config = context.config # 设置日志 if config.config_file_name is not None: fileConfig(config.config_file_name) # 元数据目标,用于自动生成迁移 target_metadata = Base.metadata def run_migrations_offline() -> None: """ 以 'offline' 模式运行迁移。 只需要 URL,不需要 Engine。调用 context.execute() 将迁移 直接发送到数据库。 """ url = config.get_main_option("sqlalchemy.url") context.configure( url=url, target_metadata=target_metadata, literal_binds=True, dialect_opts={"paramstyle": "named"}, ) with context.begin_transaction(): context.run_migrations() def run_migrations_online() -> None: """ 以 'online' 模式运行迁移。 创建 Engine 并关联 connection 到 context。 """ 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, ) with context.begin_transaction(): context.run_migrations() if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online()