| name | cli-recipes |
| description | Use when the user asks about "Alembic commands", "database migrations", "flask db migrate", "flask db upgrade", "create migration", "rollback migration", "SQLAlchemy CLI", or needs ready-to-use database migration commands.
|
Alembic / Flask-Migrate CLI Recipes
Ready-to-use commands for database schema migrations.
Flask-Migrate (Flask Projects)
Initial Setup
pip install Flask-Migrate
from flask_migrate import Migrate
def create_app():
app = Flask(__name__)
db.init_app(app)
Migrate(app, db)
return app
flask db init
Migration Workflow
flask db migrate -m "Add phone column to clients"
flask db upgrade
flask db current
Common Operations
flask db upgrade
flask db downgrade
flask db history
flask db current
flask db stamp head
flask db revision -m "Custom migration"
Standalone Alembic
Initial Setup
pip install alembic
alembic init alembic
Edit alembic/env.py to point to your models and database URL.
Migration Workflow
alembic revision --autogenerate -m "Add phone column"
alembic upgrade head
alembic downgrade -1
alembic downgrade abc123
alembic history
alembic current
Manual Migration Edits
Sometimes autogenerate misses changes. Edit the migration file directly:
def upgrade():
op.add_column('clients', sa.Column('phone', sa.String(20), nullable=True))
op.create_index('idx_clients_phone', 'clients', ['phone'])
def downgrade():
op.drop_index('idx_clients_phone', 'clients')
op.drop_column('clients', 'phone')
Common Migration Operations
from alembic import op
import sqlalchemy as sa
op.add_column('table', sa.Column('col', sa.String(100)))
op.drop_column('table', 'col')
op.alter_column('table', 'old_name', new_column_name='new_name')
op.alter_column('table', 'col', type_=sa.Text())
op.create_index('idx_name', 'table', ['col'])
op.create_unique_constraint('uq_name', 'table', ['col'])
op.create_foreign_key('fk_name', 'child', 'parent', ['parent_id'], ['id'])
op.create_table('new_table',
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('name', sa.String(100)),
)
op.drop_table('old_table')
Troubleshooting Migrations
| Issue | Fix |
|---|
| "Target database is not up to date" | Run flask db upgrade first |
| "Can't locate revision" | Run flask db stamp head to reset |
| Autogenerate misses changes | Edit migration manually |
| Migration fails midway | Fix the migration, then flask db upgrade again |
| Need to start fresh | Delete migrations/, run flask db init + flask db migrate |