alembic create_table, check if table exists

青春壹個敷衍的年華 提交于 2019-12-10 13:38:18

问题


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

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

回答1:


You can get the list of existing tables like this:

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



回答2:


As it has been said elsewhere ( Check if a table column exists in the database using SQLAlchemy and Alembic) alembic should reflect the full state of your database, that means it would automatically know if a table exists.

Make sure you define the upgrade and downgrade, so that if upgrade creates the table downgrade removes it.

If you do this you can just "downgrade" to the previous revision and upgrade again and it will work. Use autogenerate on a revision to create the initial state.




回答3:


It's probably because the table already exists. Just drop the table from your database by using psql and running drop table foo_model;



来源:https://stackoverflow.com/questions/31299709/alembic-create-table-check-if-table-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!