Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 pandas as pd
  18. from peewee import MySQLDatabase, PostgresqlDatabase
  19. from agent.component.base import ComponentBase, ComponentParamBase
  20. class ExeSQLParam(ComponentParamBase):
  21. """
  22. Define the ExeSQL component parameters.
  23. """
  24. def __init__(self):
  25. super().__init__()
  26. self.db_type = "mysql"
  27. self.database = ""
  28. self.username = ""
  29. self.host = ""
  30. self.port = 3306
  31. self.password = ""
  32. self.loop = 3
  33. self.top_n = 30
  34. def check(self):
  35. self.check_valid_value(self.db_type, "Choose DB type", ['mysql', 'postgresql', 'mariadb'])
  36. self.check_empty(self.database, "Database name")
  37. self.check_empty(self.username, "database username")
  38. self.check_empty(self.host, "IP Address")
  39. self.check_positive_integer(self.port, "IP Port")
  40. self.check_empty(self.password, "Database password")
  41. self.check_positive_integer(self.top_n, "Number of records")
  42. class ExeSQL(ComponentBase, ABC):
  43. component_name = "ExeSQL"
  44. def _run(self, history, **kwargs):
  45. if not hasattr(self, "_loop"):
  46. setattr(self, "_loop", 0)
  47. if self._loop >= self._param.loop:
  48. self._loop = 0
  49. raise Exception("Maximum loop time exceeds. Can't query the correct data via sql statement.")
  50. self._loop += 1
  51. ans = self.get_input()
  52. ans = "".join(ans["content"]) if "content" in ans else ""
  53. if not ans:
  54. return ExeSQL.be_output("SQL statement not found!")
  55. if self._param.db_type in ["mysql", "mariadb"]:
  56. db = MySQLDatabase(self._param.database, user=self._param.username, host=self._param.host,
  57. port=self._param.port, password=self._param.password)
  58. elif self._param.db_type == 'postgresql':
  59. db = PostgresqlDatabase(self._param.database, user=self._param.username, host=self._param.host,
  60. port=self._param.port, password=self._param.password)
  61. try:
  62. db.connect()
  63. query = db.execute_sql(ans)
  64. sql_res = [{"content": rec + "\n"} for rec in [str(i) for i in query.fetchall()]]
  65. db.close()
  66. except Exception as e:
  67. return ExeSQL.be_output("**Error**:" + str(e))
  68. if not sql_res:
  69. return ExeSQL.be_output("No record in the database!")
  70. sql_res.insert(0, {"content": "Number of records retrieved from the database is " + str(len(sql_res)) + "\n"})
  71. df = pd.DataFrame(sql_res[0:self._param.top_n + 1])
  72. return ExeSQL.be_output(df.to_markdown())