Alembic:为每个模式放置一个 "version_num"

Alembic: put a "version_num" for each schema

在我的团队中,我们有多个 projects/microservices 都托管在同一个数据库中,但每个服务都有特定的架构。

我想独立于其他项目管理每个项目的迁移,一种实现方法是为 Alembic 指定不同的环境,一个环境特定于一个模式。

假设我有两个服务:“service1”和“service2”,每个服务都有一个具有项目名称的架构。 我希望我的代码具有以下结构:

team
├───service1
│   ├───requirements.txt
│   ├───main.py
│   └───alembic/
└───service2
    ├───requirements.txt
    ├───main.py
    └───alembic/

我希望能够

  1. 导航到 team/service1
  2. 创建迁移并运行
    • 在架构“service1”上执行此迁移
  3. 转到team/service2
  4. 创建迁移并运行
    • 在架构“service2”上执行此迁移

这可能吗?我怎样才能做到这一点?

我在env.py中使用了configure方法的version_table_schema参数:

def run_migrations_online():
    """Run migrations in 'online' mode.

    In this scenario we need to create an Engine
    and associate a connection with the 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,
            version_table_schema="MY_SCHEMA",
        )

        with context.begin_transaction():
            context.run_migrations()

(感谢CaselIT