Files
team-tryouts/migrate_usernames.py

58 lines
2.2 KiB
Python

"""Data migration script to fix corrupted username fields.
This script fixes the bug where user.username was incorrectly set to full_name
instead of preserving the actual username. It migrates existing users by:
1. Setting username to a slug version of full_name (e.g., 'sarah-johnson')
2. Clearing full_name to empty string (will be collected via profile edit)
Run this script once to fix existing database records.
"""
from app import create_app
from extensions import db
from models import User
def slugify(name):
"""Convert a name to a username-friendly slug.
Args:
name (str): Full name to convert.
Returns:
str: Slugified username.
"""
return name.lower().replace(' ', '-').replace("'", '')
def migrate():
"""Migrate existing users to fix corrupted username/full_name fields."""
with app.app_context():
users = User.query.all()
migrated = 0
for user in users:
# If username looks like a full name (contains spaces), migrate it
if ' ' in user.username:
# Save the current username (which is actually the full name)
actual_full_name = user.username
# Generate a username from the full name
new_username = slugify(actual_full_name)
# Ensure uniqueness
base_username = new_username
counter = 1
while User.query.filter_by(username=new_username).first() and User.query.get(user.id).username != new_username:
new_username = f"{base_username}-{counter}"
counter += 1
user.username = new_username
user.full_name = actual_full_name
migrated += 1
print(f"Migrated: '{actual_full_name}' -> username='{new_username}', full_name='{actual_full_name}'")
db.session.commit()
print(f"\n[MIGRATION] Migrated {migrated} users")
print("Done! Usernames are now properly stored.")
print("Users should edit their profile to set a proper username and full name.")
if __name__ == '__main__':
app = create_app()
migrate()