千问开源大模型
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

337 lines
10 KiB

  1. # coding:utf8
  2. import os, sys
  3. cur_dir = os.path.dirname(os.path.abspath(__file__)) or os.getcwd()
  4. par_dir = os.path.abspath(os.path.join(cur_dir, os.path.pardir))
  5. sys.path.append(cur_dir)
  6. sys.path.append(par_dir)
  7. import json
  8. import re
  9. # from log_util.set_logger import set_logger
  10. # logging = set_logger('logs/error.log')
  11. import pymysql.cursors
  12. import traceback
  13. def mysqlConn(data,logging):
  14. res={"successCode":"1","errorLog":"","results":""}
  15. p_host=data["Host"]
  16. p_port=int(data["Port"])
  17. p_db=data["Database"]
  18. p_user=data["User"]
  19. p_password=data["Password"]
  20. try:
  21. db = pymysql.connect(host=p_host, user=p_user, passwd=p_password, db=p_db, port=p_port,
  22. charset='utf8', cursorclass=pymysql.cursors.DictCursor)
  23. db.ping(reconnect=True)
  24. cursor = db.cursor()
  25. sql = "SHOW TABLES"
  26. cursor.execute(sql)
  27. tables = cursor.fetchall()
  28. if tables:
  29. table_names = list(map(lambda x: list(x.values())[0], tables))
  30. res["results"] = table_names
  31. else:
  32. res["successCode"] = "0"
  33. cursor.close()
  34. db.close()
  35. return res
  36. except:
  37. res["successCode"] = "0"
  38. res["errorLog"]=traceback.format_exc()
  39. logging.error(traceback.format_exc())
  40. return res
  41. def getTableColumnNames(data,logging):
  42. res={"successCode":"1","errorLog":"","results":""}
  43. p_host=data["Host"]
  44. p_port=int(data["Port"])
  45. p_db=data["Database"]
  46. p_user=data["User"]
  47. p_password=data["Password"]
  48. p_table=data["Table"]
  49. try:
  50. db = pymysql.connect(host=p_host, user=p_user, passwd=p_password, db=p_db, port=p_port,
  51. charset='utf8', cursorclass=pymysql.cursors.DictCursor)
  52. db.ping(reconnect=True)
  53. cursor = db.cursor()
  54. sql = "DESCRIBE "+p_table
  55. cursor.execute(sql)
  56. tables = cursor.fetchall()
  57. if tables:
  58. table_names = list(map(lambda x: x['Field'], tables))
  59. res["results"] = table_names
  60. else:
  61. res["successCode"] = "0"
  62. cursor.close()
  63. db.close()
  64. return res
  65. except:
  66. res["successCode"] = "0"
  67. res["errorLog"]=traceback.format_exc()
  68. logging.error(traceback.format_exc())
  69. return res
  70. def mysqlInsert(input,logging):
  71. res={"successCode":"1","errorLog":"","results":""}
  72. data=input["metadata"]["admin"]
  73. p_host=data["Host"]
  74. p_port=int(data["Port"])
  75. p_db=data["Database"]
  76. p_user=data["User"]
  77. p_password=data["Password"]
  78. p_table=data["Table"]
  79. p_columnName=data["columnName"]
  80. cN='('+','.join(p_columnName)+') '
  81. p_values=data["values"]
  82. val=tuple(p_values)
  83. try:
  84. db = pymysql.connect(host=p_host, user=p_user, passwd=p_password, db=p_db, port=p_port,
  85. charset='utf8', cursorclass=pymysql.cursors.DictCursor)
  86. db.ping(reconnect=True)
  87. cursor = db.cursor()
  88. sql = "insert into " + p_table + cN + "values ("+ ','.join(['%s'] * len(val)) + ")"
  89. cursor.execute(sql,val)
  90. db.commit()
  91. cursor.close()
  92. db.close()
  93. return res
  94. except:
  95. res["successCode"] = "0"
  96. res["errorLog"]=traceback.format_exc()
  97. logging.error(traceback.format_exc())
  98. return res
  99. def mysqlUpdate(input,logging):
  100. res={"successCode":"1","errorLog":"","results":""}
  101. data=input["metadata"]["admin"]
  102. p_host=data["Host"]
  103. p_port=int(data["Port"])
  104. p_db=data["Database"]
  105. p_user=data["User"]
  106. p_password=data["Password"]
  107. p_table=data["Table"]
  108. # p_set=data["Set"]
  109. p_set=get_updateSet(input)
  110. # where=process_where(data["Filter"])
  111. where=get_filter(data["Filter"])
  112. try:
  113. db = pymysql.connect(host=p_host, user=p_user, passwd=p_password, db=p_db, port=p_port,
  114. charset='utf8', cursorclass=pymysql.cursors.DictCursor)
  115. db.ping(reconnect=True)
  116. cursor = db.cursor()
  117. sql = "UPDATE " + p_table + p_set + where
  118. print(sql)
  119. cursor.execute(sql)
  120. db.commit()
  121. cursor.close()
  122. db.close()
  123. return res
  124. except:
  125. res["successCode"] = "0"
  126. res["errorLog"]=traceback.format_exc()
  127. logging.error(traceback.format_exc())
  128. return res
  129. def mysqlExecute(input,logging):
  130. res={"successCode":"1","errorLog":"","results":""}
  131. data=input["metadata"]["admin"]
  132. p_host=data["Host"]
  133. p_port=int(data["Port"])
  134. p_db=data["Database"]
  135. p_user=data["User"]
  136. p_password=data["Password"]
  137. execute=data["Execute"]
  138. try:
  139. db = pymysql.connect(host=p_host, user=p_user, passwd=p_password, db=p_db, port=p_port,
  140. charset='utf8', cursorclass=pymysql.cursors.DictCursor)
  141. db.ping(reconnect=True)
  142. cursor = db.cursor()
  143. cursor.execute(execute)
  144. if 'select' in execute.lower():
  145. result = cursor.fetchall()
  146. res["results"]=json.dumps(result,ensure_ascii=False)
  147. else:
  148. db.commit()
  149. cursor.close()
  150. db.close()
  151. return res
  152. except:
  153. res["successCode"] = "0"
  154. res["errorLog"]=traceback.format_exc()
  155. logging.error(traceback.format_exc())
  156. return res
  157. # def process_where(data):
  158. # '''
  159. # 组装where
  160. # :param data: data["Filter"],{"key":"age","value":"20","operator":">"},{"logicalSymbol":"and"},{"key":"weight","value":"50","operator":"<"}
  161. # :return: WHERE age>20 and weight<50
  162. # '''
  163. # if data=="" or data==[]:
  164. # return ""
  165. # where = " WHERE "
  166. # for line in data:
  167. # if "key" in line.keys():
  168. # val = line["value"]
  169. # if isinstance(val, str):
  170. # val = "\'" + val + "\'"
  171. # tmp = str(line["key"]) + " " + line["operator"] + " " + str(val)
  172. # where += tmp
  173. # else:
  174. # where += " " + line["logicalSymbol"] + " "
  175. # return where
  176. #
  177. # def process_filter(data):
  178. # '''
  179. # 组装key,value,operator
  180. # :param data: data["Filter"],{"key":"age",value:"20","operator":"="}
  181. # :return: age=20
  182. # '''
  183. # if data=="" or data==[]:
  184. # return ""
  185. # res=data["key"]+" "+data["operator"]+" "+data["value"]
  186. # return res
  187. def get_updateSet(input):
  188. metadata=input["metadata"]
  189. user=metadata["user"]
  190. sets=metadata["admin"]["Set"]
  191. res=[]
  192. for line in sets:
  193. part=line.split("=")
  194. tmp = []
  195. for p in part:
  196. user_match=re.findall('##(.*?)##', p)
  197. if user_match!=[]:
  198. tmp.append(user[user_match[0]])
  199. res.append(str(tmp[0])+"="+str(tmp[1]))
  200. result=" SET "+",".join(res)
  201. return result
  202. def get_filter(data):
  203. if "OR" not in data.keys():
  204. return ""
  205. op_or=data["OR"]
  206. res = ""
  207. if len(op_or) == 1:
  208. tmp = []
  209. line = op_or[0]["AND"]
  210. for single_line in line:
  211. val = single_line["value"]
  212. if isinstance(val, str):
  213. val = "\'" + val + "\'"
  214. tmp.append(str(single_line["key"]) + single_line["operator"] + str(val))
  215. if single_line != line[-1]:
  216. tmp.append("and")
  217. res = " WHERE "+" ".join(tmp)
  218. elif len(op_or) > 1:
  219. tmp = []
  220. for single_and in op_or:
  221. line = single_and["AND"]
  222. for sigle_line in line:
  223. val = sigle_line["value"]
  224. if isinstance(val, str):
  225. val = "\'" + val + "\'"
  226. tmp.append(str(sigle_line["key"]) + sigle_line["operator"] + str(val))
  227. if sigle_line != line[-1]:
  228. tmp.append("and")
  229. if single_and != op_or[-1]:
  230. tmp.append("or")
  231. res = " WHERE "+" ".join(tmp)
  232. return res
  233. def mysqlQuery(input,logging):
  234. res={"successCode":"1","errorLog":"","results":""}
  235. data=input["metadata"]["admin"]
  236. p_host=data["Host"]
  237. p_port=int(data["Port"])
  238. p_db=data["Database"]
  239. p_user=data["User"]
  240. p_password=data["Password"]
  241. p_table=data["Table"]
  242. p_columnNames=data["columnNames"]
  243. # p_filter=data["Filter"]
  244. column='*'
  245. if len(p_columnNames)==1:
  246. column=p_columnNames[0]
  247. elif len(p_columnNames)>1:
  248. column=','.join(p_columnNames)
  249. where=get_filter(data["Filter"])
  250. try:
  251. db = pymysql.connect(host=p_host, user=p_user, passwd=p_password, db=p_db, port=p_port,
  252. charset='utf8', cursorclass=pymysql.cursors.DictCursor)
  253. db.ping(reconnect=True)
  254. cursor = db.cursor()
  255. sql = "SELECT " + column +" From "+ p_table + where
  256. # print(sql)
  257. cursor.execute(sql)
  258. result = cursor.fetchall()
  259. res["results"]=json.dumps(result,ensure_ascii=False)
  260. cursor.close()
  261. db.close()
  262. return res
  263. except:
  264. res["successCode"] = "0"
  265. res["errorLog"]=traceback.format_exc()
  266. logging.error(traceback.format_exc())
  267. return res
  268. def mysqlDelete(input,logging):
  269. res={"successCode":"1","errorLog":"","results":""}
  270. data=input["metadata"]["admin"]
  271. p_host=data["Host"]
  272. p_port=int(data["Port"])
  273. p_db=data["Database"]
  274. p_user=data["User"]
  275. p_password=data["Password"]
  276. p_table=data["Table"]
  277. # where=process_where(data["Filter"])
  278. where=get_filter(data["Filter"])
  279. try:
  280. db = pymysql.connect(host=p_host, user=p_user, passwd=p_password, db=p_db, port=p_port,
  281. charset='utf8', cursorclass=pymysql.cursors.DictCursor)
  282. db.ping(reconnect=True)
  283. cursor = db.cursor()
  284. sql = "DELETE From "+ p_table + where
  285. cursor.execute(sql)
  286. db.commit()
  287. cursor.close()
  288. db.close()
  289. return res
  290. except:
  291. res["successCode"] = "0"
  292. res["errorLog"]=traceback.format_exc()
  293. logging.error(traceback.format_exc())
  294. return res
  295. if __name__=="__main__":
  296. input={"metadata":{"admin":{
  297. "type":"query",
  298. "Table":"student",
  299. "columnNames":["name","age"],
  300. "Set":["##tag1##=##value1##","##tag2##=##value2##"],
  301. "Filter":{
  302. "OR":[
  303. {
  304. "AND":[{"key":"age","value":20,"operator":">"},{"key":"weight","value":50,"operator":"<"}]
  305. },
  306. {
  307. "AND":[{"key":"name","value":"ff","operator":"="}]
  308. }
  309. ]
  310. },
  311. "Host":"172.26.28.30",
  312. "Port":"3306",
  313. "Database":"test",
  314. "User":"crawl",
  315. "Password":"crawl123"
  316. }},
  317. "user": {
  318. "tag1": "age",
  319. "tag2": "weight",
  320. "value1": 2,
  321. "value2": 100
  322. }
  323. }
  324. res=mysqlUpdate(input,"")
  325. print(res)