2012-12-07 75 views
6

我正在嘗試使用alembic將「主鍵」列添加到已有的MySQL表中。我嘗試以下...將主鍵添加到alembic中的現有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) 

而且得到了以下錯誤

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'() 

看起來像由蒸餾器生成的ALTER語句的結尾沒有添加PRIMARY KEY的SQL語句。我可以錯過一些設置嗎?

在此先感謝!

回答

16

我花了一些時間挖掘alembic源代碼,這似乎並不支持。您可以在創建表時指定主鍵,但在添加列時不能。事實上,它專門檢查,不會讓你:

# from alembic.operations.add_column, line 284 
for constraint in t.constraints: 
    if not isinstance(constraint, schema.PrimaryKeyConstraint): 
    self.impl.add_constraint(constraint) 

我環顧四周,並添加主鍵到現有表可能會導致不確定的行爲 - 主鍵不應該爲空,所以您的引擎可能會或可能不會爲現有行創建主鍵。請參閱此SO討論以獲取更多信息:Insert auto increment primary key to existing table

我只是直接運行alter query,並在需要時創建主鍵。

op.execute("ALTER TABLE mytable ADD id INT PRIMARY KEY AUTO_INCREMENT;") 

如果你真的需要跨引擎的兼容性,大鐵錘將(1)創建一個新表等同於舊有一個主鍵,(2)遷移所有數據,(3)刪除舊錶並(4)重命名新表。

希望有所幫助。