Skip to content

Instantly share code, notes, and snippets.

@sudodo
Created October 14, 2023 23:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sudodo/cd5f8a7d68ff345b38f02503cb966c3b to your computer and use it in GitHub Desktop.
Save sudodo/cd5f8a7d68ff345b38f02503cb966c3b to your computer and use it in GitHub Desktop.
Migrate Flask DB

Question

When a developer update model classes after executing db.create_all(), can she reflect those updates into DB schema using convenient tools like db.create_all()?

Answer

When the database model classes (schemas) in a Flask application are updated, reflecting these changes in the actual database schema can be a bit tricky, especially when the database already contains data. db.create_all() is quite limited in this respect, as it does not modify existing tables - it only creates new tables if they do not exist.

For handling changes or migrations of the database schema, Flask has an extension called Flask-Migrate, which is built on top of another package called Alembic. Flask-Migrate/Alembic can generate migration scripts automatically based on the changes detected in the models. It also provides a command-line interface to apply the migrations to the database. Here's a basic flow of how it works:

Step 1: Setting Up Flask-Migrate

After defining your models, you will need to set up Flask-Migrate and initialize it. This is generally done in the main application script or a configuration script.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'your_connection_string'
db = SQLAlchemy(app)
migrate = Migrate(app, db)

Step 2: Initialize Flask-Migrate

Once Flask-Migrate is set up, you’ll need to initialize it with the following commands in the terminal. This will create a migrations folder, which will contain versions of schema changes.

$ flask db init

Step 3: Generate a Migration Script

After updating the model classes, generate a migration script with Flask-Migrate. This script will represent the changes between the old schema and the new schema.

$ flask db migrate -m "Your message about this migration"

Step 4: Apply the Migration to the Database

Apply the migration script to the actual database. This will modify the schema of the database to reflect the changes made in the model classes.

$ flask db upgrade

Step 5: Downgrading (if necessary)

If you need to undo a migration, you can use the downgrade command to revert to the previous version.

$ flask db downgrade

This allows you to adapt your database schema in a controlled manner, keeping track of changes, and also providing a mechanism to revert changes if they cause issues. It's particularly useful when working in a team of developers, where database changes need to be synchronized across multiple development environments.

Notes:

  • Always make sure to backup your database before attempting migrations, especially in a production environment, to prevent unintended data loss.
  • Be cautious and review automatically generated migration scripts to ensure that they are performing the actions you expect. Sometimes manual adjustment might be needed.
  • For complex schema changes, it might be practical to perform some operations manually, or to create custom migration scripts.
  • It's advisable to test migrations on a staging or a copy of the database to ensure they perform as expected before applying them to a production database.

And with this, developers can manage changes to their database schema, evolving it as their application requirements change, without losing data.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment