我正在使用 PostgreSQL 和 Alembic 进行迁移。当我向我的用户表添加新列时,Alembic 使用以下脚本生成了迁移:
revision = '4824acf75bf3'
down_revision = '2f0fbdd56de1'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column(
'user',
sa.Column(
'username',
sa.Unicode(length=255),
nullable=False
)
)
def downgrade():
op.drop_column('user', 'username')
我真正想做的是在升级生产版本时自动生成用户名的值。换句话说,我的生产版本有很多用户,如果我在上面运行上面的升级,会出现一个错误,指出用户名不能为 NULL,所以我必须删除所有用户,升级用户表和再次添加用户后,这很痛苦。因此,我想改变上面的脚本:
revision = '4824acf75bf3'
down_revision = '2f0fbdd56de1'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column(
'user',
sa.Column(
'username',
sa.Unicode(length=255)
)
)
op.execute(
'UPDATE "user" set username = <email address with no '@'
and everything comes after '@' sign should be removed>
WHERE email is not null'
)
<only after the above code is executed 'nullable=False' must be set up>
def downgrade():
op.drop_column('user', 'username')
正如上面代码中所述,我想执行一个 SQL 代码来检查电子邮件地址,如 test@example.com,并在“@”符号(在本例中为“@example.com”)之后抛出所有内容并设置值之后的用户名(在本例中为“test”)使 nullable=false。
我怎样才能做到这一点?什么必须是脚本而不是username = <email address with no '@' and everything comes after '@' sign should be removed>
和设置nullable=false
或者,如果有任何其他方法可以将username
默认值设置为不带@sing 的电子邮件地址以及之后的所有内容?