从issue 409 开始,使用translated schema names 可以最轻松地完成对租户特定模式的升级/降级操作的应用程序,这也是您通常对多租户执行主应用程序的方式。
进入 env.py:
def run_migrations_online():
connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix='sqlalchemy.',
poolclass=pool.NullPool)
with connectable.connect() as connection:
for tenant_schema_name in all_my_tenant_names:
conn = connection.execution_options(schema_translate_map={None: tenant_schema_name}
logger.info("Migrating tenant schema %s" % tenant_schema_name)
context.configure(
connection=conn,
target_metadata=target_metadata
)
# to do each tenant in its own transaction.
# move this up to do all tenants in one giant transaction
with context.begin_transaction():
context.run_migrations()
Above 会将“None”架构名称转换为给定的租户名称。如果应用程序与具有全局表的默认模式共享基于租户的模式,那么您将使用像“tenant_schema”这样的标记作为符号:
for tenant_schema_name in all_my_tenant_names:
conn = connection.execution_options(schema_translate_map={"tenant_schema": tenant_schema_name}
并在迁移文件中引用“tenant_schema”,其中实际的租户特定架构名称所在的位置:
def upgrade():
op.alter_column("some_table", "some_column", <migration options>, schema="tenant_schema")
对于“自动生成”的情况,@nick-retallack 提供的解决方案有更多您将在此使用的部分,即使用 include_schemas 以便自动生成仅查看代表最新的“样本”模式租户特定架构的版本。
为了设置 env.py 为正确的命令使用正确的系统,可以使用migration_context.get_x_argument() 的用户定义选项来控制行为。