Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions UPDATING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Comment on lines +144 to +145

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: Without a known time column the range lands only on the unbounded TEMPORAL_RANGE filters when one exists, so a categorical x-axis keeps a saved created_at range; every filter takes it only when none is unbounded.

Suggested change
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
from another datetime column. Charts with no known time column apply a time
range to their unbounded `TEMPORAL_RANGE` filters, or else to every one. 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand Down
18 changes: 18 additions & 0 deletions superset-frontend/src/components/Chart/DrillDetail/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
2 changes: 2 additions & 0 deletions superset-frontend/src/components/Chart/DrillDetail/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
118 changes: 103 additions & 15 deletions superset/common/query_context_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,24 @@
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
from superset.extensions import security_manager
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:
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"))
}
Comment on lines +534 to +545

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Drill to Detail sends no extra_form_data, so on a time cross-filter target whose x-axis is created_at this set is empty: the drill rewrites created_at to the bucket and keeps the saved ds range, while the chart does the reverse, so the detail rows differ or come back empty.

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"]))
]
Comment thread
aminghadersohi marked this conversation as resolved.
Resolved
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)
Comment thread
aminghadersohi marked this conversation as resolved.
Resolved
targets = [axis_filter]
else:
targets = temporal_filters
Comment on lines +583 to +584

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Drill to Detail sends no x-axis column, so it reaches this branch and overwrites every TEMPORAL_RANGE filter, while the chart query keeps other datetime columns' own ranges; with a dashboard time range the detail rows no longer match the clicked bar.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The dashboard time range case holds at 16716e0; a time cross-filter target's drill still diverges from the chart, see the new comment at query_context_factory.py:534.

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
23 changes: 21 additions & 2 deletions superset/common/query_object_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,15 @@
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
from superset.utils.core import (
apply_max_row_limit,
DatasourceDict,
DatasourceType,
get_base_axis_columns,
QueryObjectFilterClause,
)

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading