File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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 }
Original file line number Diff line number Diff line change 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 ))
Original file line number Diff line number Diff line change 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 ()
Original file line number Diff line number Diff line change 22from fastapi .middleware .cors import CORSMiddleware
33
44from 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
57from app .core .config import settings
68
79app = FastAPI (
2022)
2123
2224# Routes
25+
26+ app .include_router (schema_router , prefix = "/api" )
2327app .include_router (query_router , prefix = "/api" )
28+ app .include_router (schema_create_router , prefix = "/api" )
2429
2530
2631@app .get ("/health" )
You can’t perform that action at this time.
0 commit comments