Skip to content

Commit 4454eda

Browse files
authored
Merge pull request #1 from rahulapjs/patch
Patch
2 parents 34cd2a1 + f0f708a commit 4454eda

6 files changed

Lines changed: 81 additions & 15 deletions

File tree

backend/app/api/query.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,8 @@ def query_sql(payload: SQLQueryRequest):
2929

3030
except ValueError as exc:
3131
raise HTTPException(status_code=400, detail=str(exc))
32-
except Exception:
32+
except Exception as exc:
33+
print(exc)
3334
raise HTTPException(
3435
status_code=500,
3536
detail="Failed to process SQL query"

backend/app/api/schema.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
from fastapi import APIRouter
2+
from app.services.schema_loader import load_database_schema
3+
4+
router = APIRouter(tags=["Schema"])
5+
6+
7+
@router.get("/schema")
8+
def get_schema():
9+
schema = load_database_schema()
10+
return {"tables": schema}

backend/app/api/schema_create.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from fastapi import APIRouter, HTTPException
2+
from app.services.schema_creator import create_table
3+
4+
router = APIRouter(tags=["Schema"])
5+
6+
7+
@router.post("/schema/create")
8+
def create_schema(payload: dict):
9+
try:
10+
create_table(payload["table_name"], payload["columns"])
11+
return {"status": "table created"}
12+
except Exception as e:
13+
raise HTTPException(status_code=400, detail=str(e))
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import psycopg2
2+
from app.core.config import settings
3+
4+
ALLOWED_TYPES = {
5+
"text": "TEXT",
6+
"int": "INTEGER",
7+
"float": "REAL",
8+
"timestamp": "TIMESTAMP",
9+
}
10+
11+
12+
def create_table(table_name: str, columns: list[dict]):
13+
cols_sql = []
14+
15+
for col in columns:
16+
if col["type"] not in ALLOWED_TYPES:
17+
raise ValueError(f"Unsupported column type: {col['type']}")
18+
19+
cols_sql.append(
20+
f"{col['name']} {ALLOWED_TYPES[col['type']]}"
21+
)
22+
23+
sql = f"""
24+
CREATE TABLE IF NOT EXISTS {table_name} (
25+
id SERIAL PRIMARY KEY,
26+
{", ".join(cols_sql)}
27+
);
28+
"""
29+
30+
conn = psycopg2.connect(
31+
host=settings.DB_HOST,
32+
port=settings.DB_PORT,
33+
dbname=settings.DB_NAME,
34+
user=settings.DB_USER,
35+
password=settings.DB_PASSWORD,
36+
)
37+
38+
try:
39+
with conn.cursor() as cursor:
40+
cursor.execute(sql)
41+
conn.commit()
42+
finally:
43+
conn.close()

backend/app/services/sql_generator.py

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,9 @@ def generate_sql(question: str) -> Dict[str, Any]:
2121
schema = load_database_schema()
2222
formatted_schema = format_schema_for_prompt(schema)
2323

24-
system_prompt = f"""
24+
# We move the "Expert" rules to the system_instruction parameter
25+
system_instruction = f"""
2526
You are an expert SQL assistant.
26-
2727
You are given a PostgreSQL database schema.
2828
Your task is to generate a SINGLE, READ-ONLY SQL query
2929
that answers the user's question.
@@ -46,18 +46,12 @@ def generate_sql(question: str) -> Dict[str, Any]:
4646
}}
4747
"""
4848

49+
# Corrected method call for the google-genai SDK
4950
response = client.models.generate_content(
5051
model=settings.GEMINI_MODEL,
51-
contents=[
52-
types.Content(
53-
role="user",
54-
parts=[
55-
types.Part(text=system_prompt),
56-
types.Part(text=f"\nUSER QUESTION:\n{question}")
57-
]
58-
)
59-
],
60-
generation_config=types.GenerationConfig(
52+
contents=f"USER QUESTION: {question}",
53+
config=types.GenerateContentConfig(
54+
system_instruction=system_instruction,
6155
temperature=0.1,
6256
response_mime_type="application/json"
6357
)
@@ -68,9 +62,9 @@ def generate_sql(question: str) -> Dict[str, Any]:
6862
try:
6963
data = json.loads(raw_text)
7064
except json.JSONDecodeError as exc:
71-
raise ValueError("Gemini returned invalid JSON") from exc
65+
raise ValueError(f"Gemini returned invalid JSON: {raw_text}") from exc
7266

7367
if "sql" not in data or "explanation" not in data:
7468
raise ValueError("Gemini response missing required fields")
7569

76-
return data
70+
return data

backend/main.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
from fastapi.middleware.cors import CORSMiddleware
33

44
from app.api.query import router as query_router
5+
from app.api.schema import router as schema_router
6+
from app.api.schema_create import router as schema_create_router
57
from app.core.config import settings
68

79
app = FastAPI(
@@ -20,7 +22,10 @@
2022
)
2123

2224
# Routes
25+
26+
app.include_router(schema_router, prefix="/api")
2327
app.include_router(query_router, prefix="/api")
28+
app.include_router(schema_create_router, prefix="/api")
2429

2530

2631
@app.get("/health")

0 commit comments

Comments
 (0)