rusackas commented on code in PR #41184: URL: https://github.com/apache/superset/pull/41184#discussion_r3565320217
########## superset/common/grouping_sets.py: ########## @@ -0,0 +1,116 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +""" +SQL building blocks for the pivot-table non-additive totals optimization +(SIP.md, phase 3b). When a datasource engine reports +``supports_grouping_sets``, the N per-rollup-level queries can be collapsed into +a single ``GROUPING SETS`` query: the database computes every level in one scan, +and each returned row is attributed to its level via ``GROUPING()`` markers. + +These are the engine-agnostic SQL primitives. Wiring them into the query context +(emitting one query and splitting the result back into per-level results) is the +remaining integration; see SIP.md. +""" + +from __future__ import annotations + +from collections.abc import Sequence + +import pandas as pd +from sqlalchemy import func, tuple_ +from sqlalchemy.sql.elements import ColumnElement + +# Suffix for the per-column GROUPING() marker columns added to a GROUPING SETS +# query. Chosen to be unlikely to collide with a real metric/column label. +GROUPING_MARKER_SUFFIX = "__superset_grouping" Review Comment: Annotated it as `Final` in ef6691c. ########## superset/common/query_context_processor.py: ########## @@ -252,9 +256,60 @@ def get_query_result(self, query_object: QueryObject) -> QueryResult: This method delegates to the datasource's get_query_result method, which handles query execution, normalization, time offsets, and post-processing. + + When the query requests rollup ``grouping_sets`` but the engine does not + support native ``GROUPING SETS``, fall back to one query per level and + concatenate the results with ``GROUPING()``-equivalent markers, so the + combined result matches the shape the native path produces (SIP.md, + phase 3b). Engines that support it run the single native query. """ + if query_object.grouping_sets and not self._supports_grouping_sets(): + return self._grouping_sets_fallback(query_object) return self._qc_datasource.get_query_result(query_object) + def _supports_grouping_sets(self) -> bool: + engine_spec: BaseEngineSpec | None = getattr( + self._qc_datasource, "db_engine_spec", None + ) + return bool(engine_spec and engine_spec.supports_grouping_sets) + + def _grouping_sets_fallback(self, query_object: QueryObject) -> QueryResult: + """ + Emulate a GROUPING SETS query on engines without native support: run one + query per rollup level and concatenate, tagging each level's rows with + the same per-column markers the native path emits. + """ + levels: list[list[str]] = query_object.grouping_sets + # Use the same label derivation as the native path (physical column name + # or adhoc column label) so both column kinds are represented and each + # label maps back to its own column, in the same order as the source + # list. + all_labels = [get_column_name(col) for col in query_object.columns] Review Comment: Added the `list[str]` annotation in ef6691c. ########## superset/db_engine_specs/hive.py: ########## @@ -96,6 +96,11 @@ class HiveEngineSpec(PrestoEngineSpec): supports_dynamic_schema = True supports_cross_catalog_queries = False + # Explicitly opt out (overriding the inherited PrestoEngineSpec value): + # Hive/Spark's GROUPING SETS + GROUPING() marker semantics have not been + # verified against this query pattern, so fall back to one query per + # rollup level instead of assuming native support. + supports_grouping_sets = False Review Comment: Annotated as `bool` in ef6691c. ########## superset-frontend/plugins/plugin-chart-pivot-table/test/plugin/buildQuery.test.ts: ########## @@ -56,9 +55,41 @@ const formData: PivotTableQueryFormData = { currencyFormat: { symbol: 'USD', symbolPosition: 'prefix' }, }; -test('should build groupby with series in form data', () => { +test('additive metrics use the fast-path: a single full-detail query', () => { + const { queries } = buildQuery({ + ...formData, + metrics: [ + { + expressionType: 'SIMPLE', + aggregate: 'SUM', + column: { column_name: 'num' }, + label: 'sum_num', + }, + ] as any, + }); Review Comment: Typed the fixture as `QueryFormMetric[]` in ef6691c. ########## superset-frontend/plugins/plugin-chart-pivot-table/test/plugin/buildQuery.test.ts: ########## @@ -56,9 +55,41 @@ const formData: PivotTableQueryFormData = { currencyFormat: { symbol: 'USD', symbolPosition: 'prefix' }, }; -test('should build groupby with series in form data', () => { +test('additive metrics use the fast-path: a single full-detail query', () => { + const { queries } = buildQuery({ + ...formData, + metrics: [ + { + expressionType: 'SIMPLE', + aggregate: 'SUM', + column: { column_name: 'num' }, + label: 'sum_num', + }, + ] as any, + }); + expect(queries).toHaveLength(1); + // The single leaf query carries all dimensions (2 rows + 2 cols). + expect(queries[0].columns).toHaveLength(4); +}); + +test('non-additive metrics emit a single GROUPING SETS query with all levels', () => { + // 2 row dims x 2 col dims -> (2+1) x (2+1) = 9 rollup levels, carried as + // grouping_sets on a single query (saved-metric strings are non-additive). const queryContext = buildQuery(formData); + expect(queryContext.queries).toHaveLength(1); const [query] = queryContext.queries; + // The single query selects the full set of dimensions ... + expect(query.columns).toHaveLength(4); + // ... and requests every rollup level via grouping_sets (grand total = []). + expect((query as any).grouping_sets).toHaveLength(9); + expect((query as any).grouping_sets[0]).toEqual([]); + expect((query as any).grouping_sets[8]).toHaveLength(4); Review Comment: Dropped the `any` — narrowed to a `QueryObject & { grouping_sets }` type in ef6691c. -- 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
