添加非主键 Alembic 的自增列

adr*_*ino 5 python mysql sqlalchemy python-3.x alembic

我想添加一个自动增量列,它不是现有 MySQL 数据库的主键。

此操作所需的服务器上发出的命令如下:

ALTER TABLE `mytable` ADD `id` INT UNIQUE NOT NULL AUTO_INCREMENT FIRST
Run Code Online (Sandbox Code Playgroud)

我面临的问题是如何通过 Alembic 迁移复制此表更改。我试过了:

from alembic import op
import sqlalchemy as sa

def upgrade():
    op.add_column('mytable', sa.Colummn('id', sa.INTEGER(), 
                  nullable=False, autoincrement=True)
Run Code Online (Sandbox Code Playgroud)

但是当我尝试使用以下命令插入一行时:

INSERT INTO `mytable` (`col1`, `col2`) VALUES (`bar`);
Run Code Online (Sandbox Code Playgroud)

其中col1col2是不可为空的列。当我插入这条记录时,我希望表自动为我生成 id。

ERROR 1364 (HY000): Field 'id' doesn't have a default value
Run Code Online (Sandbox Code Playgroud)

如果我使用以下命令检查 Alembic 自动生成的 sql:

alembic upgrade 'hash-of-revision' --sql
Run Code Online (Sandbox Code Playgroud)

它吐出,对于给定的修订:

ALTER TABLE mytable ADD COLUMN id INTEGER NOT NULL;
Run Code Online (Sandbox Code Playgroud)

这意味着 Alembic 或 SQLAlchemyautoincrement在生成迁移的 sql 时会忽略该字段。

有没有办法解决这个问题?或者我可以基于自定义 sql 命令建立迁移吗?

小智 3

首先我们添加列并允许它具有空值

op.add_column('abc', Column('id', BIGINT(unsigned=True), comment='This column stores the type of phrase') )

然后我们创建主键

op.create_primary_key( 'abc_pk', table_name='abc', columns=['id'] )

不知道它如何允许我在空列上添加主键,但我想这是因为它位于事务块中。

然后我们更改列以具有自动增量列

op.alter_column( existing_type=BIGINT(unsigned=True), table_name='abc', column_name='id', autoincrement=True, existing_autoincrement=True, nullable=False)