alembic create_table,检查表是否存在 [英] alembic create_table, check if table exists

查看:172
本文介绍了alembic create_table,检查表是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Alembic升级脚本,可以创建一个表,但是如果它已经存在,我不希望它创建表。

I have an alembic upgrade script that creates a table, however I don't want it to create the table if it already exists.

根据学术文档,我可以将关键字args传递给< op.create_tables rel = noreferrer> sqlalchemy.schema.table ,所以我使用了 keep_existing 关键字:

According to the alembic doc, I can pass in keyword args to op.create_tables that are acceptable to sqlalchemy.schema.table, so I'm using the keep_existing keyword:

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
  )

但是我仍然在获取表已存在错误。

However I'm still getting the table already exists error.

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' ()


推荐答案

您可以像这样获得现有表的列表:

You can get the list of existing tables like this:

from sqlalchemy.engine.reflection import Inspector

conn = op.get_bind()
inspector = Inspector.from_engine(conn)
tables = inspector.get_table_names()

,然后检查表是否已经存在

and then check if table already exists or not

if table_name not in tables:
   op.create_table()

这篇关于alembic create_table,检查表是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