sql.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. # Copyright 2021-2024 Avaiga Private Limited
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  4. # the License. You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  9. # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  10. # specific language governing permissions and limitations under the License.
  11. from datetime import datetime, timedelta
  12. from typing import Dict, List, Optional, Set
  13. from sqlalchemy import text
  14. from taipy.config.common.scope import Scope
  15. from .._version._version_manager_factory import _VersionManagerFactory
  16. from ..exceptions.exceptions import MissingAppendQueryBuilder, MissingRequiredProperty
  17. from ._abstract_sql import _AbstractSQLDataNode
  18. from .data_node_id import DataNodeId, Edit
  19. class SQLDataNode(_AbstractSQLDataNode):
  20. """Data Node stored in a SQL database.
  21. Attributes:
  22. config_id (str): Identifier of the data node configuration. It must be a valid Python
  23. identifier.
  24. scope (Scope^): The scope of this data node.
  25. id (str): The unique identifier of this data node.
  26. owner_id (str): The identifier of the owner (sequence_id, scenario_id, cycle_id) or
  27. None.
  28. parent_ids (Optional[Set[str]]): The identifiers of the parent tasks or `None`.
  29. last_edit_date (datetime): The date and time of the last modification.
  30. edits (List[Edit^]): The ordered list of edits for that job.
  31. version (str): The string indicates the application version of the data node to instantiate. If not provided,
  32. the current version is used.
  33. validity_period (Optional[timedelta]): The duration implemented as a timedelta since the last edit date for
  34. which the data node can be considered up-to-date. Once the validity period has passed, the data node is
  35. considered stale and relevant tasks will run even if they are skippable (see the
  36. [Task management](../../userman/scenario_features/sdm/task/index.md) page for more details).
  37. If _validity_period_ is set to `None`, the data node is always up-to-date.
  38. edit_in_progress (bool): True if a task computing the data node has been submitted
  39. and not completed yet. False otherwise.
  40. editor_id (Optional[str]): The identifier of the user who is currently editing the data node.
  41. editor_expiration_date (Optional[datetime]): The expiration date of the editor lock.
  42. properties (dict[str, Any]): A dictionary of additional properties. Note that the
  43. _properties_ parameter must at least contain an entry for _"db_name"_, _"db_engine"_, _"read_query"_,
  44. and _"write_query_builder"_:
  45. - _"db_name"_ `(str)`: The database name, or the name of the SQLite database file.
  46. - _"db_engine"_ `(str)`: The database engine. Possible values are _"sqlite"_, _"mssql"_, _"mysql"_, or
  47. _"postgresql"_.
  48. - _"read_query"_ `(str)`: The SQL query string used to read the data from the database.
  49. - _"write_query_builder"_ `(Callable)`: A callback function that takes the data as an input parameter and
  50. returns a list of SQL queries to be executed when writing data to the data node.
  51. - _"append_query_builder"_ `(Callable)`: A callback function that takes the data as an input parameter and
  52. returns a list of SQL queries to be executed when appending data to the data node.
  53. - _"db_username"_ `(str)`: The database username.
  54. - _"db_password"_ `(str)`: The database password.
  55. - _"db_host"_ `(str)`: The database host. The default value is _"localhost"_.
  56. - _"db_port"_ `(int)`: The database port. The default value is 1433.
  57. - _"db_driver"_ `(str)`: The database driver.
  58. - _"sqlite_folder_path"_ (str): The path to the folder that contains SQLite file. The default value
  59. is the current working folder.
  60. - _"sqlite_file_extension"_ (str): The filename extension of the SQLite file. The default value is ".db".
  61. - _"db_extra_args"_ `(Dict[str, Any])`: A dictionary of additional arguments to be passed into database
  62. connection string.
  63. - _"exposed_type"_: The exposed type of the data read from SQL query. The default value is `pandas`.
  64. """
  65. __STORAGE_TYPE = "sql"
  66. __READ_QUERY_KEY = "read_query"
  67. _WRITE_QUERY_BUILDER_KEY = "write_query_builder"
  68. _APPEND_QUERY_BUILDER_KEY = "append_query_builder"
  69. def __init__(
  70. self,
  71. config_id: str,
  72. scope: Scope,
  73. id: Optional[DataNodeId] = None,
  74. owner_id: Optional[str] = None,
  75. parent_ids: Optional[Set[str]] = None,
  76. last_edit_date: Optional[datetime] = None,
  77. edits: Optional[List[Edit]] = None,
  78. version: Optional[str] = None,
  79. validity_period: Optional[timedelta] = None,
  80. edit_in_progress: bool = False,
  81. editor_id: Optional[str] = None,
  82. editor_expiration_date: Optional[datetime] = None,
  83. properties: Optional[Dict] = None,
  84. ) -> None:
  85. if properties is None:
  86. properties = {}
  87. if properties.get(self.__READ_QUERY_KEY) is None:
  88. raise MissingRequiredProperty(f"Property {self.__READ_QUERY_KEY} is not informed and is required.")
  89. if properties.get(self._WRITE_QUERY_BUILDER_KEY) is None:
  90. raise MissingRequiredProperty(f"Property {self._WRITE_QUERY_BUILDER_KEY} is not informed and is required.")
  91. super().__init__(
  92. config_id,
  93. scope,
  94. id,
  95. owner_id,
  96. parent_ids,
  97. last_edit_date,
  98. edits,
  99. version or _VersionManagerFactory._build_manager()._get_latest_version(),
  100. validity_period,
  101. edit_in_progress,
  102. editor_id,
  103. editor_expiration_date,
  104. properties=properties,
  105. )
  106. self._TAIPY_PROPERTIES.update(
  107. {
  108. self.__READ_QUERY_KEY,
  109. self._WRITE_QUERY_BUILDER_KEY,
  110. self._APPEND_QUERY_BUILDER_KEY,
  111. }
  112. )
  113. @classmethod
  114. def storage_type(cls) -> str:
  115. return cls.__STORAGE_TYPE
  116. def _get_base_read_query(self) -> str:
  117. return self.properties.get(self.__READ_QUERY_KEY)
  118. def _do_append(self, data, engine, connection) -> None:
  119. append_query_builder_fct = self.properties.get(self._APPEND_QUERY_BUILDER_KEY)
  120. if not append_query_builder_fct:
  121. raise MissingAppendQueryBuilder
  122. queries = append_query_builder_fct(data)
  123. self.__execute_queries(queries, connection)
  124. def _do_write(self, data, engine, connection) -> None:
  125. queries = self.properties.get(self._WRITE_QUERY_BUILDER_KEY)(data)
  126. self.__execute_queries(queries, connection)
  127. def __execute_queries(self, queries, connection) -> None:
  128. if not isinstance(queries, List):
  129. queries = [queries]
  130. for query in queries:
  131. if isinstance(query, str):
  132. connection.execute(text(query))
  133. else:
  134. statement = query[0]
  135. parameters = query[1]
  136. connection.execute(text(statement), parameters)