| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- """
- 数据库迁移脚本:创建 page_visit_logs 表
- 运行: python migrations/migrate_add_page_visit_logs_table.py
- """
- import asyncio
- import sys
- from typing import Any
- import aiomysql
- from config import settings
- async def migrate_create_page_visit_logs_table() -> bool:
- """创建 page_visit_logs 表(如果不存在)"""
- 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 = 'page_visit_logs'
- """,
- (settings.MYSQL_DATABASE,),
- )
- exists_row: Any = await cursor.fetchone()
- table_exists = bool(exists_row and exists_row[0] > 0)
- if table_exists:
- print("✅ page_visit_logs 表已存在,无需迁移")
- await conn.ensure_closed()
- return True
- print("🔄 创建 page_visit_logs 表...")
- await cursor.execute(
- """
- CREATE TABLE page_visit_logs (
- id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT '主键',
- user_id VARCHAR(64) NULL COMMENT '用户ID(未登录则为空)',
- path VARCHAR(512) NOT NULL COMMENT '访问路径',
- visited_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '访问时间',
- INDEX idx_page_visit_user_id (user_id),
- INDEX idx_page_visit_path (path(255)),
- INDEX idx_page_visit_visited_at (visited_at)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='页面访问日志表';
- """
- )
- await conn.commit()
- print("✅ page_visit_logs 表创建完成")
- 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是否继续创建 page_visit_logs 表? (y/n): ")
- if confirm.lower() != "y":
- sys.exit(0)
- ok = asyncio.run(migrate_create_page_visit_logs_table())
- if not ok:
- sys.exit(1)
|