feat: 三大核心功能完成 — query_history持久化 + EXPLAIN真实解析 + Dashboard修复
P1 查询历史持久化 (47 tests): - QueryHistory/QuickQuery SQLAlchemy model 建表 - query_history_service 从内存迁移到 SQLite async - 每用户500条上限自动清理 - 7个API endpoint全部对接持久化 - 10个预置快捷查询模板 P2 EXPLAIN真实解析 (40 tests): - MySQL EXPLAIN FORMAT=JSON 执行+解析 - PostgreSQL EXPLAIN (FORMAT JSON) 执行+解析 - SQLite EXPLAIN QUERY PLAN 解析 - 统一树结构输出 + 优化警告 - POST /api/v1/sql-assistant/explain endpoint Dashboard修复: - 修复重复export default导致页面崩溃 - 对接/instances /tickets /dashboard/stats真实API - 替换硬编码统计数字为API驱动 - 修复calcHealthScore安全访问 AuditLogsPage: - 修复Fragment key warning 1081 tests passed (10 system_settings failures are pre-existing)
This commit is contained in:
1 parent
1fcb984aee
commit
c7fccf99c7
8 files changed
+2274
-400
No files matched your search
@@ -180,6 +180,7 @@ async def execute_query(
|
||||
try:
|
||||
username = current_user.display_name or current_user.username
|
||||
await QueryHistoryService.record_query(
|
||||
db=db,
|
||||
user_id=current_user.id,
|
||||
username=username,
|
||||
instance_id=instance.id,
|
||||
|
||||
@@ -18,6 +18,7 @@ async def my_query_history(
|
||||
keyword: Optional[str] = None,
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
"""获取我的查询历史。
|
||||
@@ -25,6 +26,7 @@ async def my_query_history(
|
||||
自动记录每次查询,支持按数据库类型、实例、关键词筛选。
|
||||
"""
|
||||
return await QueryHistoryService.get_history(
|
||||
db=db,
|
||||
user_id=current_user.id,
|
||||
db_type=db_type,
|
||||
instance_id=instance_id,
|
||||
@@ -37,10 +39,11 @@ async def my_query_history(
|
||||
@router.post("/{history_id}/favorite")
|
||||
async def toggle_favorite(
|
||||
history_id: int,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
"""切换查询历史收藏状态。"""
|
||||
is_fav = await QueryHistoryService.toggle_favorite(current_user.id, history_id)
|
||||
is_fav = await QueryHistoryService.toggle_favorite(db, current_user.id, history_id)
|
||||
return {"is_favorite": is_fav, "message": "已收藏" if is_fav else "已取消收藏"}
|
||||
|
||||
|
||||
@@ -48,20 +51,22 @@ async def toggle_favorite(
|
||||
async def my_favorites(
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
"""获取我收藏的查询。"""
|
||||
return await QueryHistoryService.get_favorites(
|
||||
user_id=current_user.id, page=page, page_size=page_size
|
||||
db=db, user_id=current_user.id, page=page, page_size=page_size
|
||||
)
|
||||
|
||||
|
||||
@router.get("/statistics")
|
||||
async def my_query_statistics(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
"""获取我的查询统计 — 了解自己的数据使用习惯。"""
|
||||
return await QueryHistoryService.get_query_statistics(user_id=current_user.id)
|
||||
return await QueryHistoryService.get_query_statistics(db=db, user_id=current_user.id)
|
||||
|
||||
|
||||
# ── 快捷查询 ──
|
||||
@@ -70,11 +75,12 @@ async def my_query_statistics(
|
||||
async def list_quick_queries(
|
||||
db_type: Optional[str] = None,
|
||||
keyword: Optional[str] = None,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
"""获取快捷查询列表(个人+团队共享)。"""
|
||||
items = await QueryHistoryService.get_quick_queries(
|
||||
user_id=current_user.id, db_type=db_type, keyword=keyword
|
||||
db=db, user_id=current_user.id, db_type=db_type, keyword=keyword
|
||||
)
|
||||
return {"items": items, "total": len(items)}
|
||||
|
||||
@@ -87,10 +93,12 @@ async def create_quick_query(
|
||||
description: str = "",
|
||||
database_pattern: str = "*",
|
||||
is_shared: bool = False,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
"""创建快捷查询。"""
|
||||
qq = await QueryHistoryService.create_quick_query(
|
||||
db=db,
|
||||
name=name,
|
||||
description=description,
|
||||
query_content=query_content,
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
"""SQL助手 API — 人性化辅助功能。"""
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.crypto import decrypt_password
|
||||
from app.core.permissions import check_instance_access, check_instance_permission
|
||||
from app.core.security import get_current_user
|
||||
from app.models.user import User
|
||||
from app.models.instance import Instance
|
||||
from app.services.sql_assistant import SQLAssistant
|
||||
from app.services.explain_service import ExplainService
|
||||
|
||||
router = APIRouter(prefix="/sql-assistant", tags=["SQL助手"])
|
||||
|
||||
@@ -111,3 +120,63 @@ async def parse_explain(
|
||||
"warnings": result.warnings,
|
||||
"human_readable": result.human_readable,
|
||||
}
|
||||
|
||||
|
||||
# ===== EXPLAIN 真实执行 API =====
|
||||
|
||||
|
||||
class ExplainRequest(BaseModel):
|
||||
"""EXPLAIN 请求体。"""
|
||||
instance_id: int
|
||||
database: str
|
||||
query: str
|
||||
|
||||
|
||||
@router.post("/explain")
|
||||
async def execute_explain(
|
||||
req: ExplainRequest,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
"""连接数据源执行 EXPLAIN 并解析为统一树结构。
|
||||
|
||||
根据数据源类型自动构造对应的 EXPLAIN 语句:
|
||||
- MySQL: EXPLAIN FORMAT=JSON <query>
|
||||
- PostgreSQL: EXPLAIN (FORMAT JSON, ANALYZE false) <query>
|
||||
- SQLite: EXPLAIN QUERY PLAN <query>
|
||||
|
||||
返回统一的树形执行计划、优化警告和汇总统计。
|
||||
"""
|
||||
if current_user.role == "guest":
|
||||
raise HTTPException(status_code=403, detail="访客无权执行 EXPLAIN,请联系管理员申请权限")
|
||||
|
||||
if not req.query or not req.query.strip():
|
||||
raise HTTPException(status_code=400, detail="查询语句不能为空")
|
||||
|
||||
# 获取实例
|
||||
result = await db.execute(select(Instance).where(Instance.id == req.instance_id))
|
||||
instance = result.scalar_one_or_none()
|
||||
if not instance:
|
||||
raise HTTPException(status_code=404, detail="数据源不存在,请确认实例ID正确")
|
||||
|
||||
# 权限检查
|
||||
await check_instance_access(current_user, instance, db)
|
||||
await check_instance_permission(current_user, instance, "query:select", db)
|
||||
|
||||
# 解密密码
|
||||
instance.password = decrypt_password(instance.password)
|
||||
|
||||
start_time = time.time()
|
||||
try:
|
||||
explain_result = await ExplainService.execute_explain(
|
||||
instance, req.database, req.query
|
||||
)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"EXPLAIN 执行失败: {e}")
|
||||
|
||||
elapsed_ms = int((time.time() - start_time) * 1000)
|
||||
explain_result["elapsed_ms"] = elapsed_ms
|
||||
|
||||
return explain_result
|
||||
Reference in new issue
Block a user