【问题标题】:Alembic & Postgres: how to switch to another schemaAlembic & Postgres:如何切换到另一个模式
【发布时间】:2022-07-23 20:31:45
【问题描述】:

我有一个带有默认 public 架构的 postgres 数据库,它托管一些表,包括 alembic 迁移表。

我想要一个带有 app 架构的 postgres 数据库,所有表(包括 alembic 迁移)都移到那里。

如何将 Alembic 迁移与 sqlalchemy 以及任何设置更改一起使用?

我在相关问题中找到了一些信息:SQLAlchemy + alembic: create schema migrationHow to specific table schema for alembic_version when using flask-migrateCreate an alembic migration to create schema for version_table_schema,但我正在努力将它们放在一个(或两个)整洁的迁移 + 代码更改中。

我认为这里有一个食谱会很好,我打算在一天左右自己发布它,如果没有人能把我从这个麻烦中拯救出来:)

【问题讨论】:

    标签: postgresql alembic


    【解决方案1】:

    好吧,就这样吧。棘手的部分是迁移alembic_version 表,因为它在迁移之前读取并在迁移之后写入。还有几个地方需要配置。

    第一次提交

    第一次提交是为了准备。无论Base定义在哪里,都改成

    base.py

    from sqlalchemy import MetaData
    from sqlalchemy.orm import declarative_base
    
    Base = declarative_base(metadata=MetaData(schema='public'))
    

    然后修改alembic env(感谢h4!)以匹配这个:

    env.py

    [...]
    
    context.configure(
        connection=connection,
        target_metadata=target_metadata,
        version_table_schema=target_metadata.schema,
        include_schemas=True,
    )
    
    with context.begin_transaction():
        context.execute(f'create schema if not exists {target_metadata.schema};')
        context.execute(f'set search_path to {target_metadata.schema}')
        context.run_migrations()
    
    [...]
    
    

    第二次提交

    创建一个新的 Alembic 迁移

    2d8cec1e2a62_rename_schema.py

    from alembic import op
    import sqlalchemy as sa
    
    [...]
    
    def upgrade():
        if 'app' not in sa.inspect(op.get_bind()).get_schema_names():
            op.execute('alter schema public rename to app')
            op.execute('create schema public')
            op.execute('create table public.alembic_version AS (select * from app.alembic_version)')
    
    
    def downgrade():
        pass
    

    提交并运行迁移!

    第三次提交

    base.py 中的架构更改为'app'

    base.py

    from sqlalchemy import MetaData
    from sqlalchemy.orm import declarative_base
    
    Base = declarative_base(metadata=MetaData(schema='app'))
    

    提交并运行迁移。

    【讨论】:

      猜你喜欢
      • 2014-02-02
      • 2015-07-13
      • 1970-01-01
      • 2017-05-03
      • 2011-04-13
      • 2018-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多