#!/usr/bin/env python3 """ Migration script to migrate is_admin to role column in user table """ import sys import os # Add parent directory to path to import app modules sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from sqlalchemy import text from app.database import engine def migrate(): """Migrate is_admin column to role column in user table""" with engine.connect() as conn: # Check if role column already exists result = conn.execute(text(""" SELECT column_name FROM information_schema.columns WHERE table_name='user' AND column_name='role' """)) if result.fetchone(): print("✅ Column 'role' already exists in user table") # Check if is_admin column still exists result2 = conn.execute(text(""" SELECT column_name FROM information_schema.columns WHERE table_name='user' AND column_name='is_admin' """)) if result2.fetchone(): # Migrate existing admin users conn.execute(text(""" UPDATE "user" SET role = 'ADMIN' WHERE is_admin = true """)) # Set default role for non-admin users conn.execute(text(""" UPDATE "user" SET role = 'USER' WHERE role IS NULL OR role = 'user' """)) # Drop the old is_admin column conn.execute(text(""" ALTER TABLE "user" DROP COLUMN is_admin """)) conn.commit() print("✅ Migrated existing data and dropped is_admin column") else: # Correct any wrong values conn.execute(text(""" UPDATE "user" SET role = 'ADMIN' WHERE role = 'admin' """)) conn.execute(text(""" UPDATE "user" SET role = 'USER' WHERE role = 'user' """)) conn.execute(text(""" UPDATE "user" SET role = 'SUPERADMIN' WHERE role = 'superadmin' """)) conn.commit() print("✅ Corrected role values to enum names") return # Add role column conn.execute(text(""" ALTER TABLE "user" ADD COLUMN role VARCHAR(20) DEFAULT 'USER' """)) # Migrate existing admin users conn.execute(text(""" UPDATE "user" SET role = 'ADMIN' WHERE is_admin = true """)) # Set default role for non-admin users conn.execute(text(""" UPDATE "user" SET role = 'USER' WHERE role IS NULL """)) # Drop the old is_admin column conn.execute(text(""" ALTER TABLE "user" DROP COLUMN is_admin """)) conn.commit() # Commit the changes print("✅ Successfully migrated is_admin to role column") print("✅ Existing admins have been assigned 'admin' role") print("✅ Other users have been assigned 'user' role") if __name__ == "__main__": migrate()