File size: 2,269 Bytes
89157f5
 
 
 
 
 
 
5a01a63
 
 
 
 
 
89157f5
 
 
 
 
 
55ae875
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89157f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
from __future__ import annotations

from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException, status

from app.core.logger import get_logger
from app.models.schemas import (
    DatabaseQueryRequest,
    DatabaseQueryResponse,
    DatabaseValidateRequest,
    DatabaseValidateResponse,
)
from app.services.database_service import DatabaseService

router = APIRouter()
_logger = get_logger(__name__)


@router.post(
    "/database/validate",
    response_model=DatabaseValidateResponse,
    summary="Validate database connection and optionally check table/collection existence",
)
async def validate_database(
    body: DatabaseValidateRequest,
    db_service: Annotated[DatabaseService, Depends()] = None,
) -> DatabaseValidateResponse:
    if db_service is None:
        db_service = DatabaseService()
    _logger.info("Database validate request: %s", body.connection.safe_repr())
    try:
        return await db_service.validate_connection(body)
    except Exception as exc:
        _logger.error("Unexpected error validating database: %s", exc)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail={"success": False, "message": f"Internal error: {exc}"},
        )


@router.post(
    "/database/query",
    response_model=DatabaseQueryResponse,
    summary="Execute queries against MySQL, PostgreSQL, or MongoDB",
)
async def execute_database_query(
    body: DatabaseQueryRequest,
    db_service: Annotated[DatabaseService, Depends()] = None,
) -> DatabaseQueryResponse:
    if db_service is None:
        db_service = DatabaseService()

    _logger.info(
        "Database query request: type=%s, %s",
        body.db_type,
        body.connection.safe_repr(),
    )

    try:
        return await db_service.execute_query(body)
    except HTTPException:
        raise
    except Exception as exc:
        _logger.error("Unexpected error processing database query: %s", exc)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail={
                "success": False,
                "execution_time_ms": 0,
                "error": {"message": f"Internal error: {exc}", "code": "INTERNAL_ERROR"},
            },
        )