1
1
# -*- coding: utf-8 -*-
2
2
import os
3
3
import time
4
+ import uuid
4
5
5
6
import pymysql
6
7
import json
@@ -42,26 +43,59 @@ def _insert(self, data: List):
42
43
answer_type = 0
43
44
embedding_data = embedding_data .tobytes ()
44
45
is_deleted = 0
46
+ _id = str (uuid .uuid4 ())
45
47
46
48
table_name = "modelcache_llm_answer"
47
- insert_sql = "INSERT INTO {} (question, answer, answer_type, model, embedding_data, is_deleted) VALUES (%s, %s, %s, %s, _binary%s, %s)" .format (table_name )
49
+ insert_sql = f"""
50
+ INSERT INTO { table_name }
51
+ (id, question, answer, answer_type, model, embedding_data, is_deleted)
52
+ VALUES (%s, %s, %s, %s, %s, _binary%s, %s)
53
+ """
48
54
conn = self .pool .connection ()
49
55
try :
50
56
with conn .cursor () as cursor :
51
57
# 执行插入数据操作
52
- values = (question , answer , answer_type , model , embedding_data , is_deleted )
58
+ values = (_id , question , answer , answer_type , model , embedding_data , is_deleted )
53
59
cursor .execute (insert_sql , values )
54
60
conn .commit ()
55
- id = cursor .lastrowid
56
61
finally :
57
62
# 关闭连接,将连接返回给连接池
58
63
conn .close ()
59
- return id
64
+ return _id
60
65
61
- def batch_insert (self , all_data : List [CacheData ]):
66
+ def batch_insert (self , all_data : List [List ]):
67
+ table_name = "modelcache_llm_answer"
68
+ insert_sql = f"""
69
+ INSERT INTO { table_name }
70
+ (id, question, answer, answer_type, model, embedding_data, is_deleted)
71
+ VALUES (%s, %s, %s, %s, %s, %s, %s)
72
+ """
73
+
74
+ values_list = []
62
75
ids = []
76
+
63
77
for data in all_data :
64
- ids .append (self ._insert (data ))
78
+ answer = data [0 ]
79
+ question = data [1 ]
80
+ embedding_data = data [2 ].tobytes ()
81
+ model = data [3 ]
82
+ answer_type = 0
83
+ is_deleted = 0
84
+ _id = str (uuid .uuid4 ())
85
+ ids .append (_id )
86
+
87
+ values_list .append ((
88
+ _id , question , answer , answer_type , model , embedding_data , is_deleted
89
+ ))
90
+
91
+ conn = self .pool .connection ()
92
+ try :
93
+ with conn .cursor () as cursor :
94
+ cursor .executemany (insert_sql , values_list )
95
+ conn .commit ()
96
+ finally :
97
+ conn .close ()
98
+
65
99
return ids
66
100
67
101
def insert_query_resp (self , query_resp , ** kwargs ):
@@ -78,7 +112,11 @@ def insert_query_resp(self, query_resp, **kwargs):
78
112
hit_query = json .dumps (hit_query , ensure_ascii = False )
79
113
80
114
table_name = "modelcache_query_log"
81
- insert_sql = "INSERT INTO {} (error_code, error_desc, cache_hit, model, query, delta_time, hit_query, answer) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)" .format (table_name )
115
+ insert_sql = f"""
116
+ INSERT INTO { table_name }
117
+ (error_code, error_desc, cache_hit, model, query, delta_time, hit_query, answer)
118
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
119
+ """
82
120
conn = self .pool .connection ()
83
121
try :
84
122
with conn .cursor () as cursor :
@@ -92,15 +130,16 @@ def insert_query_resp(self, query_resp, **kwargs):
92
130
93
131
def get_data_by_id (self , key : int ):
94
132
table_name = "modelcache_llm_answer"
95
- query_sql = "select question, answer, embedding_data, model from {} where id={}" .format (table_name , key )
96
- conn_start = time .time ()
133
+ query_sql = f"""
134
+ SELECT question, answer, embedding_data, model
135
+ FROM { table_name }
136
+ WHERE id = %s
137
+ """
97
138
conn = self .pool .connection ()
98
-
99
- search_start = time .time ()
100
139
try :
101
140
with conn .cursor () as cursor :
102
141
# 执行数据库操作
103
- cursor .execute (query_sql )
142
+ cursor .execute (query_sql , ( key ,) )
104
143
resp = cursor .fetchone ()
105
144
finally :
106
145
# 关闭连接,将连接返回给连接池
@@ -113,14 +152,18 @@ def get_data_by_id(self, key: int):
113
152
114
153
def update_hit_count_by_id (self , primary_id : int ):
115
154
table_name = "modelcache_llm_answer"
116
- update_sql = "UPDATE {} SET hit_count = hit_count+1 WHERE id={}" .format (table_name , primary_id )
155
+ update_sql = f"""
156
+ UPDATE { table_name }
157
+ SET hit_count = hit_count+1
158
+ WHERE id = %s
159
+ """
117
160
conn = self .pool .connection ()
118
161
119
162
# 使用连接执行更新数据操作
120
163
try :
121
164
with conn .cursor () as cursor :
122
165
# 执行更新数据操作
123
- cursor .execute (update_sql )
166
+ cursor .execute (update_sql ,( primary_id ,) )
124
167
conn .commit ()
125
168
finally :
126
169
# 关闭连接,将连接返回给连接池
@@ -129,12 +172,16 @@ def update_hit_count_by_id(self, primary_id: int):
129
172
def get_ids (self , deleted = True ):
130
173
table_name = "modelcache_llm_answer"
131
174
state = 1 if deleted else 0
132
- query_sql = "Select id FROM {} WHERE is_deleted = {}" .format (table_name , state )
175
+ query_sql = f"""
176
+ SELECT id
177
+ FROM { table_name }
178
+ WHERE is_deleted = %s
179
+ """
133
180
134
181
conn = self .pool .connection ()
135
182
try :
136
183
with conn .cursor () as cursor :
137
- cursor .execute (query_sql )
184
+ cursor .execute (query_sql , ( state ,) )
138
185
ids = [row [0 ] for row in cursor .fetchall ()]
139
186
finally :
140
187
conn .close ()
@@ -143,37 +190,45 @@ def get_ids(self, deleted=True):
143
190
144
191
def mark_deleted (self , keys ):
145
192
table_name = "modelcache_llm_answer"
146
- mark_sql = " update {} set is_deleted=1 WHERE id in ({})" .format (table_name , "," .join ([str (i ) for i in keys ]))
193
+ placeholders = "," .join (["%s" ] * len (keys ))
194
+ mark_sql = f"""
195
+ UPDATE { table_name }
196
+ SET is_deleted=1
197
+ WHERE id in ({ placeholders } )
198
+ """
147
199
148
- # 从连接池中获取连接
149
200
conn = self .pool .connection ()
150
201
try :
151
202
with conn .cursor () as cursor :
152
- # 执行删除数据操作
153
- cursor .execute (mark_sql )
203
+ cursor .execute (mark_sql , keys )
154
204
delete_count = cursor .rowcount
155
205
conn .commit ()
156
206
finally :
157
- # 关闭连接,将连接返回给连接池
158
207
conn .close ()
159
208
return delete_count
160
209
161
210
def model_deleted (self , model_name ):
162
211
table_name = "modelcache_llm_answer"
163
- delete_sql = "Delete from {} WHERE model='{}'" .format (table_name , model_name )
212
+ delete_sql = f"""
213
+ Delete from { table_name }
214
+ WHERE model = %s
215
+ """
164
216
165
217
table_log_name = "modelcache_query_log"
166
- delete_log_sql = "Delete from {} WHERE model='{}'" .format (table_log_name , model_name )
218
+ delete_log_sql = f"""
219
+ Delete from { table_log_name }
220
+ WHERE model = %s
221
+ """
167
222
168
223
conn = self .pool .connection ()
169
224
# 使用连接执行删除数据操作
170
225
try :
171
226
with conn .cursor () as cursor :
172
227
# 执行删除数据操作
173
- resp = cursor .execute (delete_sql )
228
+ resp = cursor .execute (delete_sql , ( model_name ,) )
174
229
conn .commit ()
175
230
# 执行删除该模型对应日志操作 resp_log行数不返回
176
- resp_log = cursor .execute (delete_log_sql )
231
+ resp_log = cursor .execute (delete_log_sql , ( model_name ,))
177
232
conn .commit () # 分别提交事务
178
233
finally :
179
234
# 关闭连接,将连接返回给连接池
@@ -182,7 +237,10 @@ def model_deleted(self, model_name):
182
237
183
238
def clear_deleted_data (self ):
184
239
table_name = "modelcache_llm_answer"
185
- delete_sql = "DELETE FROM {} WHERE is_deleted = 1" .format (table_name )
240
+ delete_sql = f"""
241
+ DELETE FROM { table_name }
242
+ WHERE is_deleted = 1
243
+ """
186
244
187
245
conn = self .pool .connection ()
188
246
try :
@@ -197,10 +255,15 @@ def clear_deleted_data(self):
197
255
198
256
def count (self , state : int = 0 , is_all : bool = False ):
199
257
table_name = "modelcache_llm_answer"
258
+
259
+ # we're not using prepared statements here, so we need to ensure state is an integer
260
+ if not isinstance (state , int ):
261
+ raise ValueError ("'state' must be an integer." )
262
+
200
263
if is_all :
201
- count_sql = "SELECT COUNT(*) FROM {}" . format ( table_name )
264
+ count_sql = f "SELECT COUNT(*) FROM { table_name } "
202
265
else :
203
- count_sql = "SELECT COUNT(*) FROM {} WHERE is_deleted = {}" . format ( table_name , state )
266
+ count_sql = f "SELECT COUNT(*) FROM { table_name } WHERE is_deleted = { state } "
204
267
205
268
conn = self .pool .connection ()
206
269
try :
0 commit comments