Skip to content
Merged
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
13 changes: 13 additions & 0 deletions docs/sip/pivot-table-aggregation-parity.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,16 @@ dict silently in the first place).
3. Resolve the open question above, then decide the actual migration shape for orphaned Median/StdDev/Variance/CountUnique `aggregateFunction` values — likely the "flagged for review" approach #42895's SIP proposed (exact surfacing mechanism — Tag vs. report vs. in-product banner — still Evan's call, not yet decided).
4. Revisit apache/superset#44625 (reports/exports re-aggregation bug) once shelved time is up.
5. Out of scope for now: Table / Table v2 parity (confirmed not affected the same way — no pivot-style global aggregate control there) and AG Grid Interactive Pivot (separate viz, tracked as sc-118999 internally).

## Empty metric columns

Pivot Table hides columns whose metric values are all NULL by default. This
also applies to saved charts that do not have a `hideEmptyColumns` setting, so
users do not need to edit their charts after an upgrade. Clear **Hide empty
columns** to display these columns.

Zero is a value and keeps a column visible. Non-empty summaries and the parent
headers of populated columns also remain visible. The option only changes
column visibility. It retains the records and aggregators used for database
totals, result aggregations, and percentage denominators. A zero numerator
keeps its column even if a zero denominator makes its percentage undefined.
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,7 @@ export default function PivotTableChart(props: PivotTableProps) {
currencyFormats,
metricsLayout,
showValuesAs,
hideEmptyColumns = true,
aggregateFunction,
metricColorFormatters,
dateFormatters,
Expand Down Expand Up @@ -760,6 +761,7 @@ export default function PivotTableChart(props: PivotTableProps) {
onContextMenu={handleContextMenu}
allowRenderHtml={allowRenderHtml}
showValuesAs={showValuesAs}
hideEmptyColumns={hideEmptyColumns}

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.

🟡 Toggling Hide empty columns leaves the sort indicator on the wrong column. activeSortColumn in TableRenderer is an index into the visible columns. The sort-reset useEffect (TableRenderers.tsx ~826-837) doesn't depend on hideEmptyColumns, and this is the only render-trigger control that changes the column set. Repro: columns A, B (all null), C with hiding off. Sort by B ("Sorted by B ascending"), then turn hiding on. The label moves to "Sorted by C ascending" while the rows stay in B's order. It happens the other way round too.

TableRenderers.tsx isn't in the diff, so here is the patch. With it, the repro passes and all pivot tests pass.

@@ TableRenderers.tsx ~383
     onContextMenu,
     allowRenderHtml,
+    hideEmptyColumns,
   } = props;
@@ TableRenderers.tsx ~836
     namesMappingProp,
     allowRenderHtml,
+    hideEmptyColumns,
   ]);

