Database Migrations (Flask-Migrate)
Migrations solve a dangerous problem:
- your models change over time
- your database schema must change too
- you need a safe, repeatable way to apply those changes
Flask-Migrate wraps Alembic to manage migrations.
flowchart TD
A["you change a model"] --> B{"how is the schema updated?"}
B -->|"db.create_all()"| C["existing tables are left ALONE"]
C --> D["the new column never appears"]
D --> E["OperationalError: no such column"]
B -->|"Flask-Migrate"| F["flask db migrate -- autogenerate a script"]
F --> G["read the script; autogenerate misses some changes"]
G --> H["flask db upgrade -- apply it"]
H --> I["the version is recorded in alembic_version"]
I --> J["flask db downgrade can walk it back"]
Install
Section titled “Install”pip install Flask-Migratefrom flask_migrate import Migrate
migrate = Migrate(app, db)Typical workflow
Section titled “Typical workflow”- Initialize migrations folder:
flask db init- Create a migration script:
flask db migrate -m "create users table"- Apply it:
flask db upgradeKey idea
Section titled “Key idea”migrategenerates migration scripts from model diffsupgradeapplies them to the database
Best practices
Section titled “Best practices”- review generated scripts before applying
- commit migrations to git
- run migrations in CI/staging before production
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading