alembic create_table,检查表是否存在

时间:2015-07-08 17:33:23

标签: python database-migration alembic

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

根据alembic doc,我可以将sqlalchemy.schema.table接受的关键字参数传递给op.create_tables,因此我使用的是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
  )

但是我仍然得到表已存在的错误。

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

4 个答案:

答案 0 :(得分:2)

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

permissions

然后检查表是否已经存在

manifest.js

答案 1 :(得分:1)

正如其他地方(Check if a table column exists in the database using SQLAlchemy and Alembic)所述,alembic应该反映数据库的完整状态,这意味着它会自动知道表是否存在。

确保定义升级和降级,以便在升级创建表时降级将其删除。

如果你这样做,你只需“降级”到之前的版本并再次升级它就可以了。在修订上使用autogenerate来创建初始状态。

答案 2 :(得分:0)

如果有人想要,这里有一个完整的解决方案

from alembic import op
from sqlalchemy import engine_from_config
from sqlalchemy.engine import reflection

def _has_table(table_name):
    config = op.get_context().config
    engine = engine_from_config(
        config.get_section(config.config_ini_section), prefix="sqlalchemy."
    )
    inspector = reflection.Inspector.from_engine(engine)
    tables = inspector.get_table_names()
    return table_name in tables

答案 3 :(得分:-3)

这可能是因为该表已经存在。只需使用psql并运行drop table foo_model;

即可从数据库中删除该表