You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by be...@apache.org on 2025/10/25 20:52:18 UTC
(superset) 02/03: WIP filters inner
This is an automated email from the ASF dual-hosted git repository.
beto pushed a commit to branch explorable
in repository https://gitbox.apache.org/repos/asf/superset.git
commit d14bcba501daee1eed0f85411f4ede806e053e24
Author: Beto Dealmeida <ro...@dealmeida.net>
AuthorDate: Wed Oct 22 17:04:32 2025 -0400
WIP filters inner
---
superset/semantic_layers/mapper.py | 71 ++++++++++++++++++++++++++++++++++
superset/semantic_layers/snowflake_.py | 69 +++++++++++++++++++++++++++------
superset/semantic_layers/types.py | 8 ++++
3 files changed, 136 insertions(+), 12 deletions(-)
diff --git a/superset/semantic_layers/mapper.py b/superset/semantic_layers/mapper.py
index f28b0bf65e..0cd83d61cf 100644
--- a/superset/semantic_layers/mapper.py
+++ b/superset/semantic_layers/mapper.py
@@ -306,15 +306,86 @@ def _get_group_limit_from_query_object(
direction = OrderDirection.DESC if query_object.order_desc else OrderDirection.ASC
group_others = query_object.group_others_when_limit_reached
+ # Check if we need separate filters for the group limit subquery
+ # This happens when inner_from_dttm/inner_to_dttm differ from from_dttm/to_dttm
+ group_limit_filters = _get_group_limit_filters(query_object, all_dimensions)
+
return GroupLimit(
dimensions=dimensions,
top=top,
metric=metric,
direction=direction,
group_others=group_others,
+ filters=group_limit_filters,
)
+def _get_group_limit_filters(
+ query_object: QueryObject,
+ all_dimensions: dict[str, Dimension],
+) -> set[Filter | AdhocFilter] | None:
+ """
+ Get separate filters for the group limit subquery if needed.
+
+ This is used when inner_from_dttm/inner_to_dttm differ from from_dttm/to_dttm,
+ which happens during time comparison queries. The group limit subquery may need
+ different time bounds to determine the top N groups.
+
+ Returns None if the group limit should use the same filters as the main query.
+ """
+ # Check if inner time bounds are explicitly set and differ from outer bounds
+ if (
+ query_object.inner_from_dttm is None
+ or query_object.inner_to_dttm is None
+ or (
+ query_object.inner_from_dttm == query_object.from_dttm
+ and query_object.inner_to_dttm == query_object.to_dttm
+ )
+ ):
+ # No separate bounds needed - use the same filters as the main query
+ return None
+
+ # Create separate filters for the group limit subquery
+ filters: set[Filter | AdhocFilter] = set()
+
+ # Add time range filter using inner bounds
+ if query_object.granularity:
+ time_dimension = all_dimensions.get(query_object.granularity)
+ if time_dimension and query_object.inner_from_dttm and query_object.inner_to_dttm:
+ filters.add(
+ Filter(
+ type=PredicateType.WHERE,
+ column=time_dimension,
+ operator=Operator.GREATER_THAN_OR_EQUAL,
+ value=(query_object.inner_from_dttm, query_object.inner_to_dttm),
+ )
+ )
+
+ # Add fetch values predicate if present
+ if (
+ query_object.apply_fetch_values_predicate
+ and query_object.datasource.fetch_values_predicate
+ ):
+ filters.add(
+ AdhocFilter(
+ type=PredicateType.WHERE,
+ definition=query_object.datasource.fetch_values_predicate,
+ )
+ )
+
+ # Add all other non-temporal filters from query_object.filter
+ for filter_ in query_object.filter:
+ # Skip temporal range filters - we're using inner bounds instead
+ if filter_.get("op") == FilterOperator.TEMPORAL_RANGE.value:
+ continue
+
+ converted_filter = _convert_query_object_filter(filter_, all_dimensions)
+ if converted_filter:
+ filters.add(converted_filter)
+
+ return filters if filters else None
+
+
def _convert_time_grain(time_grain: str) -> TimeGrain | DateGrain | None:
"""
Convert a time grain string from the query object to a TimeGrain or DateGrain enum.
diff --git a/superset/semantic_layers/snowflake_.py b/superset/semantic_layers/snowflake_.py
index da75bcdbbd..2f8b5b9169 100644
--- a/superset/semantic_layers/snowflake_.py
+++ b/superset/semantic_layers/snowflake_.py
@@ -780,7 +780,7 @@ class SnowflakeSemanticView:
)
if group_limit:
- query = self._build_query_with_group_limit(
+ query, cte_parameters = self._build_query_with_group_limit(
metrics,
dimensions,
where_clause,
@@ -790,6 +790,8 @@ class SnowflakeSemanticView:
offset,
group_limit,
)
+ # Combine parameters: CTE params first, then main query params
+ all_parameters = cte_parameters + where_parameters + having_parameters
else:
query = self._build_simple_query(
metrics,
@@ -800,8 +802,9 @@ class SnowflakeSemanticView:
limit,
offset,
)
+ all_parameters = where_parameters + having_parameters
- return query, where_parameters + having_parameters
+ return query, all_parameters
def _alias_element(self, element: Metric | Dimension) -> str:
"""
@@ -886,9 +889,16 @@ class SnowflakeSemanticView:
group_limit: GroupLimit,
where_clause: str,
having_clause: str,
- ) -> str:
+ ) -> tuple[str, tuple[FilterValues, ...]]:
"""
Build a CTE that finds the top N combinations of limited dimensions.
+
+ If group_limit.filters is set, it uses those filters instead of the main
+ query's where_clause/having_clause. This allows using different time bounds
+ for finding top groups vs showing data.
+
+ Returns:
+ Tuple of (CTE SQL, parameters for the CTE)
"""
limited_dimension_arguments = ", ".join(
self._alias_element(dimension) for dimension in group_limit.dimensions
@@ -897,7 +907,30 @@ class SnowflakeSemanticView:
self._quote(dimension.id) for dimension in group_limit.dimensions
)
- return dedent(
+ # Use separate filters for group limit if provided (Option 2)
+ # Otherwise use the same filters as the main query (Option 1)
+ if group_limit.filters is not None:
+ group_where_clause, group_where_params = self._build_predicates(
+ {
+ filter_
+ for filter_ in group_limit.filters
+ if filter_.type == PredicateType.WHERE
+ }
+ )
+ group_having_clause, group_having_params = self._build_predicates(
+ {
+ filter_
+ for filter_ in group_limit.filters
+ if filter_.type == PredicateType.HAVING
+ }
+ )
+ cte_params = group_where_params + group_having_params
+ else:
+ group_where_clause = where_clause
+ group_having_clause = having_clause
+ cte_params = () # No additional params - using main query params
+
+ cte_sql = dedent(
f"""
WITH top_groups AS (
SELECT {limited_dimension_names}
@@ -906,9 +939,9 @@ class SnowflakeSemanticView:
DIMENSIONS {limited_dimension_arguments}
METRICS {group_limit.metric.id}
AS {self._quote(group_limit.metric.id)}
- {"WHERE " + where_clause if where_clause else ""}
+ {"WHERE " + group_where_clause if group_where_clause else ""}
)
- {"HAVING " + having_clause if having_clause else ""}
+ {"HAVING " + group_having_clause if group_having_clause else ""}
ORDER BY
{self._quote(group_limit.metric.id)} {group_limit.direction.value}
LIMIT {group_limit.top}
@@ -916,6 +949,8 @@ class SnowflakeSemanticView:
"""
)
+ return cte_sql, cte_params
+
def _build_group_filter(self, group_limit: GroupLimit) -> str:
"""
Build a WHERE filter that restricts results to top N groups.
@@ -962,7 +997,7 @@ class SnowflakeSemanticView:
limit: int | None,
offset: int | None,
group_limit: GroupLimit,
- ) -> str:
+ ) -> tuple[str, tuple[FilterValues, ...]]:
"""
Build a query that groups non-top N values as 'Other'.
@@ -970,8 +1005,11 @@ class SnowflakeSemanticView:
1. CTE to find top N groups
2. Subquery with CASE expressions to replace non-top values with 'Other'
3. Outer query to re-aggregate with the new grouping
+
+ Returns:
+ Tuple of (SQL query, CTE parameters)
"""
- top_groups_cte = self._build_top_groups_cte(
+ top_groups_cte, cte_params = self._build_top_groups_cte(
group_limit,
where_clause,
having_clause,
@@ -1054,7 +1092,7 @@ class SnowflakeSemanticView:
# Build ORDER BY clause (need to reference the aliased columns)
order_clause = self._build_order_clause(order)
- return dedent(
+ query = dedent(
f"""
{top_groups_cte},
{subquery}
@@ -1068,6 +1106,8 @@ class SnowflakeSemanticView:
"""
)
+ return query, cte_params
+
def _build_query_with_group_limit(
self,
metrics: list[Metric],
@@ -1078,12 +1118,15 @@ class SnowflakeSemanticView:
limit: int | None,
offset: int | None,
group_limit: GroupLimit,
- ) -> str:
+ ) -> tuple[str, tuple[FilterValues, ...]]:
"""
Build a query with group limiting (top N groups).
If group_others is True, groups non-top values as 'Other'.
Otherwise, filters to show only top N groups.
+
+ Returns:
+ Tuple of (SQL query, CTE parameters)
"""
if group_limit.group_others:
return self._build_query_with_others(
@@ -1105,14 +1148,14 @@ class SnowflakeSemanticView:
metric_arguments = ", ".join(self._alias_element(metric) for metric in metrics)
order_clause = self._build_order_clause(order)
- top_groups_cte = self._build_top_groups_cte(
+ top_groups_cte, cte_params = self._build_top_groups_cte(
group_limit,
where_clause,
having_clause,
)
group_filter = self._build_group_filter(group_limit)
- return dedent(
+ query = dedent(
f"""
{top_groups_cte}
SELECT * FROM (
@@ -1131,6 +1174,8 @@ class SnowflakeSemanticView:
"""
)
+ return query, cte_params
+
__repr__ = uid
diff --git a/superset/semantic_layers/types.py b/superset/semantic_layers/types.py
index 758d28d244..39d7bea01d 100644
--- a/superset/semantic_layers/types.py
+++ b/superset/semantic_layers/types.py
@@ -222,6 +222,13 @@ OrderTuple = tuple[Metric | Dimension | AdhocExpression, OrderDirection]
class GroupLimit:
"""
Limit query to top/bottom N combinations of specified dimensions.
+
+ The `filters` parameter allows specifying separate filter constraints for the
+ group limit subquery. This is useful when you want to determine the top N groups
+ using different criteria (e.g., a different time range) than the main query.
+
+ For example, you might want to find the top 10 products by sales over the last
+ 30 days, but then show daily sales for those products over the last 7 days.
"""
dimensions: list[Dimension]
@@ -229,6 +236,7 @@ class GroupLimit:
metric: Metric | None
direction: OrderDirection = OrderDirection.DESC
group_others: bool = False
+ filters: set["Filter | AdhocFilter"] | None = None
@dataclass(frozen=True)