Search code examples
pythonalembic

Squash multiple migrations into one


I did multiple minor migrations.

  1. Add column A
  2. Remove column A
  3. Add column A

Is it possible to squash these migrations into one?


Solution

  • There's no automatic way to do it, but it's pretty straightforward to do it manually. For illustration, you have the following migrations A through E and all migrations are applied to the database (current is E). You want to squash C through E.

    A > B > C > D > E
    
    1. Copy the contents of the upgrade and downgrade functions from C and D into E. Maintain the order of operations, and remove redundant operations (in your example you'd actually just end up with the contents of E).
    2. Change the down_revision of E to point to B instead of D.
    3. Delete C and D, which are no longer connected to the graph.