alembic create_table, check if table exists alembic create_table, check if table exists python python

alembic create_table, check if table exists


You can get the list of existing tables like this:

from sqlalchemy.engine.reflection import Inspectorconn = 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()


Here is a full solution if anyone wants

from alembic import opfrom sqlalchemy import engine_from_configfrom sqlalchemy.engine import reflectiondef _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


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.