Skip to content

Commit 2790ef9

Browse files
committed
refactor: add schema api
1 parent e798948 commit 2790ef9

File tree

2 files changed

+52
-5
lines changed

2 files changed

+52
-5
lines changed

backend/apps/datasource/api/datasource.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
from ..crud.field import get_fields_by_table_id
2121
from ..crud.table import get_tables_by_ds_id
2222
from ..models.datasource import CoreDatasource, CreateDatasource, TableObj, CoreTable, CoreField
23+
from apps.db.db import get_schema
2324

2425
router = APIRouter(tags=["datasource"], prefix="/datasource")
2526
path = settings.EXCEL_PATH
@@ -107,6 +108,21 @@ def inner():
107108
raise HTTPException(status_code=500, detail=f'Get table Failed: {e.args}')
108109

109110

111+
@router.post("/getSchemaByConf")
112+
async def get_schema_by_conf(session: SessionDep, trans: Trans, ds: CoreDatasource):
113+
try:
114+
return get_schema(ds)
115+
except Exception as e:
116+
# check ds status
117+
def inner():
118+
return check_status(session, trans, ds, True)
119+
120+
status = await asyncio.to_thread(inner)
121+
if status:
122+
SQLBotLogUtil.error(f"get table failed: {e}")
123+
raise HTTPException(status_code=500, detail=f'Get table Failed: {e.args}')
124+
125+
110126
@router.post("/getFields/{id}/{table_name}")
111127
async def get_fields(session: SessionDep, id: int, table_name: str):
112128
return getFields(session, id, table_name)

backend/apps/db/db.py

Lines changed: 36 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -64,11 +64,16 @@ def get_engine(ds: CoreDatasource, timeout: int = 0) -> Engine:
6464
conf.timeout = timeout
6565
if timeout > 0:
6666
conf.timeout = timeout
67-
if ds.type == "pg" and (conf.dbSchema is not None and conf.dbSchema != ""):
68-
engine = create_engine(get_uri(ds),
69-
connect_args={"options": f"-c search_path={urllib.parse.quote(conf.dbSchema)}",
70-
"connect_timeout": conf.timeout},
71-
pool_timeout=conf.timeout)
67+
if ds.type == "pg":
68+
if conf.dbSchema is not None and conf.dbSchema != "":
69+
engine = create_engine(get_uri(ds),
70+
connect_args={"options": f"-c search_path={urllib.parse.quote(conf.dbSchema)}",
71+
"connect_timeout": conf.timeout},
72+
pool_timeout=conf.timeout)
73+
else:
74+
engine = create_engine(get_uri(ds),
75+
connect_args={"connect_timeout": conf.timeout},
76+
pool_timeout=conf.timeout)
7277
elif ds.type == 'sqlServer':
7378
engine = create_engine(get_uri(ds), pool_timeout=conf.timeout)
7479
elif ds.type == 'oracle':
@@ -86,6 +91,32 @@ def get_session(ds: CoreDatasource | AssistantOutDsSchema):
8691
return session
8792

8893

94+
def get_schema(ds: CoreDatasource):
95+
conf = DatasourceConf(**json.loads(aes_decrypt(ds.configuration))) if ds.type != "excel" else get_engine_config()
96+
db = DB.get_db(ds.type)
97+
if db.connect_type == ConnectType.sqlalchemy:
98+
with get_session(ds) as session:
99+
sql: str = ''
100+
if ds.type == "sqlServer":
101+
sql = f"""select name from sys.schemas"""
102+
elif ds.type == "pg" or ds.type == "excel":
103+
sql = """SELECT nspname FROM pg_namespace"""
104+
elif ds.type == "oracle":
105+
sql = f"""select * from all_users"""
106+
with session.execute(text(sql)) as result:
107+
res = result.fetchall()
108+
res_list = [item[0] for item in res]
109+
return res_list
110+
else:
111+
if ds.type == 'dm':
112+
with dmPython.connect(user=conf.username, password=conf.password, server=conf.host,
113+
port=conf.port) as conn, conn.cursor() as cursor:
114+
cursor.execute(f"""select OBJECT_NAME from dba_objects where object_type='SCH'""")
115+
res = cursor.fetchall()
116+
res_list = [item[0] for item in res]
117+
return res_list
118+
119+
89120
def get_tables(ds: CoreDatasource):
90121
conf = DatasourceConf(**json.loads(aes_decrypt(ds.configuration))) if ds.type != "excel" else get_engine_config()
91122
db = DB.get_db(ds.type)

0 commit comments

Comments
 (0)