I am using PostgreSQL and Alembic for migration. When I added new column to my User table Alembic generated migration with the following script:
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')
What I actually want to do is autogenerating the value of username when I upgrade the production version. By other words, my production version has lots of users in it and if I run the above upgrade on it, there will be an error stating that the username cannot be NULL, so I have to delete all the users, upgrade the User table and after add the users again, which is painful. Thus, I want to change the above script with:
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')
As it is stated above in the code I would like to execute a SQL Code that checks the email address like [email protected] and throws everything after '@'sign (in this case '@example.com') and sets the value of username (in this case 'test') after that makes nullable=false.
How can I do that? What must be the script instead of username = <email address with no '@' and everything comes after '@' sign should be removed>
and setting nullable=false
Or if there is any other way of setting username
default value to be email address without @ sing and everything after it?