|
| 1 | +""" |
| 2 | +Migration script to standardize user avatar fields to imageUrl. |
| 3 | +This script: |
| 4 | +1. Identifies users with avatar field but no imageUrl field |
| 5 | +2. Copies avatar values to imageUrl field |
| 6 | +3. Removes the deprecated avatar field |
| 7 | +4. Logs migration statistics |
| 8 | +""" |
| 9 | + |
| 10 | +import json |
| 11 | +import logging |
| 12 | +import os |
| 13 | +import sys |
| 14 | +from datetime import datetime |
| 15 | + |
| 16 | +from backup_db import create_backup |
| 17 | +from bson import ObjectId |
| 18 | +from dotenv import load_dotenv |
| 19 | +from pymongo import MongoClient, UpdateOne |
| 20 | + |
| 21 | +# Add the script's directory to Python path |
| 22 | +SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) |
| 23 | +sys.path.append(SCRIPT_DIR) |
| 24 | + |
| 25 | + |
| 26 | +# Load environment variables from the backend directory |
| 27 | +BACKEND_DIR = os.path.dirname(SCRIPT_DIR) |
| 28 | +load_dotenv(os.path.join(BACKEND_DIR, ".env")) |
| 29 | + |
| 30 | +# Get MongoDB connection details from environment |
| 31 | +MONGODB_URL = os.getenv("MONGODB_URL") |
| 32 | +DATABASE_NAME = os.getenv("DATABASE_NAME") |
| 33 | + |
| 34 | +# Configure logging |
| 35 | +logging.basicConfig(level=logging.INFO) |
| 36 | +logger = logging.getLogger(__name__) |
| 37 | + |
| 38 | +# Set up file logging |
| 39 | +log_dir = "logs" |
| 40 | +os.makedirs(log_dir, exist_ok=True) |
| 41 | +log_file = os.path.join( |
| 42 | + log_dir, f"migration_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log" |
| 43 | +) |
| 44 | +file_handler = logging.FileHandler(log_file) |
| 45 | +file_handler.setFormatter( |
| 46 | + logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") |
| 47 | +) |
| 48 | +logger.addHandler(file_handler) |
| 49 | + |
| 50 | +# Validate required environment variables |
| 51 | +if not MONGODB_URL: |
| 52 | + logger.error("MONGODB_URL environment variable is required") |
| 53 | + sys.exit(1) |
| 54 | +if not DATABASE_NAME: |
| 55 | + logger.error("DATABASE_NAME environment variable is required") |
| 56 | + sys.exit(1) |
| 57 | + |
| 58 | + |
| 59 | +def migrate_avatar_to_imageurl(): |
| 60 | + """ |
| 61 | + Migrate avatar field to imageUrl in users collection. |
| 62 | + Returns statistics about the migration. |
| 63 | + """ |
| 64 | + try: |
| 65 | + # First create a backup |
| 66 | + logger.info("Creating database backup...") |
| 67 | + backup_path, backup_metadata = create_backup() |
| 68 | + logger.info(f"Backup created at: {backup_path}") |
| 69 | + |
| 70 | + # Connect to MongoDB |
| 71 | + client = MongoClient(MONGODB_URL) |
| 72 | + db = client[DATABASE_NAME] |
| 73 | + users = db.users |
| 74 | + |
| 75 | + # Find users with avatar field |
| 76 | + users_with_avatar = users.find({"avatar": {"$exists": True}}) |
| 77 | + users_to_update = [] |
| 78 | + stats = { |
| 79 | + "total_users": users.count_documents({}), |
| 80 | + "users_with_avatar": 0, |
| 81 | + "users_with_both_fields": 0, |
| 82 | + "users_updated": 0, |
| 83 | + "conflicts": 0, |
| 84 | + } |
| 85 | + |
| 86 | + for user in users_with_avatar: |
| 87 | + stats["users_with_avatar"] += 1 |
| 88 | + |
| 89 | + # Check for conflicts (users with both fields) |
| 90 | + if "imageUrl" in user and user["imageUrl"] is not None: |
| 91 | + if user["imageUrl"] != user["avatar"]: |
| 92 | + logger.warning( |
| 93 | + f"Conflict found for user {user['_id']}: " |
| 94 | + f"avatar='{user['avatar']}', imageUrl='{user['imageUrl']}'" |
| 95 | + ) |
| 96 | + stats["conflicts"] += 1 |
| 97 | + continue |
| 98 | + stats["users_with_both_fields"] += 1 |
| 99 | + |
| 100 | + # Prepare update |
| 101 | + users_to_update.append( |
| 102 | + UpdateOne( |
| 103 | + {"_id": user["_id"]}, |
| 104 | + {"$set": {"imageUrl": user["avatar"]}, "$unset": { |
| 105 | + "avatar": ""}}, |
| 106 | + ) |
| 107 | + ) |
| 108 | + |
| 109 | + # Perform bulk update if there are users to update |
| 110 | + if users_to_update: |
| 111 | + result = users.bulk_write(users_to_update) |
| 112 | + stats["users_updated"] = result.modified_count |
| 113 | + logger.info(f"Successfully updated {result.modified_count} users") |
| 114 | + |
| 115 | + return stats |
| 116 | + |
| 117 | + except Exception as e: |
| 118 | + logger.error(f"Migration failed: {str(e)}") |
| 119 | + raise |
| 120 | + |
| 121 | + |
| 122 | +def rollback_migration(backup_path): |
| 123 | + """ |
| 124 | + Rollback the migration using a specified backup. |
| 125 | + """ |
| 126 | + try: |
| 127 | + client = MongoClient(MONGODB_URL) |
| 128 | + db = client[DATABASE_NAME] |
| 129 | + |
| 130 | + backup_file_path = os.path.join(backup_path, "users.json") |
| 131 | + if not os.path.exists(backup_file_path): |
| 132 | + raise FileNotFoundError( |
| 133 | + f"Backup file not found: {backup_file_path}") |
| 134 | + |
| 135 | + # Read users collection backup |
| 136 | + with open(backup_file_path, "r") as f: |
| 137 | + users_backup = json.load(f) |
| 138 | + |
| 139 | + # Convert string IDs back to ObjectId |
| 140 | + for user in users_backup: |
| 141 | + user["_id"] = ObjectId(user["_id"]) |
| 142 | + |
| 143 | + # Replace current users collection with backup |
| 144 | + db.users.drop() |
| 145 | + if users_backup: |
| 146 | + db.users.insert_many(users_backup) |
| 147 | + |
| 148 | + logger.info(f"Successfully rolled back to backup: {backup_path}") |
| 149 | + return True |
| 150 | + |
| 151 | + except Exception as e: |
| 152 | + logger.error(f"Rollback failed: {str(e)}") |
| 153 | + raise |
| 154 | + |
| 155 | + |
| 156 | +if __name__ == "__main__": |
| 157 | + logger.info("Starting avatar to imageUrl migration...") |
| 158 | + stats = migrate_avatar_to_imageurl() |
| 159 | + |
| 160 | + logger.info("\nMigration completed. Statistics:") |
| 161 | + logger.info(f"Total users: {stats['total_users']}") |
| 162 | + logger.info(f"Users with avatar field: {stats['users_with_avatar']}") |
| 163 | + logger.info(f"Users with both fields: {stats['users_with_both_fields']}") |
| 164 | + logger.info(f"Users updated: {stats['users_updated']}") |
| 165 | + logger.info(f"Conflicts found: {stats['conflicts']}") |
| 166 | + |
| 167 | + print("\nMigration completed. Check the log file for details:", log_file) |
0 commit comments