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.

exesql.py 4.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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. if self.database == "rag_flow":
  45. if self.host == "ragflow-mysql":
  46. raise ValueError("The host is not accessible.")
  47. if self.password == "infini_rag_flow":
  48. raise ValueError("The host is not accessible.")
  49. class ExeSQL(ComponentBase, ABC):
  50. component_name = "ExeSQL"
  51. def _run(self, history, **kwargs):
  52. if not hasattr(self, "_loop"):
  53. setattr(self, "_loop", 0)
  54. if self._loop >= self._param.loop:
  55. self._loop = 0
  56. raise Exception("Maximum loop time exceeds. Can't query the correct data via SQL statement.")
  57. self._loop += 1
  58. ans = self.get_input()
  59. ans = "".join(ans["content"]) if "content" in ans else ""
  60. ans = re.sub(r'^.*?SELECT ', 'SELECT ', repr(ans), flags=re.IGNORECASE)
  61. ans = re.sub(r';.*?SELECT ', '; SELECT ', ans, flags=re.IGNORECASE)
  62. ans = re.sub(r';[^;]*$', r';', ans)
  63. if not ans:
  64. raise Exception("SQL statement not found!")
  65. if self._param.db_type in ["mysql", "mariadb"]:
  66. db = pymysql.connect(db=self._param.database, user=self._param.username, host=self._param.host,
  67. port=self._param.port, password=self._param.password)
  68. elif self._param.db_type == 'postgresql':
  69. db = psycopg2.connect(dbname=self._param.database, user=self._param.username, host=self._param.host,
  70. port=self._param.port, password=self._param.password)
  71. try:
  72. cursor = db.cursor()
  73. except Exception as e:
  74. raise Exception("Database Connection Failed! \n" + str(e))
  75. sql_res = []
  76. for single_sql in re.split(r';', ans.replace(r"\n", " ")):
  77. if not single_sql:
  78. continue
  79. try:
  80. cursor.execute(single_sql)
  81. if cursor.rowcount == 0:
  82. sql_res.append({"content": "\nTotal: 0\n No record in the database!"})
  83. continue
  84. single_res = pd.DataFrame([i for i in cursor.fetchmany(size=self._param.top_n)])
  85. single_res.columns = [i[0] for i in cursor.description]
  86. sql_res.append({"content": "\nTotal: " + str(cursor.rowcount) + "\n" + single_res.to_markdown()})
  87. except Exception as e:
  88. sql_res.append({"content": "**Error**:" + str(e) + "\nError SQL Statement:" + single_sql})
  89. pass
  90. db.close()
  91. if not sql_res:
  92. return ExeSQL.be_output("")
  93. return pd.DataFrame(sql_res)