Anton Sarukhanov

Full-Stack Developer

Squashing SQLAlchemy Migrations with Flask-Migrate

While developing a Python application with SQLAlchemy, you may find yourself rapidly iterating on database schemas as your project evolves. If you are committing your work often (as you should be), this can lead to oodles of schema migration scripts. When a project is in production, these migrations are great for rapidly deploying changes. Until then, there is little use in accumulating a pile of migrations representing every small tweak you made to your models. Squashing these migration scripts into a single "initial" migration is good for your sanity, and results in a leaner git repository. I didn't find the process of squashing your alembic migrations to be well-documented online, so here's my version.

Squashing Some Migrations🔗

If you only want to squash some of your migration history, but not all of it, follow the instructions outlined in this StackOverflow answer.

Squashing All Migrations🔗

This may be obvious already, but I'll share hoping it saves someone a few minutes of hassle. If you want to squash all of your migrations into one "initial migration", do the following. Your migrations will be re-created as a single script, based on the current state of your models.

Note: These steps may need to be adapted depending on your project's structure. I am using Alembic via Flask-Migrate.

  • Truncate your alembic_version table.
    sql> TRUNCATE TABLE alembic_version;
  • Delete the migrations directory.
    rm -rf migrations
  • Re-create the migrations directory from scratch.
    python manage.py db init
  • Create your database schema (from your model definitions) as a single migration.
    python manage.py db migrate
  • Apply any pending migrations (if your database isn't already up-to-date).
    python manage.py db upgrade