aggregateFunction={aggregateFunction}
/>
</PivotTableWrapper>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,20 @@ const config: ControlPanelConfig = {
expanded: true,
tabOverride: 'data',
controlSetRows: [
[
{
name: 'hideEmptyColumns',
config: {
type: 'CheckboxControl',
label: t('Hide empty columns'),
Comment thread
fitzee marked this conversation as resolved.
Resolved
default: true,
renderTrigger: true,
description: t(
'Hide columns with only null metric values. Keep columns with zeros or non-empty summaries. This does not change totals or percentages.',
),
},
},
],
[
{
name: 'rowTotals',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,7 @@ export default function transformProps(chartProps: ChartProps<QueryFormData>) {
rowTotals,
rowSubTotals,
collapseRows,
hideEmptyColumns = true,
valueFormat,
dateFormat,
metricsLayout,
Expand Down Expand Up @@ -288,6 +289,7 @@ export default function transformProps(chartProps: ChartProps<QueryFormData>) {
rowTotals,
rowSubTotals,
collapseRows: Boolean(collapseRows),
hideEmptyColumns,
valueFormat,
currencyFormat,
currencyCodeColumn,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,7 @@ export function TableRenderer(props: TableRendererProps) {
namesMapping: namesMappingProp,
onContextMenu,
allowRenderHtml,
hideEmptyColumns,
} = props;

const [collapsedRows, setCollapsedRows] = useState<Record<string, boolean>>(
Expand Down Expand Up @@ -834,6 +835,7 @@ export function TableRenderer(props: TableRendererProps) {
subtotalOptions,
namesMappingProp,
allowRenderHtml,
hideEmptyColumns,
]);

// Use sorted row keys if available, otherwise use base row keys
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1685,7 +1685,33 @@ class PivotData {

getColKeys(): string[][] {
this.sortKeys();
return this.colKeys;
if (!this.props.hideEmptyColumns) return this.colKeys;

// Filter display keys only. Keep every aggregator and record available to
// totals, fraction denominators and drill filters. A zero is not empty.
const populated = new Set<string>();
const collect = (cells: Record<string, Aggregator>) => {
Object.entries(cells).forEach(([key, aggregator]) => {
// Test the underlying metric before percentage formatting. A zero
// numerator must keep its column even when its denominator is zero.
const metric = (aggregator as FractionDenominator).inner ?? aggregator;
if (metric.value() != null) populated.add(key);
});
};
Object.values(this.tree).forEach(collect);
collect(this.colTotals);

// Retain a parent header when a child has a value, even if the parent's
// own aggregate is null (for example an undefined ratio).
const visible = new Set<string>();
this.colKeys.forEach(key => {
if (populated.has(flatKey(key))) {
for (let depth = 1; depth <= key.length; depth += 1) {
visible.add(flatKey(key.slice(0, depth)));
}
}
});
return this.colKeys.filter(key => visible.has(flatKey(key)));

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.

Suggestion: Filtering shifts surviving columns’ indices, but the renderer retains activeSortColumn and its sort direction. Hiding a column can leave the indicator missing or make the next click reset instead of toggle.

Assessment: 🟠 Major · 🔁 Occurrence: Sometimes · 🏷️ Stale reference

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset-frontend/plugins/plugin-chart-pivot-table/src/react-pivottable/utilities.ts
**Line:** 1714:1714
**Comment:**
	*Stale Reference: Filtering shifts surviving columns’ indices, but the renderer retains `activeSortColumn` and its sort direction. Hiding a column can leave the indicator missing or make the next click reset instead of toggle.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

}

getRowKeys(): string[][] {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ interface PivotTableCustomizeProps {
* Viewers can still expand each group with its arrow.
*/
collapseRows?: boolean;
hideEmptyColumns?: boolean;
valueFormat: string;
currencyFormat: Currency;
currencyCodeColumn?: string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -502,3 +502,61 @@ test.each([
expect(screen.getAllByText('m1').length).toBeGreaterThan(0);
},
);

test.each(
[undefined, true, false].flatMap(hideEmptyColumns =>
[false, true].map(combineMetric => ({ hideEmptyColumns, combineMetric })),
),
)(
'all-null metric columns use the compatibility default ($hideEmptyColumns, combine=$combineMetric)',
({ hideEmptyColumns, combineMetric }) => {
const props = createProps({
groupbyRows: ['year'],
groupbyColumns: ['product'],
metrics: ['limited', 'all'],
aggregateFunction: 'Sum',
combineMetric,
...(hideEmptyColumns === undefined ? {} : { hideEmptyColumns }),
data: toQueryData(
[
{ year: '2024', product: 'A', limited: 10, all: 20 },
{ year: '2024', product: 'B', limited: null, all: 30 },
{ year: '2025', product: 'A', limited: 15, all: 25 },
{ year: '2025', product: 'B', limited: null, all: 35 },
],
{ rows: ['year'], columns: ['product'] },
),
});
const { container } = renderWithTheme(<PivotTableChart {...props} />);
const productHeaders = Array.from(
container.querySelectorAll('th.pvtColLabel'),
).map(node => node.textContent);
expect(productHeaders.filter(label => label === 'A')).toHaveLength(
combineMetric ? 1 : 2,
);
expect(productHeaders.filter(label => label === 'B')).toHaveLength(
combineMetric || hideEmptyColumns !== false ? 1 : 2,
);
expect(container.querySelectorAll('td.pvtVal')).toHaveLength(
hideEmptyColumns === false ? 8 : 6,
);
},
);

test('zero-valued metric columns remain visible with the compatibility default', () => {
const props = createProps({
groupbyRows: ['year'],
groupbyColumns: ['product'],
metrics: ['limited', 'all'],
data: toQueryData([{ year: '2024', product: 'B', limited: 0, all: 30 }], {
rows: ['year'],
columns: ['product'],
}),
});
const { container } = renderWithTheme(<PivotTableChart {...props} />);
const labels = Array.from(container.querySelectorAll('th.pvtColLabel')).map(
node => node.textContent,
);
expect(labels.filter(label => label === 'B')).toHaveLength(2);
expect(screen.getByText('$ 0')).toBeInTheDocument();
});
Original file line number Diff line number Diff line change
Expand Up @@ -681,3 +681,17 @@ test('result aggregation wins over the additive fast path for an additive metric
expect(result.data).toHaveLength(1);
expect(result.data[0].data).toEqual(additiveResultProps.queriesData[0].data);
});

test.each([undefined, true, false])(
'hideEmptyColumns defaults on for saved charts (%s)',
value => {
const props = new ChartProps<QueryFormData>({
...chartProps,
formData: {
...formData,
...(value === undefined ? {} : { hideEmptyColumns: value }),
},
});
expect(transformProps(props).hideEmptyColumns).toBe(value !== false);
},
);
Original file line number Diff line number Diff line change
Expand Up @@ -1742,3 +1742,56 @@ test('TableRenderer keeps each metric aggregation on its own formatter', () => {
expect(grandTotalCells.length).toBe(1);
expect(grandTotalCells[0]).toHaveTextContent('3.000 r');
});

test.each([
{ hideEmptyColumns: false, sortColumn: 'B' },
{ hideEmptyColumns: false, sortColumn: 'C' },
{ hideEmptyColumns: true, sortColumn: 'C' },
])(
'reset sorting when empty-column visibility changes ($hideEmptyColumns, $sortColumn)',
({ hideEmptyColumns, sortColumn }) => {
const props = buildDefaultProps({
rows: ['row'],
cols: ['column'],
vals: ['value'],
aggregateFunction: 'Sum',
data: ['first', 'second'].flatMap(row => [
{ row, column: 'A', value: 1 },
{ row, column: 'B', value: null },
{ row, column: 'C', value: row === 'first' ? 20 : 10 },
]),
});
const { container, rerender } = renderWithTheme(
<TableRenderer {...props} hideEmptyColumns={hideEmptyColumns} />,
);
const sort = (column: string) => {
const header = Array.from(
container.querySelectorAll('th.pvtColLabel'),
).find(node => node.textContent === column)!;
fireEvent.click(header.querySelector('.anticon')!);
};
const rowLabels = () =>
Array.from(container.querySelectorAll('th.pvtRowLabel')).map(
node => node.textContent,
);
sort(sortColumn);
expect(
screen.getByRole('button', { name: `Sorted by ${sortColumn} ascending` }),
).toBeInTheDocument();
if (sortColumn === 'C') expect(rowLabels()).toEqual(['second', 'first']);
rerender(
<ThemeProvider theme={supersetTheme}>
<TableRenderer {...props} hideEmptyColumns={!hideEmptyColumns} />
</ThemeProvider>,
);
expect(
screen.queryByRole('button', { name: /Sorted by/ }),
).not.toBeInTheDocument();
expect(rowLabels()).toEqual(['first', 'second']);
sort('C');
expect(
screen.getByRole('button', { name: 'Sorted by C ascending' }),
).toBeInTheDocument();
expect(rowLabels()).toEqual(['second', 'first']);
},
);
Loading
Loading