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

标签 python alembic

我第一次尝试针对预先存在的数据库自动生成 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/

相关文章:

python - NDB 使用 Users API 形成实体组

python - 用于添加索引的 SQLAlchemy/Alembic 原始 SQL

python - 如何在 sqlalchemy for mysql 中的另一列之后添加一列?

python - 使用 SqlAlchemy 和 Alembic 创建部分索引

python - SQLAlchemy、Alembic 和新实例

postgresql - Alembic 未生成正确的更改

python - 计算排列中的排列数

python - 在 Mac OS Big Sur 上使用 pyenv 安装 python 3.6 时出现问题

python - python 2.4的JSON模块?

java - 为什么我需要在Java程序中创建一个类?