alembic create_table,检查表是否存在

min*_*iao 6 python database-migration alembic

我有一个创建表的alembic升级脚本,但是如果它已经存在,我不希望它创建表.

根据alembic doc,我可以将关键字args传递op.create_tablessqlalchemy.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)

  • 请注意:“Inspector”意味着“sqlalchemy.engine.reflection.Inspector” (3认同)
  • 我有很多不同版本的 100 多个表,在每个 create_table 上单独检查它似乎不是一个好主意,有什么通用的解决方案吗? (2认同)

osh*_*ryu -11

这可能是因为该表已经存在。psql只需使用并运行即可从数据库中删除表drop table foo_model;

  • 当表已经存在时,这并不是真正解决迁移本身正常运行的问题。(加上删除表会丢失数据) (4认同)