Add test connection feature for database targets
This commit introduces a new endpoint to test database connection. The frontend now includes a button to test the connection before creating a target, with real-time feedback on success or failure. Related styles and components were updated for better user experience.
This commit is contained in:
@@ -8,7 +8,7 @@ from app.core.deps import get_current_user, require_roles
|
||||
from app.models.models import Metric, QueryStat, Target, User
|
||||
from app.schemas.metric import MetricOut, QueryStatOut
|
||||
from app.schemas.overview import DatabaseOverviewOut
|
||||
from app.schemas.target import TargetCreate, TargetOut, TargetUpdate
|
||||
from app.schemas.target import TargetConnectionTestRequest, TargetCreate, TargetOut, TargetUpdate
|
||||
from app.services.audit import write_audit_log
|
||||
from app.services.collector import build_target_dsn
|
||||
from app.services.crypto import encrypt_secret
|
||||
@@ -23,6 +23,33 @@ async def list_targets(user: User = Depends(get_current_user), db: AsyncSession
|
||||
return [TargetOut.model_validate(item) for item in targets]
|
||||
|
||||
|
||||
@router.post("/test-connection")
|
||||
async def test_target_connection(
|
||||
payload: TargetConnectionTestRequest,
|
||||
user: User = Depends(require_roles("admin", "operator")),
|
||||
) -> dict:
|
||||
_ = user
|
||||
ssl = False if payload.sslmode == "disable" else True
|
||||
conn = None
|
||||
try:
|
||||
conn = await asyncpg.connect(
|
||||
host=payload.host,
|
||||
port=payload.port,
|
||||
database=payload.dbname,
|
||||
user=payload.username,
|
||||
password=payload.password,
|
||||
ssl=ssl,
|
||||
timeout=8,
|
||||
)
|
||||
version = await conn.fetchval("SHOW server_version")
|
||||
return {"ok": True, "message": "Connection successful", "server_version": version}
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=400, detail=f"Connection failed: {exc}")
|
||||
finally:
|
||||
if conn:
|
||||
await conn.close()
|
||||
|
||||
|
||||
@router.post("", response_model=TargetOut, status_code=status.HTTP_201_CREATED)
|
||||
async def create_target(
|
||||
payload: TargetCreate,
|
||||
|
||||
@@ -16,6 +16,15 @@ class TargetCreate(TargetBase):
|
||||
password: str
|
||||
|
||||
|
||||
class TargetConnectionTestRequest(BaseModel):
|
||||
host: str
|
||||
port: int = 5432
|
||||
dbname: str
|
||||
username: str
|
||||
password: str
|
||||
sslmode: str = "prefer"
|
||||
|
||||
|
||||
class TargetUpdate(BaseModel):
|
||||
name: str | None = None
|
||||
host: str | None = None
|
||||
|
||||
Reference in New Issue
Block a user