amrx
amrx

Reputation: 713

Alembic Column type change gives syntax error

There was a change in the type of Column of one of the tables from Integer to String.

Logic(PBase):
__tablename__ = "logic"
Id(Integer, primary_key=True)

this column changed to string

Logic(PBase):
__tablename__ = "logic"
Id(String, primary_key=True)

Now I am using alembic to auto-generate the migration script. To detect type change, I have supplied compare_type=True in env.py

 with connectable.connect() as connection:
    context.configure(
        connection=connection,
        target_metadata=target_metadata,
        compare_type=True
    )

Doing so, the migration script is generated fine. Here is the content of the generated migration script:

from alembic import op       # noqa
import sqlalchemy as sa      # noqa


def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('logics', 'id',
                    existing_type=sa.INTEGER(),
                    type_=sa.String())
    ### end Alembic commands ###


def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('logics', 'id',
                    existing_type=sa.String(),
                    type_=sa.INTEGER())
    ### end Alembic commands ###

But when I run the upgrade command I get a syntax error (here is the end part of traceback):

File "/Users/amit/.virtualenvs/be_new/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 436, in do_execute cursor.execute(statement, parameters) sqlalchemy.exc.OperationalError: (OperationalError) near "ALTER": syntax error u'ALTER TABLE logics ALTER COLUMN id TYPE VARCHAR' ()

What maybe the issue here?

Upvotes: 7

Views: 8672

Answers (1)

John Moutafis
John Moutafis

Reputation: 23134

I had a similar problem which I solved with the following syntax:

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('logics', 'id', type_=sa.String, existing_type=sa.INTEGER)
    ### end Alembic commands ###


def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('logics', 'id', type_=sa.INTEGER, existing_type=sa.VARCHAR)
    ### end Alembic commands ###

Essentially I omitted the parentheses after the type declarations and on the downgrade I used the type VARCHAR because String is not an SQL type.

Upvotes: 7

Related Questions