migrate_add_area_code_to_verification_codes.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. """
  2. 数据库迁移脚本:为 verification_codes 表添加 area_code 字段
  3. 运行: python migrate_add_area_code_to_verification_codes.py
  4. """
  5. import asyncio
  6. import sys
  7. from typing import Any
  8. import aiomysql
  9. from config import settings
  10. async def migrate_add_area_code_field() -> bool:
  11. """为 verification_codes 表添加 area_code 字段"""
  12. try:
  13. conn: aiomysql.Connection = await aiomysql.connect(
  14. host=settings.MYSQL_HOST,
  15. port=settings.MYSQL_PORT,
  16. user=settings.MYSQL_USER,
  17. password=settings.MYSQL_PASSWORD,
  18. db=settings.MYSQL_DATABASE,
  19. charset="utf8mb4",
  20. )
  21. async with conn.cursor() as cursor:
  22. # 检查字段是否已存在
  23. await cursor.execute(
  24. """
  25. SELECT COUNT(*) FROM information_schema.columns
  26. WHERE table_schema = %s
  27. AND table_name = 'verification_codes'
  28. AND column_name = 'area_code'
  29. """,
  30. (settings.MYSQL_DATABASE,),
  31. )
  32. exists_row: Any = await cursor.fetchone()
  33. field_exists = bool(exists_row and exists_row[0] > 0)
  34. if not field_exists:
  35. print("🔄 为 verification_codes 表添加 area_code 字段...")
  36. await cursor.execute(
  37. """
  38. ALTER TABLE verification_codes
  39. ADD COLUMN area_code VARCHAR(10) NULL COMMENT '手机区号(如 +86)'
  40. AFTER code_id
  41. """
  42. )
  43. await conn.commit()
  44. print("✅ area_code 字段添加完成")
  45. else:
  46. print("✅ area_code 字段已存在")
  47. conn.close()
  48. return True
  49. except Exception:
  50. import traceback
  51. traceback.print_exc()
  52. return False
  53. if __name__ == "__main__":
  54. if len(sys.argv) > 1 and sys.argv[1] == "--force":
  55. confirm = "y"
  56. else:
  57. confirm = input("\n是否继续执行迁移? (y/n): ")
  58. if confirm.lower() != "y":
  59. sys.exit(0)
  60. ok = asyncio.run(migrate_add_area_code_field())
  61. if not ok:
  62. sys.exit(1)