Test infrastructure: - conftest.py with SQLite in-memory DB, isolated per-test cleanup - pytest.ini with asyncio auto mode - Fixtures: admin/dba/developer/guest/disabled users, tokens, test instance Test coverage (44 tests): - test_auth: login/logout/me/token expiry (8 tests) - test_users: CRUD + role permissions (8 tests) - test_instances: CRUD + connection test mock (8 tests) - test_tickets: CRUD + review/execute workflow + pagination (11 tests) - test_query: select/drop/delete rejection + guest deny (4 tests) - test_dashboard: stats + auth check (2 tests) Backend fix: - query endpoint now catches ValueError from QueryService → 400 instead of 500 Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
46 lines
1.4 KiB
Python
46 lines
1.4 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="数据源不存在")
|
|
|
|
try:
|
|
query_result = await QueryService.execute_query(instance, req.database, req.sql, current_user.id)
|
|
except ValueError as e:
|
|
raise HTTPException(status_code=400, detail=str(e))
|
|
|
|
# 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
|