Cannot change the length of String(250) to String using Alembic and SQLAlchemy

Viewed 932

I would like to change from

description = Column(String(250))

to

description = Column(String)

When I generate migration file using below command, it's getting empty.

alembic revision --autogenerate -m "Changing the column size"

Generated migration file:

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


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

Note: I alreday have compare_type=True settings in alembic

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

It generates migration file with alter function when I change String(250) to String(500) but not for String(250) to String, Seems alembic does not support it!

Any help appreciated.

Thanks in advance!

1 Answers

If Alembic is unable to detect the change from String(250) to String() then you'll have to work around it like this:

Change the column in your model to String(251) and run

alembic revision --autogenerate -m "Modified description column"

to generate a revision file that contains something like

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('table1', 'description',
               existing_type=sa.VARCHAR(length=250, collation='SQL_Latin1_General_CP1_CI_AS'),
               type_=sa.String(length=251),
               existing_nullable=True)
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('table1', 'description',
               existing_type=sa.String(length=251),
               type_=sa.VARCHAR(length=250, collation='SQL_Latin1_General_CP1_CI_AS'),
               existing_nullable=True)
    # ### end Alembic commands ###

Edit that file to change the new column type to String() …

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('table1', 'description',
               existing_type=sa.VARCHAR(length=250, collation='SQL_Latin1_General_CP1_CI_AS'),
               type_=sa.String(),
               existing_nullable=True)
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('table1', 'description',
               existing_type=sa.String(),
               type_=sa.VARCHAR(length=250, collation='SQL_Latin1_General_CP1_CI_AS'),
               existing_nullable=True)
    # ### end Alembic commands ###

… and edit your model to use String() as well. Then run the migration

alembic upgrade head

When I tested this with SQL Server it changed the column type from varchar(250) to varchar(MAX).

Related