from alembic import op from alembic.operations.ops import CreatePrimaryKeyOp, CreateForeignKeyOp import sqlalchemy as sa def upgrade(): conn = op.get_bind() ctx = op.get_context() existing_metadata = sa.schema.MetaData() target_metadata = ctx.opts['target_metadata'] # Rename table. new_name = 'new_table_name' op.rename_table('old_table_name', new_name) # Drop PK and FKs reflected from existing table. existing_table = sa.Table(new_name, existing_metadata, autoload_with=conn) op.drop_constraint(existing_table.primary_key.name, new_name) for c in existing_table.foreign_key_constraints: op.drop_constraint(c.name, new_name) # Recreate PK and FKs according to naming convention and current class name. target_table = sa.Table(new_name, target_metadata) op.invoke(CreatePrimaryKeyOp.from_constraint(target_table.primary_key)) for c in target_table.foreign_key_constraints: op.invoke(CreateForeignKeyOp.from_constraint(c))