VeuReu commited on
Commit
80b4f73
·
verified ·
1 Parent(s): 77a5d4e

Update storage/db_routers.py

Browse files
Files changed (1) hide show
  1. storage/db_routers.py +133 -94
storage/db_routers.py CHANGED
@@ -1,95 +1,134 @@
1
- import os
2
-
3
- import sqlite3
4
-
5
- from pathlib import Path
6
-
7
- from fastapi import APIRouter, UploadFile, File, Query, HTTPException
8
- from fastapi.responses import JSONResponse
9
-
10
- from storage.common import validate_token
11
-
12
- router = APIRouter(prefix="/db", tags=["Database Manager"])
13
- HF_TOKEN = os.getenv("HF_TOKEN")
14
- DB_PATH = Path("/data/db")
15
-
16
- @router.post("/upload_db_file", tags=["Database Manager"])
17
- async def upload_db_file(
18
- file: UploadFile = File(...),
19
- token: str = Query(..., description="Token required for authorization")
20
- ):
21
- """
22
- Upload a file to the /data/db folder.
23
-
24
- Steps:
25
- - Validate the token.
26
- - Ensure /data/db exists (create it if missing).
27
- - Save the uploaded file inside /data/db using its original filename.
28
- - Return a JSON response confirming the upload.
29
- """
30
- validate_token(token)
31
-
32
- # Crear carpeta /data/db si no existe
33
- DB_PATH.mkdir(parents=True, exist_ok=True)
34
-
35
- final_path = DB_PATH / file.filename
36
-
37
- try:
38
- # Leer contenido en memoria y guardar
39
- file_bytes = await file.read()
40
- with open(final_path, "wb") as f:
41
- f.write(file_bytes)
42
- except Exception as exc:
43
- raise HTTPException(status_code=500, detail=f"Failed to save file: {exc}")
44
-
45
- return JSONResponse(
46
- status_code=200,
47
- content={
48
- "status": "ok",
49
- "saved_to": str(final_path)
50
- }
51
- )
52
-
53
- @router.post("/execute_query", tags=["Database Manager"])
54
- async def execute_query(
55
- db_filename: str = Query(..., description="SQLite .db file name"),
56
- query: str = Query(..., description="SQL query to execute"),
57
- token: str = Query(..., description="Token required for authorization")
58
- ):
59
- """
60
- Execute a SQL query against a specified SQLite database file in /data/db.
61
-
62
- Steps:
63
- - Validate the token.
64
- - Ensure the requested .db file exists inside /data/db.
65
- - Connect to the database using sqlite3.
66
- - Execute the provided query.
67
- - Return the results as a list of dictionaries (column: value).
68
- - Capture and return errors if query execution fails.
69
- """
70
- validate_token(token)
71
-
72
- db_file_path = DB_PATH / db_filename
73
-
74
- if not db_file_path.exists() or not db_file_path.is_file():
75
- raise HTTPException(status_code=404, detail=f"Database file {db_filename} not found")
76
-
77
- try:
78
- conn = sqlite3.connect(db_file_path)
79
- conn.row_factory = sqlite3.Row # para devolver columnas por nombre
80
- cur = conn.cursor()
81
-
82
- cur.execute(query)
83
- rows = cur.fetchall()
84
-
85
- # Convert rows to list of dicts
86
- results = [dict(row) for row in rows]
87
-
88
- conn.commit()
89
- conn.close()
90
- except sqlite3.Error as e:
91
- raise HTTPException(status_code=400, detail=f"SQL error: {e}")
92
- except Exception as e:
93
- raise HTTPException(status_code=500, detail=f"Unexpected error: {e}")
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})