11import json
22import time
33import traceback
4- from concurrent .futures import ThreadPoolExecutor
54from typing import List
65
76from sqlalchemy import and_ , select , update
8- from sqlalchemy .orm import sessionmaker
9- from sqlalchemy .orm .session import Session
107
118from apps .ai_model .embedding import EmbeddingModelCache
129from common .core .config import settings
1310from common .core .deps import SessionDep
1411from common .utils .utils import SQLBotLogUtil
1512from ..models .datasource import CoreTable , CoreField
1613
17- executor = ThreadPoolExecutor (max_workers = 200 )
18-
19- from common .core .db import engine
20-
21- session_maker = sessionmaker (bind = engine )
22- session = session_maker ()
23-
2414
2515def delete_table_by_ds_id (session : SessionDep , id : int ):
2616 session .query (CoreTable ).filter (CoreTable .ds_id == id ).delete (synchronize_session = False )
@@ -40,22 +30,25 @@ def update_table(session: SessionDep, item: CoreTable):
4030 session .commit ()
4131
4232
43- def run_fill_empty_table_embedding (session : Session ):
33+ def run_fill_empty_table_embedding (session_maker ):
4434 try :
4535 if not settings .TABLE_EMBEDDING_ENABLED :
4636 return
4737
4838 SQLBotLogUtil .info ('get tables' )
39+ session = session_maker ()
4940 stmt = select (CoreTable .id ).where (and_ (CoreTable .embedding .is_ (None )))
5041 results = session .execute (stmt ).scalars ().all ()
5142 SQLBotLogUtil .info ('result: ' + str (len (results )))
5243
5344 save_table_embedding (session , results )
5445 except Exception :
5546 traceback .print_exc ()
47+ finally :
48+ session_maker .remove ()
5649
5750
58- def save_table_embedding (session : Session , ids : List [int ]):
51+ def save_table_embedding (session_maker , ids : List [int ]):
5952 if not settings .TABLE_EMBEDDING_ENABLED :
6053 return
6154
@@ -65,6 +58,7 @@ def save_table_embedding(session: Session, ids: List[int]):
6558 SQLBotLogUtil .info ('start table embedding' )
6659 start_time = time .time ()
6760 model = EmbeddingModelCache .get_model ()
61+ session = session_maker ()
6862 for _id in ids :
6963 table = session .query (CoreTable ).filter (CoreTable .id == _id ).first ()
7064 fields = session .query (CoreField ).filter (CoreField .table_id == table .id ).all ()
@@ -102,14 +96,5 @@ def save_table_embedding(session: Session, ids: List[int]):
10296 SQLBotLogUtil .info ('table embedding finished in: ' + str (end_time - start_time ) + ' seconds' )
10397 except Exception :
10498 traceback .print_exc ()
105-
106-
107- def run_save_table_embeddings (ids : List [int ]):
108- executor .submit (save_table_embedding , session , ids )
109-
110-
111- def fill_empty_table_embeddings ():
112- try :
113- executor .submit (run_fill_empty_table_embedding , session )
114- except Exception :
115- traceback .print_exc ()
99+ finally :
100+ session_maker .remove ()
0 commit comments