Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
5 changes: 5 additions & 0 deletions docs/docs/using-superset/semantic-member-selections.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,11 @@ the provider exposes several time-grain variants of that member. This matches
Explore's column list: choosing a filter column selects the member, not a grain
variant. Distinct member names remain separate choices.

The **Drill by** menu also lists each dimension once, using its display label
when the provider supplies one. Selecting it still drills by the member name.
These labels also appear in the native-filter column picker when verbose names
are shown, display-control column lists, and Drill by result labels.

## Choosing a datasource for a new chart

The chart-creation datasource picker, including when opened from a dashboard,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
} from 'spec/helpers/testing-library';
import chartQueries, { sliceId } from 'spec/fixtures/mockChartQueries';
import { supersetGetCache } from 'src/utils/cachedSupersetGet';
import { semanticViewDimensionsToColumns } from 'src/utils/semanticViewStructure';
import { DrillBySubmenu, DrillBySubmenuProps } from './DrillBySubmenu';

/* eslint jest/expect-expect: ["warn", { "assertFunctionNames": ["expect*"] }] */
Expand Down Expand Up @@ -274,6 +275,39 @@ test('When menu item is clicked, call onSelection with clicked column and drill
);
});

test('semantic date variants show one labelled drill choice with the same identity', async () => {
const columns = semanticViewDimensionsToColumns([
{
name: 'Orders.order_date',
type: 'date32[day]',
grain: 'Day',
verbose_name: 'Order date',
},
{
name: 'Orders.order_date',
type: 'date32[day]',
grain: null,
verbose_name: 'Order date',
},
]);
const onSelection = jest.fn();
renderSubmenu({
dataset: { ...mockDataset, columns, drillable_columns: columns },
onSelection,
});
await expectDrillByEnabled();
const submenu = await screen.findByTestId('drill-by-submenu');
expect(within(submenu).getAllByText('Order date')).toHaveLength(1);
expect(
within(submenu).queryByText('Orders.order_date'),
).not.toBeInTheDocument();
await userEvent.click(within(submenu).getByText('Order date'));
expect(onSelection).toHaveBeenCalledWith(
expect.objectContaining({ column_name: 'Orders.order_date' }),
{ filters: defaultFilters, groupbyFieldName: 'groupby' },
);
});

