如何在Alembic/SQLAchemy中使用USING子句?

Sie*_*ruc 12 python postgresql sqlalchemy alembic

我想使用Alembic将数据库的列类型从字符串更改为整数.如果我使用纯SQL,它实现了目标:

alter table statistic_ticket alter column tags type bigint using tags::bigint;
Run Code Online (Sandbox Code Playgroud)

但是当我使用Alembic时:

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)
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

HINT: Please use USING clause for carrying out the conversion
Run Code Online (Sandbox Code Playgroud)

SQLAlchemy生成的SQL语句是:

ALTER TABLE statistic_ticket ALTER COLUMN tags TYPE INTEGER' {}
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我怎么做alembic或SQLAlchemy中的SQL op.execute(SQL)吗?

Raz*_*erM 8

从 Alembic 0.8.8 开始,您可以使用postgresql_using关键字:

op.alter_column('statistic_ticket', 'tags', type_=sa.BigInteger,
                postgresql_using='tags::bigint')
Run Code Online (Sandbox Code Playgroud)

在以前的版本中,您必须使用op.execute

op.execute('ALTER TABLE statistic_ticket ALTER COLUMN '
           'tags TYPE bigint USING tags::bigint')
Run Code Online (Sandbox Code Playgroud)