【问题标题】:Alembic --autogenerate tries to recreate every tableAlembic --autogenerate 尝试重新创建每个表
【发布时间】:2014-06-26 13:50:31
【问题描述】:

我第一次尝试针对预先存在的数据库自动生成 alembic 修订,但是当我运行以下命令时

alembic revision --autogenerate

它会生成一个迁移,尝试在我的数据库中创建每个表和索引。类似这样:

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('table1',
    sa.Column('id', sa.SmallInteger(), nullable=False),
    sa.Column('name', sa.String(length=100), nullable=True),
    sa.Column('desc', sa.Text(), nullable=True),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('name'),
    schema='schema1'
    )
    op.create_index(op.f('ix_index1'), 'table1', ['name'], unique=False, schema='schema1')
    ... all my other tables/indexes ..


def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_index(op.f('ix_index1'), table_name='table1', schema='schema1')
    op.drop_table('table1', schema='schema1')
    ... all my other tables/indexes ..

然后,如果我尝试运行迁移它会失败,因为对象已经存在:

sqlalchemy.exc.ProgrammingError: (ProgrammingError) relation "table1" already exists

所以在我看来,alembic 认为我的数据库不包含任何表,但它确实包含。

任何想法为什么会发生这种情况?

【问题讨论】:

标签: python alembic


【解决方案1】:

配置 alembic 以查看您的数据库

您是否将 target_metadata 设置为您的基本元数据?

来自documentation

要使用自动生成,我们首先需要修改我们的 env.py 以便它 访问包含目标的表元数据对象。 假设我们的应用程序在 myapp.mymodel 中有一个声明性基础。这 base 包含一个 MetaData 对象,该对象包含定义的 Table 对象 我们的数据库。我们确保将其加载到 env.py 中,然后传递给 EnvironmentContext.configure() 通过 target_metadata 参数。这 通用模板中使用的 env.py 示例脚本已经有一个 为了方便起见,在顶部附近的变量声明,我们在这里 用我们的元数据替换 None。开始于:

# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata 
target_metadata = None

我们改为:

from myapp.mymodel import Base
target_metadata = Base.metadata

【讨论】:

    猜你喜欢
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2015-12-10
    • 2021-09-15
    相关资源
    最近更新 更多