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.

Revisions

  1. jmuhlich created this gist May 2, 2018.
    26 changes: 26 additions & 0 deletions migrate.py
    Original 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))