amr*_*mrx 6 python sqlalchemy alembic
其中一个表的列类型从整数更改为字符串。
Logic(PBase):
__tablename__ = "logic"
Id(Integer, primary_key=True)
Run Code Online (Sandbox Code Playgroud)
此列更改为字符串
Logic(PBase):
__tablename__ = "logic"
Id(String, primary_key=True)
Run Code Online (Sandbox Code Playgroud)
现在我正在使用 alembic 自动生成迁移脚本。为了检测类型更改,我在 env.py 中提供了compare_type=True
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
compare_type=True
)
Run Code Online (Sandbox Code Playgroud)
这样做,迁移脚本就生成好了。以下是生成的迁移脚本的内容:
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 ###
Run Code Online (Sandbox Code Playgroud)
但是当我运行升级命令时,我收到语法错误(这是回溯的结束部分):
文件“/Users/amit/.virtualenvs/be_new/lib/python2.7/site-packages/sqlalchemy/engine/default.py”,第436行,在do_executecursor.execute(语句,参数)sqlalchemy.exc.OperationalError: (操作错误)“ALTER”附近:语法错误 u'ALTER TABLE 逻辑 ALTER COLUMN id TYPE VARCHAR' ()
这里可能有什么问题?
我有一个类似的问题,我用以下语法解决了:
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 ###
Run Code Online (Sandbox Code Playgroud)
本质上,我省略了类型声明后面的括号,并且downgrade我使用了该类型VARCHAR,因为String它不是 SQL 类型。