diff --git a/UPDATING.md b/UPDATING.md index 3b90f807db12..6e9b44596399 100644 --- a/UPDATING.md +++ b/UPDATING.md @@ -129,6 +129,23 @@ assists people when migrating to a new version. `maxPendingConnections` (`MAX_PENDING_CONNECTIONS`) is recommended, see the [websocket server README](superset-websocket/README.md). +- [#39681](https://github.com/apache/superset/issues/39681): A time range + lands on a chart's time column instead of on every `TEMPORAL_RANGE` filter. + The time column is the chart's Time Column (granularity) or its x-axis, + including the datetime column a Custom SQL x-axis reads; a temporal groupby + of a table, pivot table or box plot is not one. A dashboard time range + replaces the `TEMPORAL_RANGE` filter on that column, or else fills the chart's + unbounded time filter, or else is added as a filter on a temporal x-axis; + filters on other datetime columns keep their own ranges, also in Drill to + Detail and in time comparison queries, which compare the time column chosen + the same way. A time x-axis cross-filter's range replaces the ranges on the + cross-filtered column only. Without a time range, a chart with a temporal + x-axis takes its time bounds only from a filter on that x-axis, no longer + from another datetime column. Charts with no known time column still apply a + time range to every `TEMPORAL_RANGE` filter. A Custom SQL x-axis without a + Time Column is still bounded on the dataset's main datetime column, as + before, replacing a saved range on that column. + - Semantic-view column pickers only offer saved dimensions, including for older metadata without feature declarations. `ADHOC_COLUMN_EXPRESSIONS` remains importable but is reserved and grants no capability. Providers must use recognized SDK enum members; raw-string declarations are ignored. SQL dataset expression controls are unchanged. - Semantic-layer connection updates that reuse masked credentials require a diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/Timeseries/EchartsTimeseries.tsx b/superset-frontend/plugins/plugin-chart-echarts/src/Timeseries/EchartsTimeseries.tsx index 391fa7bbcf6e..d98a3db7f91d 100644 --- a/superset-frontend/plugins/plugin-chart-echarts/src/Timeseries/EchartsTimeseries.tsx +++ b/superset-frontend/plugins/plugin-chart-echarts/src/Timeseries/EchartsTimeseries.tsx @@ -487,9 +487,10 @@ export default function EchartsTimeseries({ val: timeRange, }, ], - // The backend rewrites every TEMPORAL_RANGE filter's value with the - // query's time_range, so without this override target charts would - // keep their own saved range and ignore the clicked bucket. + // The backend writes the query's time_range into the TEMPORAL_RANGE + // filters on the cross-filtered column, so without this override + // target charts would keep their own saved range on that column and + // ignore the clicked bucket. ...(values.length ? { time_range: timeRange } : {}), }, filterState: { diff --git a/superset-frontend/src/components/Chart/DrillDetail/DrillDetailPane.tsx b/superset-frontend/src/components/Chart/DrillDetail/DrillDetailPane.tsx index 9879fa3c4e46..ee8e876e87c5 100644 --- a/superset-frontend/src/components/Chart/DrillDetail/DrillDetailPane.tsx +++ b/superset-frontend/src/components/Chart/DrillDetail/DrillDetailPane.tsx @@ -255,11 +255,14 @@ export default function DrillDetailPane({ result_type: 'drill_detail', result_format: exportType, force: false, - form_data: { viz_type: formData.viz_type }, + form_data: { + viz_type: formData.viz_type, + ...(drillPayload.x_axis !== undefined && { + x_axis: drillPayload.x_axis, + }), + ...(dashboardId && { dashboardId }), + }, }; - if (dashboardId) { - payload.form_data = { viz_type: formData.viz_type, dashboardId }; - } SupersetClient.postForm('/api/v1/chart/data', { form_data: safeStringify(payload), }).catch(error => { diff --git a/superset-frontend/src/components/Chart/DrillDetail/utils.test.ts b/superset-frontend/src/components/Chart/DrillDetail/utils.test.ts index b68e57dc59a8..3419f4c649b3 100644 --- a/superset-frontend/src/components/Chart/DrillDetail/utils.test.ts +++ b/superset-frontend/src/components/Chart/DrillDetail/utils.test.ts @@ -54,3 +54,21 @@ test('carries the chart url_params so url_param() renders like the chart', () => } as QueryFormData); expect(payload?.url_params).toEqual({ tenant: 'zenda' }); }); + +test('carries the chart x-axis so the time range lands on it like the chart', () => { + const xAxis = { label: 'day', sqlExpression: 'DATE(created_at)' }; + const payload = getDrillPayload({ + datasource: '1__table', + viz_type: 'echarts_timeseries_bar', + x_axis: xAxis, + } as QueryFormData); + expect(payload?.x_axis).toEqual(xAxis); +}); + +test('omits the x-axis for charts without one', () => { + const payload = getDrillPayload({ + datasource: '1__table', + viz_type: 'table', + } as QueryFormData); + expect(payload).not.toHaveProperty('x_axis'); +}); diff --git a/superset-frontend/src/components/Chart/DrillDetail/utils.ts b/superset-frontend/src/components/Chart/DrillDetail/utils.ts index c397b03f742d..996f09f375f7 100644 --- a/superset-frontend/src/components/Chart/DrillDetail/utils.ts +++ b/superset-frontend/src/components/Chart/DrillDetail/utils.ts @@ -39,6 +39,8 @@ export function getDrillPayload( ]; return { viz_type: queryFormData.viz_type, + // The backend scopes the time range to the chart's x-axis, as for the chart. + ...(queryFormData.x_axis !== undefined && { x_axis: queryFormData.x_axis }), granularity: queryObject.granularity, time_range: queryObject.time_range, filters, diff --git a/superset/common/query_context_factory.py b/superset/common/query_context_factory.py index 4bdbc0f8b02d..bbae59cb6dc5 100644 --- a/superset/common/query_context_factory.py +++ b/superset/common/query_context_factory.py @@ -24,6 +24,11 @@ from superset.common.query_context import QueryContext from superset.common.query_object import QueryObject from superset.common.query_object_factory import QueryObjectFactory +from superset.common.utils.time_range_utils import ( + get_axis_temporal_columns, + get_column_identifiers, + get_temporal_column_names, +) from superset.daos.chart import ChartDAO from superset.daos.datasource import DatasourceDAO from superset.explorables.base import Explorable @@ -31,7 +36,12 @@ from superset.models.slice import Slice from superset.security.manager import STOCK_RAISE_FOR_ACCESS from superset.superset_typing import Column -from superset.utils.core import DatasourceDict, DatasourceType, is_adhoc_column +from superset.utils.core import ( + DatasourceDict, + DatasourceType, + is_adhoc_column, + QueryObjectFilterClause, +) from superset.utils.date_parser import is_no_time_range if TYPE_CHECKING: @@ -54,6 +64,11 @@ def create_query_object_factory() -> QueryObjectFactory: return QueryObjectFactory(current_app.config, DatasourceDAO()) +def _is_unbounded(value: object) -> bool: + """Whether a temporal filter value sets no range.""" + return value is None or (isinstance(value, str) and is_no_time_range(value)) + + class QueryContextFactory: # pylint: disable=too-few-public-methods _query_object_factory: QueryObjectFactory _authorize_semantic_before_metadata: bool @@ -134,7 +149,14 @@ def create( # pylint: disable=too-many-arguments force_query=force, server_pagination=server_pagination, preserve_null_row_limit=preserve_null_row_limit, - **query_obj, + # The chart's x-axis is read from the form data; an + # ``x_axis`` key in a stored query dict is ignored. + x_axis=(form_data or {}).get("x_axis"), + **{ + key: value + for key, value in query_obj.items() + if key != "x_axis" + }, ), ) for query_obj in queries @@ -175,7 +197,7 @@ def _process_query_object( query_object: QueryObject, ) -> QueryObject: self._apply_granularity(query_object, form_data, datasource) - self._apply_filters(query_object, form_data) + self._apply_filters(query_object, form_data, datasource) self._add_tooltip_columns(query_object, form_data) self._add_currency_column(query_object, form_data, datasource) return query_object @@ -480,22 +502,88 @@ def _apply_granularity( # noqa: C901 ] def _apply_filters( - self, query_object: QueryObject, form_data: dict[str, Any] | None = None + self, + query_object: QueryObject, + form_data: dict[str, Any] | None = None, + datasource: Explorable | None = None, ) -> None: - """Apply the time range, retaining the source of dashboard overrides.""" + """Apply the time range, retaining the source of dashboard overrides. + + A cross-filter's range replaces the ``TEMPORAL_RANGE`` filters on the + column it was issued for. Any other range replaces those on the chart's + time column (granularity) or x-axis, including a datetime column a + Custom SQL x-axis reads, so other datetime columns keep their own + ranges. Without such a filter and a time column, the range fills the + chart's unbounded ``TEMPORAL_RANGE`` filters, or else a filter added on a + temporal x-axis. When no such column is known, every ``TEMPORAL_RANGE`` + filter takes the range. + """ extra_form_data: object = (form_data or {}).get("extra_form_data") dashboard_time_override: bool = ( isinstance(extra_form_data, dict) and "time_range" in extra_form_data and extra_form_data["time_range"] == query_object.time_range ) - if query_object.time_range: - for filter_object in query_object.filter: - if filter_object["op"] == "TEMPORAL_RANGE": - saved: object = filter_object.get("val") - was_unbounded: bool = saved is None or ( - isinstance(saved, str) and is_no_time_range(saved) - ) - filter_object["val"] = query_object.time_range - if dashboard_time_override and was_unbounded: - filter_object["isExtra"] = True + if not query_object.time_range: + return + temporal_filters: list[QueryObjectFilterClause] = [ + filter_object + for filter_object in query_object.filter + if filter_object["op"] == "TEMPORAL_RANGE" + ] + cross_filter_columns: set[str] = { + identifier + for filter_object in ( + extra_form_data.get("filters") or [] + if isinstance(extra_form_data, dict) + else [] + ) + if isinstance(filter_object, dict) + and filter_object.get("op") == "TEMPORAL_RANGE" + and filter_object.get("val") == query_object.time_range + for identifier in get_column_identifiers(filter_object.get("col")) + } + granularity: object = getattr(query_object, "granularity", None) + x_axis: object = (form_data or {}).get("x_axis") + axis_columns: tuple[str, ...] = get_axis_temporal_columns( + x_axis, get_temporal_column_names(datasource) + ) + time_columns: set[str] = cross_filter_columns or { + *get_column_identifiers(granularity), + *get_column_identifiers(x_axis), + *axis_columns, + } + targets: list[QueryObjectFilterClause] = [ + filter_object + for filter_object in temporal_filters + if time_columns.intersection(get_column_identifiers(filter_object["col"])) + ] + if ( + not targets + and not cross_filter_columns + and not isinstance(granularity, str) + ): + # An unbounded range is the chart's time filter awaiting a range. + if unbounded := [ + filter_object + for filter_object in temporal_filters + if _is_unbounded(filter_object.get("val")) + ]: + targets = unbounded + elif len(axis_columns) == 1: + axis_filter: QueryObjectFilterClause = { + "col": axis_columns[0], + "op": "TEMPORAL_RANGE", + "val": None, + } + # Time comparison shifts only the first temporal range, so the + # x-axis range goes first. + query_object.filter.insert(0, axis_filter) + targets = [axis_filter] + else: + targets = temporal_filters + for filter_object in targets: + was_unbounded: bool = _is_unbounded(filter_object.get("val")) + filter_object["val"] = query_object.time_range + if dashboard_time_override and was_unbounded: + filter_object["isExtra"] = True diff --git a/superset/common/query_object_factory.py b/superset/common/query_object_factory.py index df7e200e2b8e..67399a8604a2 100644 --- a/superset/common/query_object_factory.py +++ b/superset/common/query_object_factory.py @@ -23,6 +23,7 @@ from superset.common.query_object import DEPRECATED_FIELDS, QueryObject from superset.common.utils.time_range_utils import ( get_since_until_from_time_range, + get_temporal_column_names, get_time_range_from_filters, ) from superset.superset_typing import Column @@ -30,6 +31,7 @@ apply_max_row_limit, DatasourceDict, DatasourceType, + get_base_axis_columns, QueryObjectFilterClause, ) @@ -61,6 +63,7 @@ def create( # pylint: disable=too-many-arguments server_pagination: bool | None = None, datasource_model_instance: BaseDatasource | None = None, preserve_null_row_limit: bool = False, + x_axis: Column | None = None, **kwargs: Any, ) -> QueryObject: if datasource_model_instance is None and datasource: @@ -101,8 +104,21 @@ def create( # pylint: disable=too-many-arguments preserve_null_row_limit=preserve_null_row_limit, ) + # Only a chart's x-axis is its time column: a temporal groupby that a + # table sends as the base axis is not. + temporal_columns: set[str] | None = None + if ( + time_range is None + and datasource_model_instance is not None + and get_base_axis_columns(kwargs.get("columns")) + ): + temporal_columns = ( + get_temporal_column_names(datasource_model_instance) + if x_axis is not None + else set() + ) processed_time_range = self._process_time_range( - time_range, kwargs.get("filters"), kwargs.get("columns") + time_range, kwargs.get("filters"), kwargs.get("columns"), temporal_columns ) from_dttm, to_dttm = get_since_until_from_time_range( processed_time_range, time_shift, processed_extras @@ -164,8 +180,11 @@ def _process_time_range( time_range: str | None, filters: list[QueryObjectFilterClause] | None = None, columns: list[Column] | None = None, + temporal_columns: set[str] | None = None, ) -> str: - return get_time_range_from_filters(time_range, filters, columns) + return get_time_range_from_filters( + time_range, filters, columns, temporal_columns + ) # light version of the view.utils.core # import view.utils require application context diff --git a/superset/common/utils/time_range_utils.py b/superset/common/utils/time_range_utils.py index 271a4cb8d720..b4984f2728bc 100644 --- a/superset/common/utils/time_range_utils.py +++ b/superset/common/utils/time_range_utils.py @@ -16,7 +16,8 @@ # under the License. from __future__ import annotations -from collections.abc import Mapping, Sequence +import re +from collections.abc import Collection, Mapping, Sequence from datetime import datetime from typing import Any, cast @@ -30,7 +31,7 @@ from superset.superset_typing import Column from superset.utils.core import ( FilterOperator, - get_x_axis_label, + get_base_axis_columns, ) from superset.utils.date_parser import get_since_until @@ -39,8 +40,15 @@ def get_time_range_from_filters( time_range: str | None, filters: Sequence[Mapping[str, object]] | None, columns: list[Column] | None, + temporal_columns: Collection[str] | None = None, ) -> str: - """Select the original range expression without evaluating relative dates.""" + """Select the original range expression without evaluating relative dates. + + The x-axis takes the range that targets it, by label, then by expression, + then by a datetime column its expression reads. A temporal x-axis without + one has no range. Without an x-axis, or with one that reads none of + ``temporal_columns``, the first temporal range is used. + """ if time_range is not None: return time_range temporal_filters: list[Mapping[str, object]] = [ @@ -51,12 +59,73 @@ def get_time_range_from_filters( ] if not temporal_filters: return NO_TIME_RANGE - x_axis_label: str | None = get_x_axis_label(columns) - selected: Mapping[str, object] = next( - (filter_ for filter_ in temporal_filters if filter_.get("col") == x_axis_label), - temporal_filters[0], + base_axes: list[Column] = get_base_axis_columns(columns) + if not base_axes: + return cast(str, temporal_filters[0].get("val")) + axis_columns: tuple[str, ...] = ( + get_axis_temporal_columns(base_axes[0], temporal_columns) + if temporal_columns is not None + else () ) - return cast(str, selected.get("val")) + for identifier in (*get_column_identifiers(base_axes[0]), *axis_columns): + for filter_ in temporal_filters: + if identifier in get_column_identifiers(filter_.get("col")): + return cast(str, filter_.get("val")) + if temporal_columns is not None and not axis_columns: + return cast(str, temporal_filters[0].get("val")) + return NO_TIME_RANGE + + +def get_column_identifiers(column: object) -> tuple[str, ...]: + """Return the names a column is referenced by: its label, then expression.""" + if isinstance(column, str): + return (column,) + if isinstance(column, Mapping): + return tuple( + value + for key in ("label", "sqlExpression") + if isinstance(value := column.get(key), str) and value + ) + return () + + +# Quoted names are length-bounded so an unterminated opener cannot make the scan +# rescan the rest of the expression from every opener (quadratic backtracking). +_SQL_IDENTIFIER = re.compile( + r'"([^"]{1,255})"|`([^`]{1,255})`|\[([^\]]{1,255})\]|([A-Za-z_]\w{0,254})' +) + + +def get_axis_temporal_columns( + axis: object, temporal_columns: Collection[str] +) -> tuple[str, ...]: + """Return the datetime columns an x-axis reads: itself, or those its SQL names.""" + if isinstance(axis, str): + return (axis,) if axis in temporal_columns else () + expression: object = ( + axis.get("sqlExpression") if isinstance(axis, Mapping) else None + ) + if not isinstance(expression, str): + return () + names: list[str] = [ + next(group for group in match.groups() if group) + for match in _SQL_IDENTIFIER.finditer(expression) + ] + return tuple(dict.fromkeys(name for name in names if name in temporal_columns)) + + +def get_temporal_column_names(datasource: object) -> set[str]: + """Return the names of a datasource's datetime columns.""" + columns: object = getattr(datasource, "columns", None) + return { + column["column_name"] if isinstance(column, dict) else column.column_name + for column in (columns if isinstance(columns, (list, tuple)) else []) + if ( + column.get("is_dttm") + if isinstance(column, dict) + else getattr(column, "is_dttm", False) + ) + } def get_since_until_from_time_range( diff --git a/superset/models/helpers.py b/superset/models/helpers.py index 6c5937e64410..31abb5535d8d 100644 --- a/superset/models/helpers.py +++ b/superset/models/helpers.py @@ -99,9 +99,12 @@ ) from superset.common.utils import dataframe_utils from superset.common.utils.time_range_utils import ( + get_axis_temporal_columns, + get_column_identifiers, get_since_until_from_query_object, get_since_until_from_temporal_filter, get_since_until_from_time_range, + get_temporal_column_names, ) from superset.connectors.sqla.partition_mapping import ( build_mirrored_predicates, @@ -2252,6 +2255,22 @@ class SqlaQuery(NamedTuple): ) +def _carries_compared_range( + flt: QueryObjectFilterClause, query_object: QueryObject, temporal_col: str | None +) -> bool: + """Whether a temporal filter holds the range a time comparison replaces. + + That is the time column's range, or the query's time range wherever it was + applied. Ranges of other datetime columns hold for every period, as they do + in the main query; without a time range, every temporal filter is replaced. + """ + return flt.get("op") == FilterOperator.TEMPORAL_RANGE and ( + query_object.time_range is None + or flt.get("val") == query_object.time_range + or temporal_col in get_column_identifiers(flt.get("col")) + ) + + class ExploreMixin: # pylint: disable=too-many-public-methods """ Allows any flask_appbuilder.Model (Query, Table, etc.) @@ -3573,18 +3592,18 @@ def processing_time_offsets( # pylint: disable=too-many-locals,too-many-stateme # Create a completely new filter list to preserve original filters query_object_clone.filter = copy.deepcopy(query_object_clone.filter) - # Remove any existing temporal filters that might conflict - query_object_clone.filter = [ - flt - for flt in query_object_clone.filter - if not (flt.get("op") == FilterOperator.TEMPORAL_RANGE) - ] - # Determine the temporal column with multiple fallback strategies temporal_col = self._get_temporal_column_for_filter( query_object, x_axis_label ) + # Remove the temporal filters carrying the compared range + query_object_clone.filter = [ + flt + for flt in query_object_clone.filter + if not _carries_compared_range(flt, query_object, temporal_col) + ] + # Always add a temporal filter for date range offsets if temporal_col: new_temporal_filter: QueryObjectFilterClause = { @@ -3612,14 +3631,15 @@ def processing_time_offsets( # pylint: disable=too-many-locals,too-many-stateme # the temporal filter so we run the query with the correct time range if not dataframe_utils.is_datetime_series(df.get(index)): query_object_clone.filter = copy.deepcopy(query_object_clone.filter) + temporal_col = self._get_temporal_column_for_filter( + query_object, x_axis_label + ) # Find and update temporal filters for flt in query_object_clone.filter: - if flt.get( - "op" - ) == FilterOperator.TEMPORAL_RANGE and isinstance( - flt.get("val"), str - ): + if _carries_compared_range( + flt, query_object, temporal_col + ) and isinstance(flt.get("val"), str): time_range = cast(str, flt.get("val")) ( new_outer_from_dttm, @@ -3839,30 +3859,57 @@ def _get_temporal_column_for_filter( # noqa: C901 """ Helper method to reliably determine the temporal column for filtering. - This method tries multiple strategies to find the correct temporal column: - 1. Use the column from existing TEMPORAL_RANGE filter + The column is the query's time column, chosen as the main query chooses + it, so that a comparison shifts the range the main query applied: + 1. The column of a TEMPORAL_RANGE filter on the time column (granularity), + the x-axis, or a datetime column the x-axis expression reads 2. Use explicitly set granularity - 3. Use x_axis_label if it exists + 3. The column of a TEMPORAL_RANGE filter carrying the query's time range + 4. The column of the first TEMPORAL_RANGE filter + 5. Use x_axis_label if it exists :param query_object: The query object :param x_axis_label: The x-axis label from the query :return: The name of the temporal column, or None if not found """ - # Strategy 1: Use the column from existing TEMPORAL_RANGE filter - if query_object.filter: - for flt in query_object.filter: - if flt.get("op") == FilterOperator.TEMPORAL_RANGE: - col = flt.get("col") - if isinstance(col, str): - return col - elif isinstance(col, dict) and col.get("sqlExpression"): - return str(col.get("label") or col.get("sqlExpression")) - - # Strategy 2: Use explicitly set granularity - if query_object.granularity: + temporal_filters: list[QueryObjectFilterClause] = [ + flt + for flt in query_object.filter or [] + if flt.get("op") == FilterOperator.TEMPORAL_RANGE + ] + base_axes = get_base_axis_columns(query_object.columns) + time_columns: set[str] = { + *get_column_identifiers(query_object.granularity), + *( + identifier + for axis in base_axes[:1] + for identifier in ( + *get_column_identifiers(axis), + *get_axis_temporal_columns(axis, get_temporal_column_names(self)), + ) + ), + } + candidates: list[QueryObjectFilterClause] = [ + flt + for flt in temporal_filters + if time_columns.intersection(get_column_identifiers(flt.get("col"))) + ] + if not candidates and query_object.granularity: return query_object.granularity - - # Strategy 3: Use x_axis_label if it exists + if not candidates and query_object.time_range: + candidates = [ + flt + for flt in temporal_filters + if flt.get("val") == query_object.time_range + ] + for flt in candidates or temporal_filters: + col = flt.get("col") + if isinstance(col, str): + return col + elif isinstance(col, dict) and col.get("sqlExpression"): + return str(col.get("label") or col.get("sqlExpression")) + + # Use x_axis_label if it exists if x_axis_label: return x_axis_label diff --git a/superset/semantic_layers/mapper.py b/superset/semantic_layers/mapper.py index 2e81a3c204cc..3c4c6343b1c3 100644 --- a/superset/semantic_layers/mapper.py +++ b/superset/semantic_layers/mapper.py @@ -61,6 +61,7 @@ from superset.common.utils.time_range_utils import ( get_since_until_from_query_object, get_since_until_from_time_range, + get_temporal_column_names, get_time_range_from_filters, ) from superset.connectors.sqla.models import BaseDatasource @@ -766,6 +767,7 @@ def _get_adhoc_filters( query_object.time_range, query_object.filter, query_object.columns, + get_temporal_column_names(query_object.datasource), ) if replaced_time_axis is not None else None diff --git a/superset/views/datasource/schemas.py b/superset/views/datasource/schemas.py index de0df05caadb..c8225e83c4e6 100644 --- a/superset/views/datasource/schemas.py +++ b/superset/views/datasource/schemas.py @@ -84,6 +84,13 @@ class SamplesPayloadSchema(Schema): metadata={"description": "Extra parameters to add to the query."}, allow_none=True, ) + x_axis = fields.Raw( + metadata={ + "description": "X-axis of the chart the samples are drilled from, which " + "scopes a time range to the chart's time column." + }, + allow_none=True, + ) url_params = fields.Dict( metadata={ "description": "URL parameters of the dashboard or Explore view the " diff --git a/superset/views/datasource/utils.py b/superset/views/datasource/utils.py index 51e63e421cff..43ff768a49d1 100644 --- a/superset/views/datasource/utils.py +++ b/superset/views/datasource/utils.py @@ -129,14 +129,17 @@ def _split_samples_form_data( """ Separate the payload keys that describe the request from the query object. - ``viz_type`` and ``url_params`` belong on the form data: the former drives - result handling, the latter is what the ``url_param()`` Jinja macro reads. + ``viz_type``, ``x_axis`` and ``url_params`` belong on the form data: the + first drives result handling, the second scopes a time range to the chart's + time column, the last is what the ``url_param()`` Jinja macro reads. """ form_data: dict[str, Any] = {"dashboardId": dashboard_id} if dashboard_id else {} if payload: payload = dict(payload) if "viz_type" in payload: form_data["viz_type"] = payload.pop("viz_type") + if (x_axis := payload.pop("x_axis", None)) is not None: + form_data["x_axis"] = x_axis if url_params := payload.pop("url_params", None): form_data["url_params"] = url_params return payload, form_data or None diff --git a/tests/unit_tests/common/test_drill_by_time_column.py b/tests/unit_tests/common/test_drill_by_time_column.py index 06afe836e85b..e1fbbe10b524 100644 --- a/tests/unit_tests/common/test_drill_by_time_column.py +++ b/tests/unit_tests/common/test_drill_by_time_column.py @@ -233,13 +233,15 @@ def _bar(rows: list[Any], month: str) -> int: ), } EXPECTED_BARS = { - "range_and_ship_filter": [0, 3, 2, 2], - "time_column_and_x_axis_no_filter": [0, 0, 2, 2], - "time_column_and_dashboard_x_axis_filter": [0, 0, 2, 2], + # The time range bounds order_date; ship_date keeps its own range, which drops + # the February order shipped in July. + "range_and_ship_filter": [0, 0, 2, 1], + "time_column_and_x_axis_no_filter": [0, 0, 2, 1], + "time_column_and_dashboard_x_axis_filter": [0, 0, 2, 1], # Bars count ship_date months: the Time Column replaces the x-axis. "time_column_overrides_x_axis": [0, 0, 3, 2], - "custom_sql_x_axis": [0, 0, 2, 2], - "custom_sql_x_axis_with_own_label": [0, 0, 2, 2], + "custom_sql_x_axis": [0, 0, 2, 1], + "custom_sql_x_axis_with_own_label": [0, 0, 2, 1], } diff --git a/tests/unit_tests/common/test_query_context_factory.py b/tests/unit_tests/common/test_query_context_factory.py index 8195ec07ec62..b54e668e6042 100644 --- a/tests/unit_tests/common/test_query_context_factory.py +++ b/tests/unit_tests/common/test_query_context_factory.py @@ -68,7 +68,6 @@ def test_ordinary_context_rewrites_reach_async_cache_values() -> None: "extras": {"where": "country = '{{ 'France' }}'", "time_grain_sqla": "P1D"}, } expected = deepcopy(query) - expected["filters"][1]["val"] = query["time_range"] expected["extras"]["where"] = "country = 'France'" with ( patch( @@ -88,7 +87,7 @@ def test_ordinary_context_rewrites_reach_async_cache_values() -> None: ) assert context.queries[0].filter == [query["filters"][1]] assert context.queries[0].filter[0] is query["filters"][1] - assert query["filters"][1]["val"] == query["time_range"] + assert query["filters"][1]["val"] == "2020-01-01 : 2021-01-01" assert context.queries[0].extras is query["extras"] unrendered_key = context._processor.cache_key() context.raise_for_access() @@ -1463,3 +1462,324 @@ def test_saved_temporal_bindings_use_default_only_for_omitted_granularity( else set() ) datasource.save.assert_not_called() + + +def _two_datetime_dataset() -> SqlaTable: + return SqlaTable( + id=1, + table_name="events", + database=Database(database_name="test", sqlalchemy_uri="sqlite://"), + columns=[ + TableColumn(column_name="ds", type="DATETIME", is_dttm=True), + TableColumn(column_name="created_at", type="DATETIME", is_dttm=True), + TableColumn(column_name="country", type="VARCHAR"), + ], + main_dttm_col="ds", + ) + + +@pytest.mark.parametrize( + ("x_axis", "expected_from"), + [("ds", None), ("country", datetime(2000, 1, 1))], +) +def test_time_bounds_come_from_the_temporal_x_axis( + x_axis: str, expected_from: datetime | None +) -> None: + """Only a non-temporal x-axis takes its bounds from another column's range.""" + query: dict[str, Any] = { + "columns": [ + {"columnType": "BASE_AXIS", "label": x_axis, "sqlExpression": x_axis} + ], + "metrics": ["count"], + "filters": [ + { + "col": "created_at", + "op": "TEMPORAL_RANGE", + "val": "2000-01-01 : 2001-01-01", + }, + ], + } + with patch( + "superset.daos.datasource.DatasourceDAO.get_datasource", + return_value=_two_datetime_dataset(), + ): + context = QueryContextFactory().create( + datasource={"id": 1, "type": "table"}, + queries=[query], + form_data={"x_axis": x_axis}, + ) + assert context.queries[0].from_dttm == expected_from + + +def test_time_range_rewrites_only_the_granularity_filter() -> None: + """A dashboard time range leaves other datetime columns' ranges intact.""" + secondary: QueryObjectFilterClause = { + "col": "created_at", + "op": "TEMPORAL_RANGE", + "val": "2000-01-01 : 2001-01-01", + } + axis_filter: QueryObjectFilterClause = { + "col": {"label": "ds", "sqlExpression": "ds"}, + "op": "TEMPORAL_RANGE", + "val": "No filter", + } + query: QueryObject = QueryObject( + granularity="ds", + time_range="2024-01-01 : 2025-01-01", + filters=[axis_filter, secondary], + ) + QueryContextFactory()._apply_filters(query) + assert axis_filter["val"] == "2024-01-01 : 2025-01-01" + assert secondary["val"] == "2000-01-01 : 2001-01-01" + + +def _create_with_time_range( + columns: list[Any], filters: list[Any], x_axis: Any +) -> QueryObject: + time_range = "2024-01-01 : 2025-01-01" + with patch( + "superset.daos.datasource.DatasourceDAO.get_datasource", + return_value=_two_datetime_dataset(), + ): + context = QueryContextFactory().create( + datasource={"id": 1, "type": "table"}, + queries=[ + { + "columns": columns, + "metrics": ["count"], + "time_range": time_range, + "filters": filters, + } + ], + form_data={"x_axis": x_axis, "extra_form_data": {"time_range": time_range}}, + ) + return context.queries[0] + + +def test_time_range_bounds_the_x_axis_and_keeps_other_ranges() -> None: + """Without a Time Column, the range replaces only the x-axis filter.""" + query = _create_with_time_range( + [{"columnType": "BASE_AXIS", "label": "ds", "sqlExpression": "ds"}], + [ + {"col": "ds", "op": "TEMPORAL_RANGE", "val": "No filter"}, + { + "col": "created_at", + "op": "TEMPORAL_RANGE", + "val": "2000-01-01 : 2001-01-01", + }, + ], + "ds", + ) + assert query.granularity is None + assert [(flt["col"], flt["val"]) for flt in query.filter] == [ + ("ds", "2024-01-01 : 2025-01-01"), + ("created_at", "2000-01-01 : 2001-01-01"), + ] + + +def test_time_range_bounds_a_custom_sql_x_axis_on_another_column() -> None: + """An expression x-axis keeps the range when the main datetime differs.""" + axis: dict[str, str] = {"sqlExpression": "created_at", "label": "created_at"} + query = _create_with_time_range( + [{"columnType": "BASE_AXIS", **axis}], + [{"col": "created_at", "op": "TEMPORAL_RANGE", "val": "No filter"}], + {"expressionType": "SQL", **axis}, + ) + assert query.granularity == "ds" + assert [(flt["col"], flt["val"]) for flt in query.filter] == [ + ("created_at", "2024-01-01 : 2025-01-01"), + ] + + +def test_time_range_adds_a_filter_for_a_temporal_x_axis_without_one() -> None: + """The range bounds the x-axis rather than another datetime column.""" + query = _create_with_time_range( + [{"columnType": "BASE_AXIS", "label": "ds", "sqlExpression": "ds"}], + [ + { + "col": "created_at", + "op": "TEMPORAL_RANGE", + "val": "2000-01-01 : 2001-01-01", + } + ], + "ds", + ) + assert query.filter == [ + { + "col": "ds", + "op": "TEMPORAL_RANGE", + "val": "2024-01-01 : 2025-01-01", + "isExtra": True, + }, + {"col": "created_at", "op": "TEMPORAL_RANGE", "val": "2000-01-01 : 2001-01-01"}, + ] + + +def test_time_range_rewrites_every_filter_for_a_categorical_x_axis() -> None: + """A non-temporal x-axis leaves no known time column to scope the range.""" + query = _create_with_time_range( + [{"columnType": "BASE_AXIS", "label": "country", "sqlExpression": "country"}], + [ + { + "col": "created_at", + "op": "TEMPORAL_RANGE", + "val": "2000-01-01 : 2001-01-01", + } + ], + "country", + ) + assert [(flt["col"], flt["val"]) for flt in query.filter] == [ + ("created_at", "2024-01-01 : 2025-01-01"), + ] + + +def _create(query: dict[str, Any], form_data: dict[str, Any]) -> QueryObject: + with patch( + "superset.daos.datasource.DatasourceDAO.get_datasource", + return_value=_two_datetime_dataset(), + ): + context = QueryContextFactory().create( + datasource={"id": 1, "type": "table"}, + queries=[{"metrics": ["count"], **query}], + form_data=form_data, + ) + return context.queries[0] + + +def test_time_range_follows_the_x_axis_of_a_query_without_columns() -> None: + """Drill to Detail keeps the chart's other datetime ranges, as the chart does.""" + query = _create( + { + "time_range": "2024-01-01 : 2025-01-01", + "filters": [ + {"col": "ds", "op": "TEMPORAL_RANGE", "val": "No filter"}, + { + "col": "created_at", + "op": "TEMPORAL_RANGE", + "val": "2000-01-01 : 2001-01-01", + }, + ], + }, + {"x_axis": "ds", "viz_type": "echarts_timeseries_bar"}, + ) + assert [(flt["col"], flt["val"]) for flt in query.filter] == [ + ("ds", "2024-01-01 : 2025-01-01"), + ("created_at", "2000-01-01 : 2001-01-01"), + ] + + +def test_time_range_ignores_a_temporal_groupby_without_an_x_axis() -> None: + """A table's temporal groupby is not its time column, as in its totals query.""" + query = _create( + { + "columns": [ + { + "timeGrain": "P1D", + "columnType": "BASE_AXIS", + "label": "created_at", + "sqlExpression": "created_at", + } + ], + "time_range": "2024-01-01 : 2025-01-01", + "filters": [{"col": "ds", "op": "TEMPORAL_RANGE", "val": "No filter"}], + }, + {"viz_type": "table"}, + ) + assert [(flt["col"], flt["val"]) for flt in query.filter] == [ + ("ds", "2024-01-01 : 2025-01-01"), + ] + + +def test_time_column_on_a_table_takes_the_saved_range() -> None: + """Without an x-axis, a temporal groupby does not discard the saved range.""" + query = _create( + { + "columns": [ + { + "timeGrain": "P1D", + "columnType": "BASE_AXIS", + "label": "created_at", + "sqlExpression": "created_at", + } + ], + "granularity": "created_at", + "filters": [ + {"col": "ds", "op": "TEMPORAL_RANGE", "val": "2000-01-01 : 2001-01-01"} + ], + }, + {"viz_type": "table"}, + ) + assert query.from_dttm == datetime(2000, 1, 1) + + +def test_time_range_bounds_the_column_under_a_custom_sql_x_axis() -> None: + """A Custom SQL x-axis takes the range on the datetime column it reads.""" + axis: dict[str, str] = {"sqlExpression": "DATE(created_at)", "label": "day"} + query = _create( + { + "columns": [{"columnType": "BASE_AXIS", **axis}], + "time_range": "2024-01-01 : 2025-01-01", + "filters": [ + {"col": "created_at", "op": "TEMPORAL_RANGE", "val": "No filter"} + ], + }, + {"x_axis": {"expressionType": "SQL", **axis}}, + ) + assert query.granularity == "ds" + assert [(flt["col"], flt["val"]) for flt in query.filter] == [ + ("created_at", "2024-01-01 : 2025-01-01"), + ] + + +def test_cross_filter_range_lands_on_the_cross_filtered_column() -> None: + """A clicked time bucket replaces ranges on its column, not the target's axis.""" + bucket = "2024-03-01 00:00:00 : 2024-04-01 00:00:00" + cross_filter: dict[str, Any] = {"col": "ds", "op": "TEMPORAL_RANGE", "val": bucket} + query = _create( + { + "columns": [ + { + "columnType": "BASE_AXIS", + "label": "created_at", + "sqlExpression": "created_at", + } + ], + "time_range": bucket, + "filters": [ + {"col": "ds", "op": "TEMPORAL_RANGE", "val": "2020-01-01 : 2021-01-01"}, + {"col": "created_at", "op": "TEMPORAL_RANGE", "val": "Last year"}, + {**cross_filter, "isExtra": True}, + ], + }, + { + "x_axis": "created_at", + "extra_form_data": {"filters": [cross_filter], "time_range": bucket}, + }, + ) + assert [(flt["col"], flt["val"]) for flt in query.filter] == [ + ("ds", bucket), + ("created_at", "Last year"), + ("ds", bucket), + ] + + +def test_stored_query_with_an_x_axis_key_is_accepted() -> None: + """A stored query dict carrying ``x_axis`` does not clash with the form data's.""" + query = _create( + { + "x_axis": "created_at", + "columns": [ + {"columnType": "BASE_AXIS", "label": "ds", "sqlExpression": "ds"} + ], + "time_range": "2024-01-01 : 2025-01-01", + "filters": [ + {"col": "ds", "op": "TEMPORAL_RANGE", "val": "No filter"}, + {"col": "created_at", "op": "TEMPORAL_RANGE", "val": "Last year"}, + ], + }, + {"x_axis": "ds"}, + ) + assert [(flt["col"], flt["val"]) for flt in query.filter] == [ + ("ds", "2024-01-01 : 2025-01-01"), + ("created_at", "Last year"), + ] diff --git a/tests/unit_tests/common/test_query_context_processor.py b/tests/unit_tests/common/test_query_context_processor.py index fed270d28171..b177d6a4cee9 100644 --- a/tests/unit_tests/common/test_query_context_processor.py +++ b/tests/unit_tests/common/test_query_context_processor.py @@ -17,7 +17,7 @@ from datetime import datetime, timedelta from decimal import Decimal -from typing import Any +from typing import Any, cast from unittest.mock import MagicMock, patch, PropertyMock import numpy as np @@ -3771,3 +3771,228 @@ def test_get_query_result_discards_a_result_stopped_mid_statement() -> None: mock_datasource.get_query_result.assert_called_once() assert result.status == QueryStatus.FAILED assert result.df.empty + + +def _captured_offset_filters( + processor: QueryContextProcessor, + offset: str, + column: dict[str, Any] | str, + index: pd.Series, + filters: list[dict[str, Any]], +) -> list[dict[str, Any]]: + """Run one time offset and return the filters of the comparison query.""" + return _captured_offset_query(processor, offset, column, index, filters)["filter"] + + +def _captured_offset_query( + processor: QueryContextProcessor, + offset: str, + column: dict[str, Any] | str, + index: pd.Series, + filters: list[dict[str, Any]], + granularity: str | None = None, + temporal_columns: tuple[str, ...] = (), +) -> dict[str, Any]: + """Run one time offset and return the comparison query.""" + from types import SimpleNamespace + + from superset.common.query_object import QueryObject + from superset.models.helpers import ExploreMixin + + datasource: Any = processor._qc_datasource + datasource.columns = [ + SimpleNamespace(column_name=name, is_dttm=True) for name in temporal_columns + ] + label: str = column if isinstance(column, str) else column["label"] + for method in ( + "processing_time_offsets", + "_align_offset_without_time_grain", + "_coalesce_offset_index", + "_get_temporal_column_for_filter", + "is_valid_date_range", + ): + setattr(datasource, method, getattr(ExploreMixin, method).__get__(datasource)) + query_object = QueryObject( + datasource=MagicMock(), + columns=[cast(Any, column)], + metrics=["sum__num"], + granularity=granularity, + time_range="2024-04-01 : 2024-07-01", + time_offsets=[offset], + filters=cast(Any, filters), + ) + captured: list[dict[str, Any]] = [] + + def fake_query(dct: dict[str, Any]) -> MagicMock: + captured.append(dct) + result = MagicMock() + result.df = pd.DataFrame({label: index, "sum__num": [1.0] * len(index)}) + result.query = "SELECT 1" + return result + + datasource.query = fake_query + datasource.normalize_df = MagicMock( + side_effect=lambda offset_df, _query_object, _labels=None: offset_df + ) + with ( + patch("superset.models.helpers.feature_flag_manager") as flags, + patch( + "superset.common.utils.query_cache_manager.QueryCacheManager" + ) as cache_manager, + patch.object(datasource, "get_time_grain", return_value=None), + ): + flags.is_feature_enabled.return_value = True + cache_manager.get.return_value = MagicMock(is_loaded=False) + datasource.processing_time_offsets( + pd.DataFrame({label: index, "sum__num": [1.0] * len(index)}), + query_object, + None, + None, + False, + ) + return captured[0] + + +_SECONDARY_RANGE: dict[str, Any] = { + "col": "created_at", + "op": "TEMPORAL_RANGE", + "val": "2000-01-01 : 2001-01-01", +} + + +def test_date_range_offset_keeps_other_datetime_ranges( + processor: QueryContextProcessor, +) -> None: + """The comparison replaces the time range only, as the main query applies it.""" + filters = _captured_offset_filters( + processor, + "2024-01-01 : 2024-04-01", + {"columnType": "BASE_AXIS", "label": "ds", "sqlExpression": "ds"}, + pd.Series(pd.to_datetime(["2024-04-01", "2024-05-01"])), + [ + {"col": "ds", "op": "TEMPORAL_RANGE", "val": "2024-04-01 : 2024-07-01"}, + dict(_SECONDARY_RANGE), + ], + ) + assert [(flt["col"], flt["val"]) for flt in filters] == [ + ("created_at", "2000-01-01 : 2001-01-01"), + ("ds", "2024-01-01 00:00:00 : 2024-04-01 00:00:00"), + ] + + +def test_relative_offset_shifts_only_the_time_range( + processor: QueryContextProcessor, +) -> None: + """Other datetime ranges are not shifted when the index is not temporal.""" + filters = _captured_offset_filters( + processor, + "1 year ago", + "country", + pd.Series(["a", "b"]), + [ + {"col": "ds", "op": "TEMPORAL_RANGE", "val": "2024-04-01 : 2024-07-01"}, + dict(_SECONDARY_RANGE), + ], + ) + assert [(flt["col"], flt["val"]) for flt in filters] == [ + ("ds", "2023-04-01 00:00:00 : 2023-07-01 00:00:00"), + ("created_at", "2000-01-01 : 2001-01-01"), + ] + + +_X_AXIS_RANGE: dict[str, Any] = { + "col": "ds", + "op": "TEMPORAL_RANGE", + "val": "2024-04-01 : 2024-07-01", +} + + +def test_date_range_offset_replaces_the_x_axis_range_listed_after_another( + processor: QueryContextProcessor, +) -> None: + """The compared column is the x-axis, not the first temporal filter listed.""" + filters = _captured_offset_filters( + processor, + "2024-01-01 : 2024-04-01", + {"columnType": "BASE_AXIS", "label": "ds", "sqlExpression": "ds"}, + pd.Series(pd.to_datetime(["2024-04-01", "2024-05-01"])), + [dict(_SECONDARY_RANGE), dict(_X_AXIS_RANGE)], + ) + assert [(flt["col"], flt["val"]) for flt in filters] == [ + ("created_at", "2000-01-01 : 2001-01-01"), + ("ds", "2024-01-01 00:00:00 : 2024-04-01 00:00:00"), + ] + + +def test_relative_offset_shifts_the_x_axis_range_listed_after_another( + processor: QueryContextProcessor, +) -> None: + """Shifting another column's range would leave the series empty.""" + query = _captured_offset_query( + processor, + "1 year ago", + {"columnType": "BASE_AXIS", "label": "ds", "sqlExpression": "ds"}, + pd.Series(pd.to_datetime(["2024-04-01", "2024-05-01"])), + [dict(_SECONDARY_RANGE), dict(_X_AXIS_RANGE)], + ) + assert query["granularity"] == "ds" + assert (query["from_dttm"], query["to_dttm"]) == ( + datetime(2023, 4, 1), + datetime(2023, 7, 1), + ) + assert [(flt["col"], flt["val"]) for flt in query["filter"]] == [ + ("created_at", "2000-01-01 : 2001-01-01"), + ("ds", "2023-04-01 00:00:00 : 2023-07-01 00:00:00"), + ] + + +def test_offset_shifts_the_time_column_not_another_datetime_range( + processor: QueryContextProcessor, +) -> None: + """With a Time Column and a categorical axis, other ranges are kept.""" + query = _captured_offset_query( + processor, + "1 year ago", + "country", + pd.Series(["a", "b"]), + [dict(_SECONDARY_RANGE)], + granularity="ds", + ) + assert query["granularity"] == "ds" + assert [(flt["col"], flt["val"]) for flt in query["filter"]] == [ + ("created_at", "2000-01-01 : 2001-01-01"), + ] + + +def test_date_range_offset_bounds_the_column_a_custom_sql_axis_reads( + processor: QueryContextProcessor, +) -> None: + """A Custom SQL x-axis compares on the datetime column it reads.""" + query = _captured_offset_query( + processor, + "2024-01-01 : 2024-04-01", + {"columnType": "BASE_AXIS", "label": "day", "sqlExpression": "DATE(ds)"}, + pd.Series(pd.to_datetime(["2024-04-01", "2024-05-01"])), + [dict(_SECONDARY_RANGE), dict(_X_AXIS_RANGE)], + temporal_columns=("ds", "created_at"), + ) + assert [(flt["col"], flt["val"]) for flt in query["filter"]] == [ + ("created_at", "2000-01-01 : 2001-01-01"), + ("ds", "2024-01-01 00:00:00 : 2024-04-01 00:00:00"), + ] + + +def test_get_temporal_column_for_filter_keeps_the_first_filter_fallback( + processor: QueryContextProcessor, +) -> None: + """Without a known time column, the first temporal filter is compared.""" + query_object = MagicMock( + filter=[dict(_SECONDARY_RANGE), dict(_X_AXIS_RANGE)], + columns=["country"], + granularity=None, + time_range=None, + ) + datasource: Any = processor._qc_datasource + assert ( + datasource._get_temporal_column_for_filter(query_object, None) == "created_at" + ) diff --git a/tests/unit_tests/common/test_time_range_utils.py b/tests/unit_tests/common/test_time_range_utils.py index def4f9cbc81c..b0133af17871 100644 --- a/tests/unit_tests/common/test_time_range_utils.py +++ b/tests/unit_tests/common/test_time_range_utils.py @@ -14,12 +14,14 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. +import time from datetime import datetime from unittest import mock import pytest from superset.common.utils.time_range_utils import ( + get_axis_temporal_columns, get_since_until_from_query_object, get_since_until_from_temporal_filter, get_since_until_from_time_range, @@ -27,6 +29,7 @@ ) from superset.constants import NO_TIME_RANGE from superset.exceptions import QueryObjectValidationError +from superset.superset_typing import AdhocColumn @pytest.mark.parametrize("invalid_value", [None, 42, True, [], ["2001 : 2002"], {}]) @@ -88,6 +91,73 @@ def test_time_range_selection_ignores_missing_value() -> None: ) +def test_time_range_selection_ignores_other_columns_for_axis() -> None: + """A temporal x-axis without its own range does not borrow another column's.""" + axis: AdhocColumn = { + "columnType": "BASE_AXIS", + "label": "ds", + "sqlExpression": "ds", + } + filters: list[dict[str, object]] = [ + {"col": "created_at", "op": "TEMPORAL_RANGE", "val": "2000 : 2001"}, + ] + assert get_time_range_from_filters(None, filters, [axis]) == NO_TIME_RANGE + + +def test_time_range_selection_matches_axis_expression() -> None: + """A filter on the axis expression selects it when none targets the label.""" + axis: AdhocColumn = { + "columnType": "BASE_AXIS", + "label": "dttm2", + "sqlExpression": "dttm", + } + filters: list[dict[str, object]] = [ + {"col": "other", "op": "TEMPORAL_RANGE", "val": "2000 : 2001"}, + {"col": "dttm", "op": "TEMPORAL_RANGE", "val": "2001 : 2002"}, + ] + assert get_time_range_from_filters(None, filters, [axis]) == "2001 : 2002" + + +def test_time_range_selection_matches_adhoc_filter_column() -> None: + """An adhoc column subject is matched by its label or expression.""" + axis: AdhocColumn = { + "columnType": "BASE_AXIS", + "label": "ds", + "sqlExpression": "ds", + } + filters: list[dict[str, object]] = [ + {"col": "other", "op": "TEMPORAL_RANGE", "val": "2000 : 2001"}, + { + "col": {"label": "ds", "sqlExpression": "ds"}, + "op": "TEMPORAL_RANGE", + "val": "2001 : 2002", + }, + ] + assert get_time_range_from_filters(None, filters, [axis]) == "2001 : 2002" + + +def test_time_range_selection_matches_the_column_a_custom_sql_axis_reads() -> None: + """A Custom SQL x-axis takes the range on the datetime column it reads.""" + axis: AdhocColumn = { + "columnType": "BASE_AXIS", + "label": "day", + "sqlExpression": 'DATE("created_at")', + } + filters: list[dict[str, object]] = [ + {"col": "ds", "op": "TEMPORAL_RANGE", "val": "2000 : 2001"}, + {"col": "created_at", "op": "TEMPORAL_RANGE", "val": "2001 : 2002"}, + ] + temporal_columns: set[str] = {"ds", "created_at"} + assert ( + get_time_range_from_filters(None, filters, [axis], temporal_columns) + == "2001 : 2002" + ) + assert ( + get_time_range_from_filters(None, filters[:1], [axis], temporal_columns) + == NO_TIME_RANGE + ) + + def test__get_since_until_from_time_range(): assert get_since_until_from_time_range(time_range="2001 : 2002") == ( datetime(2001, 1, 1), @@ -155,3 +225,25 @@ def test__since_until_from_adhoc_filters(dummy_query_object): datetime(2001, 1, 1, 0, 0, 0), datetime(2002, 1, 1, 0, 0, 0), ) + + +@pytest.mark.parametrize("opener", ['"', "`", "["]) +def test_axis_columns_scan_an_unterminated_quote_in_linear_time(opener: str) -> None: + """A client-supplied axis with unterminated quotes does not stall the scan.""" + axis: AdhocColumn = {"label": "day", "sqlExpression": opener * 40_000 + " ds"} + started: float = time.perf_counter() + assert get_axis_temporal_columns(axis, {"ds"}) == ("ds",) + assert time.perf_counter() - started < 1 + + +def test_axis_columns_read_quoted_names() -> None: + """Quoted, backticked and bracketed names resolve to their datetime columns.""" + axis: AdhocColumn = { + "label": "day", + "sqlExpression": 'COALESCE("ds", `created_at`, [shipped at], country)', + } + assert get_axis_temporal_columns(axis, {"ds", "created_at", "shipped at"}) == ( + "ds", + "created_at", + "shipped at", + ) diff --git a/tests/unit_tests/semantic_layers/mapper_test.py b/tests/unit_tests/semantic_layers/mapper_test.py index a34519f3ffc8..177c3794989f 100644 --- a/tests/unit_tests/semantic_layers/mapper_test.py +++ b/tests/unit_tests/semantic_layers/mapper_test.py @@ -6144,3 +6144,39 @@ def test_group_limit_requires_projected_enum_grant( QueryObjectValidationError, match="Group limit is not supported" ): validate_query_object(query) + + +def test_axis_range_matches_the_factory_for_a_categorical_axis( + app_context: None, +) -> None: + """The range the factory took for a categorical x-axis is not applied twice.""" + from types import SimpleNamespace + + from superset.semantic_layers.mapper import _get_adhoc_filters + + query = QueryObject( + columns=[ + { + "columnType": "BASE_AXIS", + "label": "category", + "sqlExpression": "category", + } + ], + filters=[{"col": "order_date", "op": "TEMPORAL_RANGE", "val": "Last week"}], + ) + query.datasource = cast( + Any, + SimpleNamespace( + columns=[ + SimpleNamespace(column_name="order_date", is_dttm=True), + SimpleNamespace(column_name="category", is_dttm=False), + ] + ), + ) + dimensions = { + "order_date": Dimension("orders.order_date", "order_date", pa.date32()) + } + assert ( + _get_adhoc_filters(cast(ValidatedQueryObject, query), dimensions, "order_date") + == set() + ) diff --git a/tests/unit_tests/views/datasource/test_utils.py b/tests/unit_tests/views/datasource/test_utils.py index 649d46754d69..bc32613baf9d 100644 --- a/tests/unit_tests/views/datasource/test_utils.py +++ b/tests/unit_tests/views/datasource/test_utils.py @@ -766,3 +766,19 @@ def test_get_samples_failure_without_error_text_keeps_the_default_message( assert "None" not in str(excinfo.value) assert str(excinfo.value) == DatasetSamplesFailedError.message datasource.database.db_engine_spec.extract_errors.assert_not_called() + + +@pytest.mark.parametrize( + "x_axis", ["ds", {"label": "day", "sqlExpression": "DATE(created_at)"}] +) +def test_samples_form_data_carries_the_chart_x_axis(x_axis: object) -> None: + """Drill to Detail scopes a time range to the chart's x-axis, as the chart does.""" + from superset.views.datasource import utils + from superset.views.datasource.schemas import SamplesPayloadSchema + + payload = SamplesPayloadSchema().load( + {"x_axis": x_axis, "time_range": "Last week", "filters": []} + ) + query, form_data = utils._split_samples_form_data(payload, None) + assert query == {"time_range": "Last week", "filters": []} + assert form_data == {"x_axis": x_axis}