SQLAlchemy / Alembic: check if table has column
Some times you want to check if a table already has a column befor try to add or drop the column in an alembic migration file.
Helper file
We define us a little helper function for this use case:
from alembic import op from sqlalchemy import engine_from_config from sqlalchemy.engine import reflection def table_has_column(table, column): config = op.get_context().config engine = engine_from_config( config.get_section(config.config_ini_section), prefix='sqlalchemy.') insp = reflection.Inspector.from_engine(engine) has_column = False for col in insp.get_columns(table): if column not in col['name']: continue has_column = True return has_column
This code we put in a file alembic_helpers.py inside the alembic directory, where the env.py file is.
Using the helper function table_has_column
In the alembic version file for our upgrade step, we use it like this to chekc if a table has a column before we try to drop that column:
from alembic import op import imp import os alembic_helpers = imp.load_source('alembic_helpers', ( os.getcwd() + '/' + op.get_context().script.dir + '/alembic_helpers.py')) def upgrade(): if alembic_helpers.table_has_column('reference', 'sections'): op.drop_column('reference', 'sections')