FastAPI backend with auth, user, instance, ticket, query, dashboard APIs. React + TypeScript frontend with mock data UI (10 pages). SQLite + async SQLAlchemy, JWT auth, role-based access control. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
43 lines
1.3 KiB
Python
43 lines
1.3 KiB
Python
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.database import get_db
|
|
from app.core.security import get_current_user
|
|
from app.models.user import User
|
|
from app.models.instance import Instance
|
|
from app.models.audit_log import AuditLog
|
|
from app.schemas.query import QueryRequest, QueryResult
|
|
from app.services.query_service import QueryService
|
|
|
|
router = APIRouter(prefix="/query", tags=["SQL 查询"])
|
|
|
|
|
|
@router.post("", response_model=QueryResult)
|
|
async def execute_query(
|
|
req: QueryRequest,
|
|
db: AsyncSession = Depends(get_db),
|
|
current_user: User = Depends(get_current_user),
|
|
):
|
|
if current_user.role == "guest":
|
|
raise HTTPException(status_code=403, 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="数据源不存在")
|
|
|
|
query_result = await QueryService.execute_query(instance, req.database, req.sql, current_user.id)
|
|
|
|
# Record audit log
|
|
log = AuditLog(
|
|
user_id=current_user.id,
|
|
action="QUERY",
|
|
target_type="query",
|
|
target_id=instance.id,
|
|
detail=req.sql[:500],
|
|
)
|
|
db.add(log)
|
|
|
|
return query_result
|