Vitor-Avila commented on code in PR #27582: URL: https://github.com/apache/superset/pull/27582#discussion_r1536267533
########## superset/jinja_context.py: ########## @@ -722,3 +723,72 @@ def dataset_macro( sqla_query = dataset.get_query_str_extended(query_obj, mutate=False) sql = sqla_query.sql return f"(\n{sql}\n) AS dataset_{dataset_id}" + + +def get_dataset_id_from_context(metric_key: str) -> int: + """ + Retrives the Dataset ID from the request context. + + :param metric_key: the metric key. + :returns: the dataset ID. + """ + # pylint: disable=import-outside-toplevel + from superset.daos.chart import ChartDAO + from superset.views.utils import get_form_data + + exc_message = _( + "Please specify the Dataset ID for the ``%(name)s`` metric in the Jinja macro.", + name=metric_key, + ) + + form_data, chart = get_form_data() + if not (form_data or chart): + raise SupersetTemplateException(exc_message) + + if chart: + return chart.datasource_id + if dataset_id := form_data.get("url_params", {}).get("datasource_id"): + return dataset_id Review Comment: that's a good catch! I was thinking that you must associate a dataset to a chart when creating one, but forgot it could be deleted after. Improved that `if chart` to `if chart and chart.datasource_id` to avoid returning `None`. On the second part tho (with the walrus operator) if `url_params["datasource_id"]` is `None`, this `if` block condition won't be met and therefore it won't return. I added a test case covering this specific scenario. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: notifications-unsubscr...@superset.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: notifications-unsubscr...@superset.apache.org For additional commands, e-mail: notifications-h...@superset.apache.org