Migrating databases using Alembic and Flask-Migrate
Updating database schema is an important use case for all applications, as it involves adding or removing tables and/or columns or changing column types. One way is to drop the database and then create a new one using db.drop_all()
and db.create_all()
. However, this approach cannot be followed for applications in production or even in staging. We would like to migrate our database to match the newly updated model with all the data intact.
For this, we have Alembic, a Python-based tool for managing database migrations, which uses SQLAlchemy as the underlying engine. Alembic provides automatic migrations to a great extent with some limitations (of course, we cannot expect any tool to be seamless). As the icing on the cake, we have a Flask extension called Flask-Migrate, which eases the process of migrations even more. In this recipe, we will cover the basics of database migration techniques using Alembic and Flask-Migrate.