Update storage/db_routers.py
Browse files- storage/db_routers.py +133 -94
storage/db_routers.py
CHANGED
|
@@ -1,95 +1,134 @@
|
|
| 1 |
-
import os
|
| 2 |
-
|
| 3 |
-
import sqlite3
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
from fastapi
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
token: str = Query(..., description="Token required for authorization")
|
| 20 |
-
):
|
| 21 |
-
"""
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
Steps:
|
| 25 |
-
- Validate the token.
|
| 26 |
-
-
|
| 27 |
-
-
|
| 28 |
-
- Return
|
| 29 |
-
"""
|
| 30 |
-
validate_token(token)
|
| 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 |
-
- Return
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
return JSONResponse(content={"results": results})
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import sqlite3
|
| 4 |
+
import zipfile
|
| 5 |
+
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from fastapi import APIRouter, UploadFile, File, Query, HTTPException
|
| 9 |
+
from fastapi.responses import JSONResponse
|
| 10 |
+
|
| 11 |
+
from storage.common import validate_token
|
| 12 |
+
|
| 13 |
+
router = APIRouter(prefix="/db", tags=["Database Manager"])
|
| 14 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 15 |
+
DB_PATH = Path("/data/db")
|
| 16 |
+
|
| 17 |
+
@router.get("/download_all_db_files", tags=["Database Manager"])
|
| 18 |
+
async def download_all_db_files(
|
| 19 |
+
token: str = Query(..., description="Token required for authorization")
|
| 20 |
+
):
|
| 21 |
+
"""
|
| 22 |
+
Download all .db files from /data/db as a ZIP archive.
|
| 23 |
+
|
| 24 |
+
Steps:
|
| 25 |
+
- Validate the token.
|
| 26 |
+
- Verify that /data/db exists and contains .db files.
|
| 27 |
+
- Create an in-memory ZIP containing all .db files.
|
| 28 |
+
- Return the ZIP as a downloadable file.
|
| 29 |
+
"""
|
| 30 |
+
validate_token(token)
|
| 31 |
+
|
| 32 |
+
if not DB_PATH.exists():
|
| 33 |
+
raise HTTPException(status_code=404, detail="DB folder does not exist")
|
| 34 |
+
|
| 35 |
+
db_files = list(DB_PATH.glob("*.db"))
|
| 36 |
+
if not db_files:
|
| 37 |
+
raise HTTPException(status_code=404, detail="No .db files found")
|
| 38 |
+
|
| 39 |
+
# Crear ZIP en memoria (sin escribir en disco)
|
| 40 |
+
zip_buffer = io.BytesIO()
|
| 41 |
+
|
| 42 |
+
with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zipf:
|
| 43 |
+
for file_path in db_files:
|
| 44 |
+
zipf.write(file_path, arcname=file_path.name)
|
| 45 |
+
|
| 46 |
+
zip_buffer.seek(0)
|
| 47 |
+
|
| 48 |
+
return FileResponse(
|
| 49 |
+
zip_buffer,
|
| 50 |
+
media_type="application/zip",
|
| 51 |
+
filename="db_files.zip"
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@router.post("/upload_db_file", tags=["Database Manager"])
|
| 56 |
+
async def upload_db_file(
|
| 57 |
+
file: UploadFile = File(...),
|
| 58 |
+
token: str = Query(..., description="Token required for authorization")
|
| 59 |
+
):
|
| 60 |
+
"""
|
| 61 |
+
Upload a file to the /data/db folder.
|
| 62 |
+
|
| 63 |
+
Steps:
|
| 64 |
+
- Validate the token.
|
| 65 |
+
- Ensure /data/db exists (create it if missing).
|
| 66 |
+
- Save the uploaded file inside /data/db using its original filename.
|
| 67 |
+
- Return a JSON response confirming the upload.
|
| 68 |
+
"""
|
| 69 |
+
validate_token(token)
|
| 70 |
+
|
| 71 |
+
# Crear carpeta /data/db si no existe
|
| 72 |
+
DB_PATH.mkdir(parents=True, exist_ok=True)
|
| 73 |
+
|
| 74 |
+
final_path = DB_PATH / file.filename
|
| 75 |
+
|
| 76 |
+
try:
|
| 77 |
+
# Leer contenido en memoria y guardar
|
| 78 |
+
file_bytes = await file.read()
|
| 79 |
+
with open(final_path, "wb") as f:
|
| 80 |
+
f.write(file_bytes)
|
| 81 |
+
except Exception as exc:
|
| 82 |
+
raise HTTPException(status_code=500, detail=f"Failed to save file: {exc}")
|
| 83 |
+
|
| 84 |
+
return JSONResponse(
|
| 85 |
+
status_code=200,
|
| 86 |
+
content={
|
| 87 |
+
"status": "ok",
|
| 88 |
+
"saved_to": str(final_path)
|
| 89 |
+
}
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
@router.post("/execute_query", tags=["Database Manager"])
|
| 93 |
+
async def execute_query(
|
| 94 |
+
db_filename: str = Query(..., description="SQLite .db file name"),
|
| 95 |
+
query: str = Query(..., description="SQL query to execute"),
|
| 96 |
+
token: str = Query(..., description="Token required for authorization")
|
| 97 |
+
):
|
| 98 |
+
"""
|
| 99 |
+
Execute a SQL query against a specified SQLite database file in /data/db.
|
| 100 |
+
|
| 101 |
+
Steps:
|
| 102 |
+
- Validate the token.
|
| 103 |
+
- Ensure the requested .db file exists inside /data/db.
|
| 104 |
+
- Connect to the database using sqlite3.
|
| 105 |
+
- Execute the provided query.
|
| 106 |
+
- Return the results as a list of dictionaries (column: value).
|
| 107 |
+
- Capture and return errors if query execution fails.
|
| 108 |
+
"""
|
| 109 |
+
validate_token(token)
|
| 110 |
+
|
| 111 |
+
db_file_path = DB_PATH / db_filename
|
| 112 |
+
|
| 113 |
+
if not db_file_path.exists() or not db_file_path.is_file():
|
| 114 |
+
raise HTTPException(status_code=404, detail=f"Database file {db_filename} not found")
|
| 115 |
+
|
| 116 |
+
try:
|
| 117 |
+
conn = sqlite3.connect(db_file_path)
|
| 118 |
+
conn.row_factory = sqlite3.Row # para devolver columnas por nombre
|
| 119 |
+
cur = conn.cursor()
|
| 120 |
+
|
| 121 |
+
cur.execute(query)
|
| 122 |
+
rows = cur.fetchall()
|
| 123 |
+
|
| 124 |
+
# Convert rows to list of dicts
|
| 125 |
+
results = [dict(row) for row in rows]
|
| 126 |
+
|
| 127 |
+
conn.commit()
|
| 128 |
+
conn.close()
|
| 129 |
+
except sqlite3.Error as e:
|
| 130 |
+
raise HTTPException(status_code=400, detail=f"SQL error: {e}")
|
| 131 |
+
except Exception as e:
|
| 132 |
+
raise HTTPException(status_code=500, detail=f"Unexpected error: {e}")
|
| 133 |
+
|
| 134 |
return JSONResponse(content={"results": results})
|