|
17 | 17 | from __future__ import annotations |
18 | 18 |
|
19 | 19 | from collections import Counter |
20 | | -from typing import Optional, TYPE_CHECKING |
| 20 | +from typing import Any, Optional, TYPE_CHECKING |
21 | 21 |
|
22 | 22 | from flask import g |
23 | 23 | from flask_appbuilder.security.sqla.models import Role, User |
|
34 | 34 | from superset.daos.exceptions import DatasourceNotFound |
35 | 35 | from superset.daos.tag import TagDAO |
36 | 36 | from superset.tags.models import ObjectType, Tag, TagType |
| 37 | +from superset.utils import json |
37 | 38 | from superset.utils.core import DatasourceType, get_user_id |
38 | 39 |
|
39 | 40 | if TYPE_CHECKING: |
@@ -185,3 +186,43 @@ def update_tags( |
185 | 186 | TagDAO.create_custom_tagged_objects( |
186 | 187 | object_type, object_id, [tag.name for tag in tags_to_add] |
187 | 188 | ) |
| 189 | + |
| 190 | + |
| 191 | +def update_chart_config_dataset( |
| 192 | + config: dict[str, Any], dataset_info: dict[str, Any] |
| 193 | +) -> dict[str, Any]: |
| 194 | + """ |
| 195 | + Update the chart configuration and query_context with new dataset information |
| 196 | +
|
| 197 | + :param config: The original chart configuration |
| 198 | + :param dataset_info: Dict with datasource_id, datasource_type, and datasource_name |
| 199 | + :return: The updated chart configuration |
| 200 | + """ |
| 201 | + # Update datasource id, type, and name |
| 202 | + config.update(dataset_info) |
| 203 | + |
| 204 | + dataset_uid = f"{dataset_info['datasource_id']}__{dataset_info['datasource_type']}" |
| 205 | + config["params"].update({"datasource": dataset_uid}) |
| 206 | + |
| 207 | + if "query_context" in config and config["query_context"] is not None: |
| 208 | + try: |
| 209 | + query_context = json.loads(config["query_context"]) |
| 210 | + |
| 211 | + query_context["datasource"] = { |
| 212 | + "id": dataset_info["datasource_id"], |
| 213 | + "type": dataset_info["datasource_type"], |
| 214 | + } |
| 215 | + |
| 216 | + if "form_data" in query_context: |
| 217 | + query_context["form_data"]["datasource"] = dataset_uid |
| 218 | + |
| 219 | + if "queries" in query_context: |
| 220 | + for query in query_context["queries"]: |
| 221 | + if "datasource" in query: |
| 222 | + query["datasource"] = query_context["datasource"] |
| 223 | + |
| 224 | + config["query_context"] = json.dumps(query_context) |
| 225 | + except json.JSONDecodeError: |
| 226 | + config["query_context"] = None |
| 227 | + |
| 228 | + return config |
0 commit comments