Skip to content
Closed
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
14 changes: 14 additions & 0 deletions docs/docs/using-superset/semantic-layer-connections.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,17 @@ with the `TIMEOUT` error type and can be retried in another request; views added
before the budget ran out stay added. Views that already exist are refused before
their lookup, so resending the whole request spends the budget only on the views
that are still missing.

## Dashboard time grain

A Time grain dashboard filter or display control is ignored by semantic-view
charts with no grouping columns, such as Big Number. It is also ignored by Table
and Interactive Table charts whose grouped columns are known not to be dates.
Their metrics and time-range filters are preserved; charts with an active time
dimension retain the selected grain. Ordinary SQL datasets are unchanged.

Other grouped chart types on a semantic view are not covered by this fix and
still show the time-column error when a grain is supplied without a time
dimension. Charts replayed from a stored query context, including single-chart
reports and API reads of a saved chart, are unchanged until re-saved from the
fixed frontend.
Original file line number Diff line number Diff line change
Expand Up @@ -16,39 +16,4 @@
* specific language governing permissions and limitations
* under the License.
*/
import {
isPhysicalColumn,
QueryObject,
TimeGranularity,
} from '@superset-ui/core';

// Only recognized duration choices are safe to treat as dormant. Legacy date
// formats and anchored week intervals are not semantic-layer durations.
const DURATION_GRAINS = new Set<string>(
Object.values(TimeGranularity).filter(
grain => grain.startsWith('P') && !grain.includes('/'),
),
);

/** Omit a dormant duration only when every selected column is proven non-temporal. */
export function omitDormantTimeGrain(
query: QueryObject,
temporalColumns: Record<string, boolean> | undefined,
): QueryObject {
const grain = query.extras?.time_grain_sqla;
if (
typeof grain !== 'string' ||
!DURATION_GRAINS.has(grain) ||
query.granularity ||
query.is_timeseries ||
!Array.isArray(query.columns) ||
!query.columns.every(
column => isPhysicalColumn(column) && temporalColumns?.[column] === false,
)
) {
return query;
}
const extras = { ...query.extras };
delete extras.time_grain_sqla;
return { ...query, extras };
}
export { omitDormantTimeGrain } from '@superset-ui/core';
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ import { SetDataMaskHook } from '../chart';
import { JsonObject } from '../connection';
import { normalizeTimeColumn } from './normalizeTimeColumn';
import { isXAxisSet } from './getXAxis';
import { omitDormantTimeGrain } from './omitDormantTimeGrain';
import { QueryMode } from './types';

const WRAP_IN_ARRAY = (baseQueryObject: QueryObject) => [baseQueryObject];

