PROGRAMMING

Alembic - migration for String length change

#python , #sqlalchemy , #alembic

Recently I wanted to change the length of String field, something like:

my_field = Column(String(10), nullable=False)

to

my_field = Column(String(20), nullable=False)

After running alembic revision --autogenerate -m 'Some description' the update and downgrade methods were empty.

revision = '1d9d8d3187b6'
down_revision = '24a05a2fbaf1'
branch_labels = None
depends_on = None

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    ### end Alembic commands ###


def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    ### end Alembic commands ###

Why? After some research, I found the solution.

Alembic has turned off this feature by default and it doesn’t detect changes like this (documentation). You can enable it by adding compare_type=True in context. Edit alembic/env.py file and add compare_type=True in context. For me it looks like this:

Edit run_migrations_offline() method:

context.configure(
    url=url, target_metadata=target_metadata, literal_binds=True,
    compare_type=True
)

Edit run_migrations_online() method:

context.configure(
    connection=connection,
    target_metadata=target_metadata,
    compare_type=True
)

Since now Alembic will detect changes like this made by me.

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('mymodel', 'myfield',
               existing_type=sa.VARCHAR(length=10),
               type_=sa.String(length=20),
               existing_nullable=False)
    ### end Alembic commands ###


def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('mymodel', 'myfield',
               existing_type=sa.String(length=20),
               type_=sa.VARCHAR(length=10),
               existing_nullable=False)
    ### end Alembic commands ###

Side note, if you get an error:

FAILED: Target database is not up to date.

this simply means that you don’t have all migrations applied. Run alembic upgrade head and after that, migration should work correctly.