fix_sessions_his.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. """
  2. 修复 sessions_his 表缺失字段的迁移脚本
  3. """
  4. import pymysql
  5. import os
  6. from dotenv import load_dotenv
  7. load_dotenv()
  8. conn = pymysql.connect(
  9. host=os.getenv('DB_HOST', 'localhost'),
  10. port=int(os.getenv('DB_PORT', 3306)),
  11. user=os.getenv('DB_USER', 'root'),
  12. password=os.getenv('DB_PASSWORD', ''),
  13. database=os.getenv('DB_NAME', 'buff'),
  14. charset='utf8mb4'
  15. )
  16. cursor = conn.cursor()
  17. # 添加 his_created_at 字段
  18. sql1 = (
  19. "ALTER TABLE `sessions_his` "
  20. "ADD COLUMN `his_created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '历史记录创建时间', "
  21. "ADD INDEX `idx_his_created_at` (`his_created_at`)"
  22. )
  23. try:
  24. cursor.execute(sql1)
  25. print('Added his_created_at column')
  26. except Exception as e:
  27. if 'Duplicate' in str(e) or 'already exists' in str(e):
  28. print('his_created_at column already exists')
  29. else:
  30. print(f'his_created_at error: {e}')
  31. # 添加 his_operation 字段
  32. sql2 = (
  33. "ALTER TABLE `sessions_his` "
  34. "ADD COLUMN `his_operation` varchar(10) NOT NULL COMMENT '操作类型: INSERT/UPDATE/DELETE/RENEW'"
  35. )
  36. try:
  37. cursor.execute(sql2)
  38. print('Added his_operation column')
  39. except Exception as e:
  40. if 'Duplicate' in str(e) or 'already exists' in str(e):
  41. print('his_operation column already exists')
  42. else:
  43. print(f'his_operation error: {e}')
  44. conn.commit()
  45. cursor.close()
  46. conn.close()
  47. print('Migration completed!')