Expand Down Expand Up @@ -62,6 +64,16 @@ export default function buildQueryContext(
}
const datasource = new DatasourceKey(formData.datasource).toObject();
if (datasource.type === DatasourceType.SemanticView) {
const isRawQuery =
formData.query_mode === QueryMode.Raw ||
(formData.query_mode !== QueryMode.Aggregate &&
!!formData.all_columns?.length);
// Classify final queries, including totals, without changing saved form data.
if (!isRawQuery) {
queries = queries.map(query =>
omitDormantTimeGrain(query, formData.temporal_columns_lookup),
);
}
queries = queries.map(query => {
const hasInferredSeriesColumns =
query.is_timeseries && query.metrics?.length && query.columns?.length;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,5 @@ export {
getSemanticSelectionSources,
isGrainOnlyExtraFormData,
} from './semanticSelection';

export { omitDormantTimeGrain } from './omitDormantTimeGrain';
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* 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.
*/
import { isPhysicalColumn, QueryObject } from './types';
import { TimeGranularity } from '../time-format/types';

// Only recognized duration choices are safe to treat as dormant. Legacy date
// formats and anchored week intervals are not semantic-layer durations.
const DURATION_GRAINS = new Set<string>(
Object.values(TimeGranularity).filter(
grain => grain.startsWith('P') && !grain.includes('/'),
),
);

/** Omit a dormant duration only when every selected column is proven non-temporal. */
export function omitDormantTimeGrain(
query: QueryObject,
temporalColumns: Record<string, boolean> | undefined,
): QueryObject {
const grain = query.extras?.time_grain_sqla;
if (
typeof grain !== 'string' ||
!DURATION_GRAINS.has(grain) ||
query.granularity ||
query.is_timeseries ||
!Array.isArray(query.columns) ||
!query.columns.every(
column => isPhysicalColumn(column) && temporalColumns?.[column] === false,
)
) {
return query;
}
const extras = { ...query.extras };
delete extras.time_grain_sqla;
return { ...query, extras };
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,14 @@
* specific language governing permissions and limitations
* under the License.
*/
import { buildQueryContext, VizType } from '@superset-ui/core';
import {
buildQueryContext,
QueryMode,
QueryObject,
QueryFormData,
TimeGranularity,
VizType,
} from '@superset-ui/core';
import * as queryModule from '../../src/query/normalizeTimeColumn';

test('semantic queries omit a positive limit without final series columns', () => {
Expand Down Expand Up @@ -196,3 +203,57 @@ describe('buildQueryContext', () => {
spyNormalizeTimeColumn.mockRestore();
});
});

test('normalizes dormant grain per final semantic query without mutating inputs', () => {
const formData: QueryFormData = {
datasource: '5__semantic_view',
viz_type: VizType.BigNumberTotal,
metrics: ['revenue'],
extra_form_data: { time_grain_sqla: 'P1M' },
temporal_columns_lookup: { category: false, created: true },
};
const finalQueries: QueryObject[] = [
{ columns: [], extras: { time_grain_sqla: 'P1M' } },
{ columns: ['category'], extras: { time_grain_sqla: 'P1M' } },
{ columns: ['created'], extras: { time_grain_sqla: 'P1M' } },
{ columns: ['unknown'], extras: { time_grain_sqla: 'P1M' } },
{ columns: [], is_timeseries: true, extras: { time_grain_sqla: 'P1M' } },
{ columns: [], granularity: 'created', extras: { time_grain_sqla: 'P1M' } },
{ columns: [], extras: { time_grain_sqla: TimeGranularity.DATE } },
];
finalQueries.forEach(query => {
Object.freeze(query.extras);
Object.freeze(query);
});
Object.freeze(formData.extra_form_data);
Object.freeze(formData);
const context = buildQueryContext(formData, () => finalQueries);
expect(context.queries.map(query => query.extras?.time_grain_sqla)).toEqual([
undefined,
undefined,
'P1M',
'P1M',
'P1M',
'P1M',
'date',
]);
expect(finalQueries[0].extras?.time_grain_sqla).toBe('P1M');
expect(context.form_data).toBe(formData);
});

test.each([
{ query_mode: QueryMode.Raw },
{ all_columns: ['category'] },
{ query_mode: 'invalid' as QueryMode, all_columns: ['category'] },
{ datasource: '5__table' },
])('preserves dormant grain outside semantic aggregation: %j', overrides => {
const context = buildQueryContext({
datasource: '5__semantic_view',
viz_type: VizType.Table,
metrics: ['revenue'],
temporal_columns_lookup: { category: false },
extra_form_data: { time_grain_sqla: 'P1M' },
...overrides,
});
expect(context.queries[0].extras?.time_grain_sqla).toBe('P1M');
});
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
*/
import {
AdhocColumn,
DatasourceType,
buildQueryContext,
ensureIsArray,
getColumnLabel,
Expand All @@ -37,7 +36,6 @@ import {
} from '@superset-ui/core';
import {
getTotalsMetrics,
omitDormantTimeGrain,
isTimeComparison,
timeCompareOperator,
toTotalsAggregate,
Expand Down Expand Up @@ -812,14 +810,6 @@ export const buildQueryUncached: BuildQuery<TableChartFormData> = (

return [queryObject, ...extraQueries];
});
if (
context.datasource.type === DatasourceType.SemanticView &&
queryMode === QueryMode.Aggregate
) {
context.queries = context.queries.map(query =>
omitDormantTimeGrain(query, formData.temporal_columns_lookup),
);
}
return context;
};

Expand Down
12 changes: 0 additions & 12 deletions superset-frontend/plugins/plugin-chart-table/src/buildQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ import {

import {
getTotalsMetrics,
omitDormantTimeGrain,
isTimeComparison,
timeCompareOperator,
toTotalsAggregate,
Expand Down Expand Up @@ -424,17 +423,6 @@ export const buildQuery: BuildQuery<TableChartFormData> = (
return [queryObject, ...extraQueries];
});

// Normalize only rebuilt frontend requests, never saved form data. GET chart
// data can bypass this builder, so old stored query contexts may still fail
// strict host validation. Classify each final query, including derived ones.
if (
context.datasource.type === DatasourceType.SemanticView &&
queryMode === QueryMode.Aggregate
) {
context.queries = context.queries.map(query =>
omitDormantTimeGrain(query, formData.temporal_columns_lookup),
);
}
return context;
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,11 @@ import {
SemanticSelectionSource,
DatasourceType,
buildQueryObject,
buildQueryContext,
QueryFormData,
} from '@superset-ui/core';
import { sliceId as chartId } from 'spec/fixtures/mockChartQueries';
import buildBigNumberQuery from '../../../plugins/plugin-chart-echarts/src/BigNumber/BigNumberTotal/buildQuery';

type ChartCustomizationItem = NonNullable<
GetFormDataWithExtraFiltersArguments['chartCustomizationItems']
Expand Down Expand Up @@ -1243,3 +1245,83 @@ test.each([
);
},
);

test.each(
['native filter', 'display control'].flatMap(source =>
['3__semantic_view', '3__table'].flatMap(datasource =>
[false, true].map(hasTime => ({ source, datasource, hasTime })),
),
),
)(
'$source grain on $datasource with temporal column $hasTime',
({ source, datasource, hasTime }) => {
const native = source === 'native filter';
const id = native
? 'NATIVE_FILTER-duration'
: 'CHART_CUSTOMIZATION-duration';
const form = {
...mockChart.form_data,
datasource,
viz_type: 'big_number_total',
metrics: ['revenue'],
groupby: hasTime ? ['created'] : [],
temporal_columns_lookup: { created: true },
time_grain_sqla: 'P1D',
time_range: '2026-01-01 : 2026-04-01',
semantic_selection_version: 'cube-member-id-v1',
};
const result = getFormDataWithExtraFilters({
...mockArgs,
filters: {},
chart: { ...mockChart, form_data: form },
dataMask: {
[id]: {
id,
filterState: { value: ['P1M'] },
extraFormData: { time_grain_sqla: 'P1M' },
},
},
nativeFilters: native
? ({
[id]: {
id,
filterType: 'filter_timegrain',
chartsInScope: [chartId],
scope: { rootPath: ['ROOT_ID'], excluded: [] },
targets: [],
},
} as GetFormDataWithExtraFiltersArguments['nativeFilters'])
: {},
chartCustomizationItems: native
? []
: [
createChartCustomization({
id,
filterType: 'chart_customization_timegrain',
targets: [],
}),
],
});
const buildQuery = hasTime ? buildQueryContext : buildBigNumberQuery;
const query = buildQuery({
...result,
datasource: form.datasource,
viz_type: form.viz_type,
} as QueryFormData).queries[0];
expect(query.extras?.time_grain_sqla).toBe(
datasource.endsWith('__semantic_view') && !hasTime ? undefined : 'P1M',
);
expect(query).toMatchObject({
columns: form.groupby,
metrics: ['revenue'],
time_range: form.time_range,
extras: { semantic_selection_version: 'cube-member-id-v1' },
});
expect(form.time_grain_sqla).toBe('P1D');
expect(result).toMatchObject(
native
? { extra_form_data: { time_grain_sqla: 'P1M' } }
: { time_grain_sqla: 'P1M' },
);
},
);
Loading