36 lines
1.3 KiB
Python
36 lines
1.3 KiB
Python
from fastapi import FastAPI, HTTPException
|
|
from fastapi.responses import JSONResponse
|
|
from fastapi.encoders import jsonable_encoder
|
|
from app.schemas import QueryPayload, ExecutePayload
|
|
from app.db import get_engine, run_query, run_execute
|
|
|
|
app = FastAPI(title="MSSQL ODBC Service", version="1.1.0")
|
|
|
|
def _trim_strings(obj):
|
|
if isinstance(obj, str):
|
|
return obj.strip()
|
|
if isinstance(obj, list):
|
|
return [_trim_strings(x) for x in obj]
|
|
if isinstance(obj, dict):
|
|
return {k: _trim_strings(v) for k, v in obj.items()}
|
|
return obj
|
|
|
|
@app.post("/query")
|
|
async def query(payload: QueryPayload):
|
|
try:
|
|
engine = get_engine(payload)
|
|
result = await run_query(engine, payload.sql, payload.params, payload.max_rows)
|
|
result = _trim_strings(result)
|
|
return JSONResponse(content=jsonable_encoder(result))
|
|
except Exception as e:
|
|
raise HTTPException(status_code=400, detail=str(e))
|
|
|
|
@app.post("/execute")
|
|
async def execute(payload: ExecutePayload):
|
|
try:
|
|
engine = get_engine(payload)
|
|
result = await run_execute(engine, payload.sql, payload.params, payload.autocommit)
|
|
result = _trim_strings(result)
|
|
return JSONResponse(content=jsonable_encoder(result))
|
|
except Exception as e:
|
|
raise HTTPException(status_code=400, detail=str(e)) |