Introduction Migrations

What are migrations?

  • A migration is a file that keeps track of changes to our database schema (structure of our database).

  • Offers version control on our schema.

  • Migrations deal with how we manage modifications to our data schema, over time.

Benefits of migrations in our app:

  • Mistakes to our database schema are very expensive to make.

  • The entire app can go down, so we want to quickly roll back changes, and test changes before we make them.

  • Encapsulate a set of changes to our database schema, made over time.

  • Are uniquely named.

  • Are usually stored as local files in our project repo, e.g. a migrations/ folder.

  • There should be a one-to-one mapping between the changes made to our database, and the migration files that exist in our migrations/ folder.

  • Our migrations files set up the tables for our database.

  • All changes made to our db should exist physically as part of migration files in our repository.

Upgrades and rollbacks:

  • Migrations stack together in order to form the latest version of our database schema.

  • We can upgrade our database schema by applying migrations.

  • We can roll back our database schema to a former version by reverting the migrations that we applied.

Migration command-line scripts:

There are generally 3 scripts needed, for:

  • migrate: creating a migration script template to fill out; generating a migration file based on changes to be made

  • upgrade: applying migrations that hadn't been applied yet ("upgrading" our database)

  • downgrade: rolling back applied migrations that were problematic ("downgrading" our database)

Why use migrations?

Without migrations:

  • We do heavy-handed work, creating and recreating the same tables in our database even for minor changes.

  • We can lose existing data in older tables we dropped.

With migrations:

  • Auto-detects changes from the old version & new version of the SQLAlchemy models.

  • Creates a migration script that resolves differences between the old & new versions.

  • Gives fine-grain control to change existing tables.

This is much better, because:

  • We can keep existing schema structures, only modifying what needs to be modified.

  • We can keep existing data.

  • We isolate units of change in migration scripts that we can roll back to a “safe” db state.


Flask-Migrate commands:

pip install Flask-Migrate
flask db --help

flask db init

  • Create initial migrations directory structure.

flask db migrate

  • Detects the model changes to be made and creates a migration file with an upgrade and downgrade logic set up.

(replaces use of db.create_all()).

flask db upgrade

  • Runs the upgrade command in the migration file, to apply the migration.

flask db downgrade

  • Runs the downgrade command in the migration file, to roll back in migration.