drop_rbac_tables.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/env python3
  2. """
  3. 删除现有的RBAC相关表
  4. """
  5. import pymysql
  6. from dotenv import load_dotenv
  7. import os
  8. load_dotenv()
  9. def get_db_connection():
  10. """获取数据库连接"""
  11. try:
  12. config = {
  13. 'host': os.getenv('DB_HOST', 'localhost'),
  14. 'port': int(os.getenv('DB_PORT', 3306)),
  15. 'user': os.getenv('DB_USER', 'root'),
  16. 'password': os.getenv('DB_PASSWORD', 'admin'),
  17. 'database': os.getenv('DB_NAME', 'lq_db'),
  18. 'charset': 'utf8mb4',
  19. 'autocommit': True
  20. }
  21. return pymysql.connect(**config)
  22. except Exception as e:
  23. print(f"数据库连接失败: {e}")
  24. return None
  25. def drop_rbac_tables():
  26. """删除RBAC相关表"""
  27. print("🗑️ 删除现有RBAC相关表...")
  28. print("=" * 50)
  29. conn = get_db_connection()
  30. if not conn:
  31. print("❌ 数据库连接失败")
  32. return False
  33. cursor = conn.cursor()
  34. try:
  35. # 按依赖关系顺序删除表
  36. tables_to_drop = [
  37. 'user_roles',
  38. 'role_permissions',
  39. 'role_menus',
  40. 'permissions',
  41. 'roles',
  42. 'menus'
  43. ]
  44. for table in tables_to_drop:
  45. try:
  46. cursor.execute(f"DROP TABLE IF EXISTS {table}")
  47. print(f" ✅ 删除表: {table}")
  48. except Exception as e:
  49. print(f" ⚠️ 删除表 {table} 失败: {e}")
  50. conn.commit()
  51. cursor.close()
  52. conn.close()
  53. print("\n✅ RBAC表删除完成")
  54. return True
  55. except Exception as e:
  56. print(f"❌ 删除表失败: {e}")
  57. cursor.close()
  58. conn.close()
  59. return False
  60. if __name__ == "__main__":
  61. drop_rbac_tables()