Skip to content

Instantly share code, notes, and snippets.

@jmuhlich
Created May 2, 2018 19:30
Show Gist options
  • Save jmuhlich/2c9580ad366568f2ac60cb221b0f225d to your computer and use it in GitHub Desktop.
Save jmuhlich/2c9580ad366568f2ac60cb221b0f225d to your computer and use it in GitHub Desktop.
Alembic migration to rename primary and foreign key constraints along with a table rename
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))
@dfeinzeig
Copy link

super helpful! thanks!

only thing this misses is the sequence for the primary key. you can add something like:

op.execute("ALTER SEQUENCE old_table_name_id_seq RENAME TO new_table_name_id_seq;")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment