How to use USING clause in Alembic/SQLAchemy?

5.3k Views Asked by At

I would like to change column type of the database from string to integer by using Alembic. If I use pure SQL, it achieves the goal:

alter table statistic_ticket alter column tags type bigint using tags::bigint;

But when I use Alembic like:

import sqlalchemy as sa
def upgrade():
    op.alter_column('statistic_ticket', 'tags', nullable = True, existing_type=sa.String(length=255), type_=sa.Integer, existing_nullable=True)

I got an error:

HINT: Please use USING clause for carrying out the conversion

The SQL statement generated by SQLAlchemy was:

ALTER TABLE statistic_ticket ALTER COLUMN tags TYPE INTEGER' {}

Can someone show me how to do in alembic or the SQL in SQLAlchemy via op.execute(SQL)?

1

There are 1 best solutions below

0
On

From Alembic 0.8.8, you can use the postgresql_using keyword:

op.alter_column('statistic_ticket', 'tags', type_=sa.BigInteger,
                postgresql_using='tags::bigint')

On prior versions, you have to use op.execute:

op.execute('ALTER TABLE statistic_ticket ALTER COLUMN '
           'tags TYPE bigint USING tags::bigint')