Refine username field migration to follow SQLite constraints

This commit is contained in:
Automated Action 2025-05-26 13:36:26 +00:00
parent 2e92746b97
commit 185226a858

View File

@ -18,10 +18,8 @@ depends_on = None
def upgrade() -> None: def upgrade() -> None:
# Add username column to user table # Add username column to user table
with op.batch_alter_table('user') as batch_op: op.add_column('user', sa.Column('username', sa.String(), nullable=True))
batch_op.add_column(sa.Column('username', sa.String(), nullable=True))
batch_op.create_index('ix_user_username', ['username'], unique=True)
# For existing users, initialize username from email # For existing users, initialize username from email
# This is just SQL template code - in a real migration with existing data, # This is just SQL template code - in a real migration with existing data,
# you would need to handle this appropriately # you would need to handle this appropriately
@ -30,13 +28,14 @@ def upgrade() -> None:
WHERE username IS NULL WHERE username IS NULL
""") """)
# Now make username non-nullable for future records # Now make username non-nullable for future records and add index
with op.batch_alter_table('user') as batch_op: with op.batch_alter_table('user') as batch_op:
batch_op.alter_column('username', nullable=False) batch_op.alter_column('username', nullable=False)
batch_op.create_index('ix_user_username', ['username'], unique=True)
def downgrade() -> None: def downgrade() -> None:
# Remove username column from user table # Remove username column from user table
with op.batch_alter_table('user') as batch_op: with op.batch_alter_table('user') as batch_op:
batch_op.drop_index('ix_user_username') batch_op.drop_index('ix_user_username')
batch_op.drop_column('username') op.drop_column('user', 'username')