Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

exesql.py 3.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. from abc import ABC
  17. import re
  18. import pandas as pd
  19. import pymysql
  20. import psycopg2
  21. from agent.component.base import ComponentBase, ComponentParamBase
  22. class ExeSQLParam(ComponentParamBase):
  23. """
  24. Define the ExeSQL component parameters.
  25. """
  26. def __init__(self):
  27. super().__init__()
  28. self.db_type = "mysql"
  29. self.database = ""
  30. self.username = ""
  31. self.host = ""
  32. self.port = 3306
  33. self.password = ""
  34. self.loop = 3
  35. self.top_n = 30
  36. def check(self):
  37. self.check_valid_value(self.db_type, "Choose DB type", ['mysql', 'postgresql', 'mariadb'])
  38. self.check_empty(self.database, "Database name")
  39. self.check_empty(self.username, "database username")
  40. self.check_empty(self.host, "IP Address")
  41. self.check_positive_integer(self.port, "IP Port")
  42. self.check_empty(self.password, "Database password")
  43. self.check_positive_integer(self.top_n, "Number of records")
  44. class ExeSQL(ComponentBase, ABC):
  45. component_name = "ExeSQL"
  46. def _run(self, history, **kwargs):
  47. if not hasattr(self, "_loop"):
  48. setattr(self, "_loop", 0)
  49. if self._loop >= self._param.loop:
  50. self._loop = 0
  51. raise Exception("Maximum loop time exceeds. Can't query the correct data via SQL statement.")
  52. self._loop += 1
  53. ans = self.get_input()
  54. ans = "".join(ans["content"]) if "content" in ans else ""
  55. ans = re.sub(r'^.*?SELECT ', 'SELECT ', repr(ans), flags=re.IGNORECASE)
  56. ans = re.sub(r';.*?SELECT ', '; SELECT ', ans, flags=re.IGNORECASE)
  57. ans = re.sub(r';[^;]*$', r';', ans)
  58. if not ans:
  59. raise Exception("SQL statement not found!")
  60. if self._param.db_type in ["mysql", "mariadb"]:
  61. db = pymysql.connect(db=self._param.database, user=self._param.username, host=self._param.host,
  62. port=self._param.port, password=self._param.password)
  63. elif self._param.db_type == 'postgresql':
  64. db = psycopg2.connect(dbname=self._param.database, user=self._param.username, host=self._param.host,
  65. port=self._param.port, password=self._param.password)
  66. try:
  67. cursor = db.cursor()
  68. except Exception as e:
  69. raise Exception("Database Connection Failed! \n" + str(e))
  70. sql_res = []
  71. for single_sql in re.split(r';', ans.replace(r"\n", " ")):
  72. if not single_sql:
  73. continue
  74. try:
  75. cursor.execute(single_sql)
  76. if cursor.rowcount == 0:
  77. sql_res.append({"content": "\nTotal: 0\n No record in the database!"})
  78. continue
  79. single_res = pd.DataFrame([i for i in cursor.fetchmany(size=self._param.top_n)])
  80. single_res.columns = [i[0] for i in cursor.description]
  81. sql_res.append({"content": "\nTotal: " + str(cursor.rowcount) + "\n" + single_res.to_markdown()})
  82. except Exception as e:
  83. sql_res.append({"content": "**Error**:" + str(e) + "\nError SQL Statement:" + single_sql})
  84. pass
  85. db.close()
  86. if not sql_res:
  87. return ExeSQL.be_output("")
  88. return pd.DataFrame(sql_res)