Created
May 2, 2018 19:30
-
-
Save jmuhlich/2c9580ad366568f2ac60cb221b0f225d to your computer and use it in GitHub Desktop.
Revisions
-
jmuhlich created this gist
May 2, 2018 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,26 @@ 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))