min*_*iao 6 python database-migration alembic
我有一个创建表的alembic升级脚本,但是如果它已经存在,我不希望它创建表.
根据alembic doc,我可以将关键字args传递op.create_tables给sqlalchemy.schema.table可接受的,所以我使用的是keep_existing关键字:
op.create_table('foo_model',
sa.Column('foo_id', sa.Integer(), nullable=False),
sa.Column('foo_str', sa.String(length=255), nullable=True),
sa.PrimaryKeyConstraint('foo_id'),
keep_existing= True
)
Run Code Online (Sandbox Code Playgroud)
但是我仍然得到表已经存在的错误.
sqlalchemy.exc.InternalError: (InternalError) (1050, u"Table 'foo_model' already exists") '\nCREATE TABLE foo_model (\n\tfoo_id INTEGER NOT NULL AUTO_INCREMENT, \n\tfoo_str VARCHAR(255), \n\tPRIMARY KEY (foo_id)\n)\n\n' ()
Run Code Online (Sandbox Code Playgroud)
小智 19
您可以像这样获取现有表的列表:
from sqlalchemy.engine.reflection import Inspector
conn = op.get_bind()
inspector = Inspector.from_engine(conn)
tables = inspector.get_table_names()
Run Code Online (Sandbox Code Playgroud)
然后检查表是否已经存在
if table_name not in tables:
op.create_table()
Run Code Online (Sandbox Code Playgroud)
osh*_*ryu -11
这可能是因为该表已经存在。psql只需使用并运行即可从数据库中删除表drop table foo_model;