Migrations with Flask-Migrate
Key Concepts
- Database Migrations
- Flask-Migrate
- Migration Commands
- Schema Changes
- Version Control for Databases
Database Migrations
Database migrations are a way to manage changes to the database schema over time. They allow you to evolve your database schema in a controlled and organized manner, ensuring that all instances of your application use the correct schema.
Flask-Migrate
Flask-Migrate is an extension for Flask that handles SQLAlchemy database migrations. It integrates with Alembic, a lightweight database migration tool, to provide a simple interface for managing database schema changes.
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db' db = SQLAlchemy(app) migrate = Migrate(app, db)
Migration Commands
Flask-Migrate provides several commands to manage migrations. These commands include creating a new migration, upgrading the database to the latest version, and rolling back to a previous version.
# Initialize the migration repository flask db init # Create a new migration script flask db migrate -m "Initial migration" # Apply the migration to the database flask db upgrade # Rollback to the previous version flask db downgrade
Schema Changes
Schema changes involve modifying the structure of your database tables. This can include adding new tables, modifying existing tables, or deleting tables. Migrations help manage these changes by creating scripts that describe the changes to be applied.
class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) # After adding a new column class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) age = db.Column(db.Integer, nullable=True)
Version Control for Databases
Just as code is version-controlled using tools like Git, database schema changes can be version-controlled using migrations. This ensures that all developers and environments use the same database schema, reducing errors and inconsistencies.
# Example of a migration script def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('user', sa.Column('age', sa.Integer(), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('user', 'age') # ### end Alembic commands ###