const xAxisFilters = [
{
col: 'ds',
Expand Down
9 changes: 5 additions & 4 deletions superset-frontend/src/hooks/apiResources/datasets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,10 +164,11 @@ export const useDatasetDrillInfo = (
const structure = await fetchSemanticViewStructure(numericDatasetId);
// Built as a partial Dataset (the declaration is typed, so
// table_name/columns are genuinely checked): no id or
// datasource_type is fabricated, and verbose_name is omitted rather
// than null — consumers only falsy-check it. The metrics are the one
// narrowing: the structure payload carries no uuid or full metric
// metadata, so each is asserted to Metric with only the fields
// datasource_type is fabricated. The shared mapper supplies each
// column's verbose_name from the structure or falls back to its name.
// Metrics are the one narrowing: the structure payload carries no
// uuid or full metric metadata, so each is asserted to Metric with
// only the fields
// consumers read (metric_name for verbose_map; expression for
// parity). Fabricating a uuid would be worse than the assertion.
result = {
Expand Down
48 changes: 48 additions & 0 deletions superset-frontend/src/utils/semanticViewStructure.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,54 @@ test('marks semantic dimensions as groupable for drill by', () => {
]);
});

test('collapses time grain variants into one labelled dimension', () => {
expect(
semanticViewDimensionsToColumns([
{
name: 'Orders.order_date',
type: 'timestamp[us]',
grain: 'Month',
verbose_name: 'Monthly order date',
},
{
name: 'Orders.order_date',
type: 'date32[day]',
grain: null,
verbose_name: 'Order date',
},
{
name: 'Orders.order_date',
type: 'timestamp[us]',
grain: 'Day',
verbose_name: 'Order date',
},
{ name: 'Orders.order_ts', type: 'timestamp[us]', grain: 'Hour' },
{
name: 'Orders.ship_date',
type: 'date32[day]',
verbose_name: 'Order date',
},
]),
).toEqual([
expect.objectContaining({
column_name: 'Orders.order_date',
verbose_name: 'Order date',
type: 'date32[day]',
groupby: true,
}),
expect.objectContaining({
column_name: 'Orders.order_ts',
verbose_name: 'Orders.order_ts',
groupby: true,
}),
expect.objectContaining({
column_name: 'Orders.ship_date',
verbose_name: 'Order date',
groupby: true,
}),
]);
});

test('maps the structure payload', async () => {
fetchMock.get('glob:*/api/v1/semantic_view/501/structure', {
result: {
Expand Down
21 changes: 18 additions & 3 deletions superset-frontend/src/utils/semanticViewStructure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,12 @@ export const mapSemanticTypeToGenericDataType = (
export interface SemanticViewStructure {
name?: string;
semantic_selection_version?: string;
dimensions: { name: string; type: string }[];
dimensions: {
name: string;
type: string;
grain?: string | null;
verbose_name?: string | null;
}[];
metrics: { name: string; definition: string }[];
}

Expand Down Expand Up @@ -114,15 +119,25 @@ export const fetchSemanticViewStructure = async (
*/
export const semanticViewDimensionsToColumns = (
dimensions: SemanticViewStructure['dimensions'],
): Column[] =>
dimensions.map(dim => {
): Column[] => {
type Dimension = SemanticViewStructure['dimensions'][number];
const byName = new Map<string, Dimension>();
dimensions.forEach(dimension => {
const existing = byName.get(dimension.name);
if (!existing || (!dimension.grain && existing.grain)) {
byName.set(dimension.name, dimension);
}
});
return Array.from(byName.values(), dim => {
const mappedType = mapSemanticTypeToGenericDataType(dim.type);
return {
column_name: dim.name,
verbose_name: dim.verbose_name || dim.name,

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.

🟢 Low (optional) — The fallback adds a redundant tooltip

With || dim.name, unlabelled dimensions get verbose_name === column_name, so getColumnTooltipNode shows "Column name: X / Label: X" in the pre-filter column picker, where there was no tooltip before. Explore sends verbose_name: null, and every consumer already falls back to verbose_name || column_name, so keeping dim.verbose_name ?? undefined would be enough. The mapper test's verbose_name: 'Orders.order_ts' expectation would need updating too. Non-blocking.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Applied in 177fe1e. An unlabelled dimension now keeps verbose_name absent in the mapped column. Drill by and the other inspected consumers still display the member name through their existing fallbacks. The mapper test failed before this change and passes afterward; both focused Jest suites and frontend type checking pass.

type: dim.type,
is_dttm: mappedType === GenericDataType.Temporal,
type_generic: mappedType,
filterable: true,
groupby: true,
};
});
};
1 change: 1 addition & 0 deletions superset/semantic_layers/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,7 @@ def structure(self, pk: int) -> Response:
"definition": dim.definition,
"description": dim.description,
"grain": dim.grain.name if dim.grain else None,
"verbose_name": dim.verbose_name,
}
for dim in sorted(
view.implementation.get_dimensions(), key=lambda d: d.name

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.

🟡 Medium — Without a raw variant, the label depends on hash order

get_dimensions() returns a set, and this endpoint sorts it by d.name only. Same-name grain variants therefore arrive in a hash order that changes from one worker process to the next. When a member has no grain == null variant, semanticViewDimensionsToColumns keeps whichever variant comes first. The label and type shown in Drill by and the display-control lists can then change between workers: one shows "Order day" (date32), another "Order year" (int64, not temporal). They can also disagree with Explore, which picks the finest grain consistently via grain_preference. Using that as a secondary sort key makes "first seen" in the mapper match Explore. This also covers the known follow-up in the PR description.

Also needs from superset.semantic_layers.dimension_resolution import grain_preference at the top of the file (outside the diff, so it can't go in the suggestion).

Suggested change
view.implementation.get_dimensions(), key=lambda d: d.name
view.implementation.get_dimensions(),
key=lambda d: (d.name, grain_preference(d)),

I checked it with a regression test that feeds Day/Week/Month/Year variants as a real set and expects them in fineness order. Under PYTHONHASHSEED 1–3 it fails without this change and passes with it, and the other structure tests still pass.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Applied in 177fe1e. The structure response now sorts variants by member name and the shared grain preference, matching Explore's raw and finest-grain selection. A regression using a real set failed under three hash seeds before the change and passes under all three after it. The focused API tests and semantic-layer 100% coverage gate pass.

Expand Down
6 changes: 6 additions & 0 deletions tests/unit_tests/semantic_layers/api_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -3048,10 +3048,12 @@ def test_get_views_flag_off_returns_404(


@SEMANTIC_LAYERS_APP
@pytest.mark.parametrize("verbose_name", ["Order date", None])
def test_get_semantic_view_structure(
client: Any,
full_api_access: None,
mocker: MockerFixture,
verbose_name: str | None,
) -> None:
"""Test GET /<pk>/structure returns dimensions and metrics."""
mock_dim = MagicMock()
Expand All @@ -3061,6 +3063,7 @@ def test_get_semantic_view_structure(
mock_dim.description = "Order date"
mock_dim.grain = MagicMock()
mock_dim.grain.name = "Day"
mock_dim.verbose_name = verbose_name

mock_metric = MagicMock()
mock_metric.name = "orders"
Expand Down Expand Up @@ -3098,6 +3101,7 @@ def test_get_semantic_view_structure(
assert result["dimensions"][0]["definition"] == "ordered_at"
assert result["dimensions"][0]["description"] == "Order date"
assert result["dimensions"][0]["grain"] == "Day"
assert result["dimensions"][0]["verbose_name"] == verbose_name
assert len(result["metrics"]) == 1
assert result["metrics"][0]["name"] == "orders"
assert result["metrics"][0]["type"] == "double"
Expand Down Expand Up @@ -3178,6 +3182,7 @@ def test_get_semantic_view_structure_no_grain(
mock_dim.definition = None
mock_dim.description = None
mock_dim.grain = None
mock_dim.verbose_name = None

mock_view: MagicMock = MagicMock(
implementation=MagicMock(selection_identity_version=None)
Expand All @@ -3198,6 +3203,7 @@ def test_get_semantic_view_structure_no_grain(
assert response.status_code == 200
result = response.json["result"]
assert result["dimensions"][0]["grain"] is None
assert result["dimensions"][0]["verbose_name"] is None
assert result["metrics"] == []
assert result["semantic_selection_version"] is None
# An unset description must come back as null, not be omitted: the modal
Expand Down
Loading