ecommerceapplication-i7hp4n/migrations/versions/2a3b4c5d6e7f_add_username_field.py

41 lines
1.2 KiB
Python

"""Add username field
Revision ID: 2a3b4c5d6e7f
Revises: 1a2b3c4d5e6f
Create Date: 2023-11-17 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2a3b4c5d6e7f'
down_revision = '1a2b3c4d5e6f'
branch_labels = None
depends_on = None
def upgrade() -> None:
# Add username column to user table
op.add_column('user', sa.Column('username', sa.String(), nullable=True))
# For existing users, initialize username from email
# This is just SQL template code - in a real migration with existing data,
# you would need to handle this appropriately
op.execute("""
UPDATE "user" SET username = email
WHERE username IS NULL
""")
# Now make username non-nullable for future records and add index
with op.batch_alter_table('user') as batch_op:
batch_op.alter_column('username', nullable=False)
batch_op.create_index('ix_user_username', ['username'], unique=True)
def downgrade() -> None:
# Remove username column from user table
with op.batch_alter_table('user') as batch_op:
batch_op.drop_index('ix_user_username')
op.drop_column('user', 'username')