Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

exesql.py 3.4KB

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