| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- """
- 数据库迁移脚本:创建 user_intimacy 表(用户亲密度 0-3 颗心)
- 运行: 在 backend 目录下执行 python migrations/migrate_add_user_intimacy_table.py
- 或在项目根目录执行 python backend/migrations/migrate_add_user_intimacy_table.py
- """
- import asyncio
- import sys
- from pathlib import Path
- from typing import Any
- # 将 backend 加入 path,支持从项目根或 backend 目录运行
- _backend = Path(__file__).resolve().parent.parent
- if str(_backend) not in sys.path:
- sys.path.insert(0, str(_backend))
- import aiomysql
- from config import settings
- async def migrate_create_user_intimacy_table() -> bool:
- """创建 user_intimacy 表(如果不存在)"""
- try:
- conn: aiomysql.Connection = await aiomysql.connect(
- host=settings.MYSQL_HOST,
- port=settings.MYSQL_PORT,
- user=settings.MYSQL_USER,
- password=settings.MYSQL_PASSWORD,
- db=settings.MYSQL_DATABASE,
- charset="utf8mb4",
- )
- async with conn.cursor() as cursor:
- await cursor.execute(
- """
- SELECT COUNT(*) FROM information_schema.tables
- WHERE table_schema = %s AND table_name = 'user_intimacy'
- """,
- (settings.MYSQL_DATABASE,),
- )
- exists_row: Any = await cursor.fetchone()
- table_exists = bool(exists_row and exists_row[0] > 0)
- if table_exists:
- print("✅ user_intimacy 表已存在,无需迁移")
- await conn.ensure_closed()
- return True
- print("🔄 创建 user_intimacy 表...")
- await cursor.execute(
- """
- CREATE TABLE user_intimacy (
- id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT '主键',
- user_id VARCHAR(64) NOT NULL COMMENT '用户ID',
- heart_count INT NOT NULL DEFAULT 3 COMMENT '亲密度心数 0-3',
- last_visit_date_at_deduction VARCHAR(10) NULL COMMENT '上次扣心所依据的最后访问日期 YYYY-MM-DD',
- updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
- UNIQUE KEY uk_user_intimacy_user_id (user_id),
- INDEX idx_user_intimacy_user_id (user_id)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户亲密度表';
- """
- )
- await conn.commit()
- print("✅ user_intimacy 表创建完成")
- await conn.ensure_closed()
- return True
- except Exception as exc: # noqa: BLE001
- import traceback
- print(f"❌ 迁移失败: {exc}")
- traceback.print_exc()
- return False
- if __name__ == "__main__":
- if len(sys.argv) > 1 and sys.argv[1] == "--force":
- confirm = "y"
- else:
- confirm = input("\n是否继续创建 user_intimacy 表? (y/n): ")
- if confirm.lower() != "y":
- sys.exit(0)
- ok = asyncio.run(migrate_create_user_intimacy_table())
- if not ok:
- sys.exit(1)
|