migrate_add_user_intimacy_table.py 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. """
  2. 数据库迁移脚本:创建 user_intimacy 表(用户亲密度 0-3 颗心)
  3. 运行: 在 backend 目录下执行 python migrations/migrate_add_user_intimacy_table.py
  4. 或在项目根目录执行 python backend/migrations/migrate_add_user_intimacy_table.py
  5. """
  6. import asyncio
  7. import sys
  8. from pathlib import Path
  9. from typing import Any
  10. # 将 backend 加入 path,支持从项目根或 backend 目录运行
  11. _backend = Path(__file__).resolve().parent.parent
  12. if str(_backend) not in sys.path:
  13. sys.path.insert(0, str(_backend))
  14. import aiomysql
  15. from config import settings
  16. async def migrate_create_user_intimacy_table() -> bool:
  17. """创建 user_intimacy 表(如果不存在)"""
  18. try:
  19. conn: aiomysql.Connection = await aiomysql.connect(
  20. host=settings.MYSQL_HOST,
  21. port=settings.MYSQL_PORT,
  22. user=settings.MYSQL_USER,
  23. password=settings.MYSQL_PASSWORD,
  24. db=settings.MYSQL_DATABASE,
  25. charset="utf8mb4",
  26. )
  27. async with conn.cursor() as cursor:
  28. await cursor.execute(
  29. """
  30. SELECT COUNT(*) FROM information_schema.tables
  31. WHERE table_schema = %s AND table_name = 'user_intimacy'
  32. """,
  33. (settings.MYSQL_DATABASE,),
  34. )
  35. exists_row: Any = await cursor.fetchone()
  36. table_exists = bool(exists_row and exists_row[0] > 0)
  37. if table_exists:
  38. print("✅ user_intimacy 表已存在,无需迁移")
  39. await conn.ensure_closed()
  40. return True
  41. print("🔄 创建 user_intimacy 表...")
  42. await cursor.execute(
  43. """
  44. CREATE TABLE user_intimacy (
  45. id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT '主键',
  46. user_id VARCHAR(64) NOT NULL COMMENT '用户ID',
  47. heart_count INT NOT NULL DEFAULT 3 COMMENT '亲密度心数 0-3',
  48. last_visit_date_at_deduction VARCHAR(10) NULL COMMENT '上次扣心所依据的最后访问日期 YYYY-MM-DD',
  49. updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  50. UNIQUE KEY uk_user_intimacy_user_id (user_id),
  51. INDEX idx_user_intimacy_user_id (user_id)
  52. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户亲密度表';
  53. """
  54. )
  55. await conn.commit()
  56. print("✅ user_intimacy 表创建完成")
  57. await conn.ensure_closed()
  58. return True
  59. except Exception as exc: # noqa: BLE001
  60. import traceback
  61. print(f"❌ 迁移失败: {exc}")
  62. traceback.print_exc()
  63. return False
  64. if __name__ == "__main__":
  65. if len(sys.argv) > 1 and sys.argv[1] == "--force":
  66. confirm = "y"
  67. else:
  68. confirm = input("\n是否继续创建 user_intimacy 表? (y/n): ")
  69. if confirm.lower() != "y":
  70. sys.exit(0)
  71. ok = asyncio.run(migrate_create_user_intimacy_table())
  72. if not ok:
  73. sys.exit(1)