gpt4 book ai didi

python - Alembic --autogenerate 尝试重新创建每个表

转载 作者:太空狗 更新时间:2023-10-29 19:28:38 31 4
gpt4 key购买 nike

我第一次尝试针对预先存在的数据库自动生成 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 认为我的数据库不包含任何表,但它确实包含。

知道为什么会发生这种情况吗?

最佳答案

配置 alembic 以查看您的数据库

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

来自documentation .

To use autogenerate, we first need to modify our env.py so that it gets access to a table metadata object that contains the target. Suppose our application has a declarative base in myapp.mymodel. This base contains a MetaData object which contains Table objects defining our database. We make sure this is loaded in env.py and then passed to EnvironmentContext.configure() via the target_metadata argument. The env.py sample script used in the generic template already has a variable declaration near the top for our convenience, where we replace None with our MetaData. Starting with:

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

we change to:

from myapp.mymodel import Base
target_metadata = Base.metadata

关于python - Alembic --autogenerate 尝试重新创建每个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24432373/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com