min*_*sky 7 python sqlalchemy alembic
我正在尝试使用alembic将'id'主键列添加到已存在的MySQL表中.我试过以下......
op.add_column('mytable', sa.Column('id', sa.Integer(), nullable=False))
op.alter_column('mytable', 'id', autoincrement=True, existing_type=sa.Integer(), existing_server_default=False, existing_nullable=False)
Run Code Online (Sandbox Code Playgroud)
但得到以下错误
sqlalchemy.exc.OperationalError: (OperationalError) (1075, 'Incorrect table definition; there can be only one auto column and it must be defined as a key') 'ALTER TABLE mytable CHANGE id id INTEGER NOT NULL AUTO_INCREMENT' ()
Run Code Online (Sandbox Code Playgroud)
看起来像是由alembic生成的sql语句没有PRIMARY KEY在alter语句的末尾添加.我可以错过一些设置吗?
提前致谢!
Rac*_*ers 20
我花了一些时间挖掘alembic源代码,这似乎不受支持.您可以在创建表时指定主键,但在添加列时不能指定.事实上,它专门检查,不会让你:
# from alembic.operations.toimpl.add_column, line 132
for constraint in t.constraints:
if not isinstance(constraint, sa_schema.PrimaryKeyConstraint):
operations.impl.add_constraint(constraint)
Run Code Online (Sandbox Code Playgroud)
我环顾四周,向现有表添加主键可能会导致未指定的行为 - 主键不应为null,因此您的引擎可能会也可能不会为现有行创建主键.有关详细信息,请参阅此SO讨论:将 自动增量主键插入现有表
我只是直接运行alter query,并在需要时创建主键.
op.execute("ALTER TABLE mytable ADD id INT PRIMARY KEY AUTO_INCREMENT;")
Run Code Online (Sandbox Code Playgroud)
如果你真的需要跨引擎兼容性,那么大锤子就是(1)用一个主键创建一个与旧表相同的新表,(2)迁移所有数据,(3)删除旧表和(4) )重命名新表.
希望有所帮助.
| 归档时间: |
|
| 查看次数: |
5917 次 |
| 最近记录: |