| 
 | 1 | +#!/usr/bin/env python3  | 
 | 2 | +"""  | 
 | 3 | +Database migration script to add theme_preference column to existing users.  | 
 | 4 | +Run this script once to update the database schema.  | 
 | 5 | +"""  | 
 | 6 | + | 
 | 7 | +import sys  | 
 | 8 | +import os  | 
 | 9 | + | 
 | 10 | +# Add the app directory to Python path  | 
 | 11 | +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))  | 
 | 12 | + | 
 | 13 | +from app import create_app  | 
 | 14 | +from app.models import db, User  | 
 | 15 | + | 
 | 16 | +def add_theme_column():  | 
 | 17 | +    """Add theme_preference column to users table if it doesn't exist"""  | 
 | 18 | +    app = create_app()  | 
 | 19 | +      | 
 | 20 | +    with app.app_context():  | 
 | 21 | +        try:  | 
 | 22 | +            # Check if the column already exists by trying to query it  | 
 | 23 | +            result = db.session.execute("SELECT theme_preference FROM user LIMIT 1")  | 
 | 24 | +            print("Column 'theme_preference' already exists in the database.")  | 
 | 25 | +            return True  | 
 | 26 | +        except Exception as e:  | 
 | 27 | +            print(f"Column 'theme_preference' does not exist. Adding it now...")  | 
 | 28 | +              | 
 | 29 | +            try:  | 
 | 30 | +                # Add the column with default value 'light'  | 
 | 31 | +                db.session.execute("ALTER TABLE user ADD COLUMN theme_preference VARCHAR(20) DEFAULT 'light'")  | 
 | 32 | +                db.session.commit()  | 
 | 33 | +                print("Successfully added 'theme_preference' column to user table.")  | 
 | 34 | +                  | 
 | 35 | +                # Update all existing users to have light theme by default  | 
 | 36 | +                users_updated = User.query.filter(User.theme_preference.is_(None)).update(  | 
 | 37 | +                    {'theme_preference': 'light'}, synchronize_session=False  | 
 | 38 | +                )  | 
 | 39 | +                db.session.commit()  | 
 | 40 | +                print(f"Updated {users_updated} existing users with default light theme.")  | 
 | 41 | +                  | 
 | 42 | +                return True  | 
 | 43 | +            except Exception as e:  | 
 | 44 | +                print(f"Error adding column: {e}")  | 
 | 45 | +                db.session.rollback()  | 
 | 46 | +                return False  | 
 | 47 | + | 
 | 48 | +if __name__ == "__main__":  | 
 | 49 | +    print("Adding theme_preference column to database...")  | 
 | 50 | +    success = add_theme_column()  | 
 | 51 | +    if success:  | 
 | 52 | +        print("Database migration completed successfully!")  | 
 | 53 | +        sys.exit(0)  | 
 | 54 | +    else:  | 
 | 55 | +        print("Database migration failed!")  | 
 | 56 | +        sys.exit(1)  | 
0 commit comments