diff --git a/docs/docs/using-superset/creating-your-first-dashboard.mdx b/docs/docs/using-superset/creating-your-first-dashboard.mdx index 38dd856aa629..edf5620f13de 100644 --- a/docs/docs/using-superset/creating-your-first-dashboard.mdx +++ b/docs/docs/using-superset/creating-your-first-dashboard.mdx @@ -150,6 +150,14 @@ for how the column should be treated in the Explore workflow: +In the dataset editor's **Columns** tab, use **Default time filter** beside +**Default datetime column** to set the range of the time filters Explore adds +for this dataset, for example on a new chart or when you add a datetime column +to the filters. Opening a saved chart doesn't change its range. +**Use instance default** inherits the administrator's setting, and **No filter** +means an unbounded range. Chart authors can change the range before saving +their charts. + #### Snowflake column name casing For physical Snowflake datasets, Superset uses the dialect's automatic identifier diff --git a/superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/dndControls.tsx b/superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/dndControls.tsx index 6a7ad9f2658d..5fdb71ba15b5 100644 --- a/superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/dndControls.tsx +++ b/superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/dndControls.tsx @@ -34,10 +34,12 @@ import { ColumnOption, ColumnMeta, FilterOption, +} from '..'; +import { temporalColumnMixin, datePickerInAdhocFilterMixin, xAxisMixin, -} from '..'; +} from './mixins'; type Control = { savedMetrics?: Metric[] | null; diff --git a/superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/mixins.tsx b/superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/mixins.tsx index 840dfc3a35f1..683e93f67e17 100644 --- a/superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/mixins.tsx +++ b/superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/mixins.tsx @@ -29,7 +29,7 @@ import { ControlState, ExtraControlProps, } from '../types'; -import { getTemporalColumns } from '../utils'; +import { getDatasetDefaultTimeFilter, getTemporalColumns } from '../utils'; const getAxisLabel = ( formData: QueryFormData, @@ -114,7 +114,11 @@ export const datePickerInAdhocFilterMixin: Pick< clause: 'WHERE', subject: temporalColumn, operator: 'TEMPORAL_RANGE', - comparator: state?.common?.conf?.DEFAULT_TIME_FILTER || NO_TIME_RANGE, + comparator: + state?.initialTimeRange || + getDatasetDefaultTimeFilter(state?.datasource) || + state?.common?.conf?.DEFAULT_TIME_FILTER || + NO_TIME_RANGE, expressionType: 'SIMPLE', }, ]; diff --git a/superset-frontend/packages/superset-ui-chart-controls/src/types.ts b/superset-frontend/packages/superset-ui-chart-controls/src/types.ts index 5bc38c190ece..8d726f8eeb61 100644 --- a/superset-frontend/packages/superset-ui-chart-controls/src/types.ts +++ b/superset-frontend/packages/superset-ui-chart-controls/src/types.ts @@ -164,6 +164,7 @@ export interface ControlPanelState { controls: ControlStateMapping; common: JsonObject; metadata?: JsonObject | null; + initialTimeRange?: string | null; } /** diff --git a/superset-frontend/packages/superset-ui-chart-controls/src/utils/getDatasetDefaultTimeFilter.ts b/superset-frontend/packages/superset-ui-chart-controls/src/utils/getDatasetDefaultTimeFilter.ts new file mode 100644 index 000000000000..f8ea79fd2fe8 --- /dev/null +++ b/superset-frontend/packages/superset-ui-chart-controls/src/utils/getDatasetDefaultTimeFilter.ts @@ -0,0 +1,40 @@ +/** + * 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 { Dataset } from '../types'; + +/** + * Returns the dataset's `extra.default_time_filter`, which Explore uses instead + * of the instance `DEFAULT_TIME_FILTER` when it adds a time filter. Unparseable + * metadata counts as unset. + */ +export function getDatasetDefaultTimeFilter( + dataset?: Pick | null, +): string | undefined { + let range: unknown; + try { + const extra = + typeof dataset?.extra === 'string' + ? JSON.parse(dataset.extra) + : dataset?.extra; + range = extra?.default_time_filter; + } catch { + return undefined; + } + return typeof range === 'string' && range ? range : undefined; +} diff --git a/superset-frontend/packages/superset-ui-chart-controls/src/utils/index.ts b/superset-frontend/packages/superset-ui-chart-controls/src/utils/index.ts index f130cf7b3e30..9f1fce482a18 100644 --- a/superset-frontend/packages/superset-ui-chart-controls/src/utils/index.ts +++ b/superset-frontend/packages/superset-ui-chart-controls/src/utils/index.ts @@ -28,6 +28,7 @@ export { default as columnChoices, columnsByType } from './columnChoices'; export * from './defineSavedMetrics'; export * from './getStandardizedControls'; export * from './getTemporalColumns'; +export * from './getDatasetDefaultTimeFilter'; export * from './displayTimeRelatedControls'; export * from './colorControls'; export * from './metricColumnFilter'; diff --git a/superset-frontend/packages/superset-ui-chart-controls/test/utils/getDatasetDefaultTimeFilter.test.ts b/superset-frontend/packages/superset-ui-chart-controls/test/utils/getDatasetDefaultTimeFilter.test.ts new file mode 100644 index 000000000000..efd8db29a6f9 --- /dev/null +++ b/superset-frontend/packages/superset-ui-chart-controls/test/utils/getDatasetDefaultTimeFilter.test.ts @@ -0,0 +1,34 @@ +/** + * 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 { getDatasetDefaultTimeFilter } from '../../src'; + +test.each([ + [ + '{"default_time_filter": "Last week", "warning_markdown": "x"}', + 'Last week', + ], + [{ default_time_filter: 'No filter' }, 'No filter'], + ['{"default_time_filter": ""}', undefined], + ['{"default_time_filter": 7}', undefined], + ['{bad', undefined], + ['[]', undefined], + [undefined, undefined], +])('getDatasetDefaultTimeFilter(%p) returns %p', (extra, expected) => { + expect(getDatasetDefaultTimeFilter({ extra })).toBe(expected); +}); diff --git a/superset-frontend/packages/superset-ui-core/src/ui-overrides/types.ts b/superset-frontend/packages/superset-ui-core/src/ui-overrides/types.ts index 10c9d5b49a55..c2f083aff73b 100644 --- a/superset-frontend/packages/superset-ui-core/src/ui-overrides/types.ts +++ b/superset-frontend/packages/superset-ui-core/src/ui-overrides/types.ts @@ -226,6 +226,7 @@ export interface DateFilterControlProps { name: string; onChange: (timeRange: string) => void; value?: string; + placeholder?: string; onOpenPopover?: () => void; onClosePopover?: () => void; overlayStyle?: 'Modal' | 'Popover'; diff --git a/superset-frontend/src/components/Chart/chartAction.ts b/superset-frontend/src/components/Chart/chartAction.ts index 16d53542282b..a9a8b98b4f69 100644 --- a/superset-frontend/src/components/Chart/chartAction.ts +++ b/superset-frontend/src/components/Chart/chartAction.ts @@ -41,6 +41,7 @@ import { buildV1ChartDataPayload, getQuerySettings, getChartDataUri, + getInitialTimeRange, } from 'src/explore/exploreUtils'; import { addDangerToast, @@ -425,6 +426,11 @@ export const dynamicPluginControlsReady = const exploreState = { ...state.explore, datasource: state.explore.datasource || { type: 'table' }, + initialTimeRange: getInitialTimeRange( + !state.explore.slice, + state.explore.datasource as { extra?: string } | undefined, + state.common?.conf?.DEFAULT_TIME_FILTER as string | undefined, + ), }; const controlsState = getControlsState( exploreState, diff --git a/superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.tsx b/superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.tsx index de6301f46fb6..2df274ba402d 100644 --- a/superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.tsx +++ b/superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.tsx @@ -51,6 +51,8 @@ import Tabs from '@superset-ui/core/components/Tabs'; import WarningIconWithTooltip from '@superset-ui/core/components/WarningIconWithTooltip'; import TableSelector from 'src/components/TableSelector'; import CheckboxControl from 'src/explore/components/controls/CheckboxControl'; +import DateFilterControl from 'src/explore/components/controls/DateFilterControl'; +import { getDatasetDefaultTimeFilter } from '@superset-ui/chart-controls'; import TextControl from 'src/explore/components/controls/TextControl'; import TextAreaControl from 'src/explore/components/controls/TextAreaControl'; import withToasts from 'src/components/MessageToasts/withToasts'; @@ -134,6 +136,7 @@ import { DatasourceFolder } from 'src/explore/components/DatasourcePanel/types'; import { getDatasetCertification, isDatasetExtraValid, + parseExtra, } from './datasetCertification'; const extensionsRegistry = getExtensionsRegistry(); @@ -544,6 +547,14 @@ const FieldLabelWithTooltip = styled.div` `} `; +const DefaultTimeFilterField = styled(Flex)` + ${({ theme }) => css` + button[name='default_time_filter'] { + height: ${theme.sizeXL + 2 * (theme.sizeUnit + theme.lineWidth)}px; + } + `} +`; + const StyledButtonWrapper = styled.span` ${({ theme }) => ` margin-top: ${theme.sizeUnit * 3}px; @@ -2252,34 +2263,88 @@ function DatasourceEditor({ label: col.verbose_name || col.column_name, })); + // An unset default time filter inherits the instance default. The field is + // hidden while the Extra JSON is malformed. + const extra = parseExtra(datasource.extra); + const showDefaultTimeFilter = isSqla && !!extra; + const defaultTimeFilter = getDatasetDefaultTimeFilter({ extra }); + const setDefaultTimeFilter = (range?: string) => { + // An empty range is unset. Leave the Extra JSON as written when the + // range does not change. + const default_time_filter = range || undefined; + if (default_time_filter === defaultTimeFilter) return; + onDatasourceChange({ + ...datasource, + extra: JSON.stringify({ ...extra, default_time_filter }), + }); + }; + const DateFilterComponent = + extensionsRegistry.get('filter.dateFilterControl') ?? DateFilterControl; + return ( {t('Default Column Settings')} - - - {t('Default datetime column')} - - - + handleMainDttmColChange(value as string | undefined) + } + placeholder={t('Select datetime column')} + allowClear + data-test="default-datetime-column-select" + /> + + + {showDefaultTimeFilter && ( + + + + + {t('Default time filter')} + + + + + {defaultTimeFilter && ( +
+ +
+ )} +
+ + )} + {t('Currency code column')} @@ -2329,6 +2394,7 @@ function DatasourceEditor({ theme?.sizeUnit, datasource, onDatasourceChange, + isSqla, ]); const renderCertificationFieldset = useCallback(() => { diff --git a/superset-frontend/src/components/Datasource/components/DatasourceEditor/datasetCertification.ts b/superset-frontend/src/components/Datasource/components/DatasourceEditor/datasetCertification.ts index 9034822b2892..3352315ab3b5 100644 --- a/superset-frontend/src/components/Datasource/components/DatasourceEditor/datasetCertification.ts +++ b/superset-frontend/src/components/Datasource/components/DatasourceEditor/datasetCertification.ts @@ -27,7 +27,7 @@ type JsonObject = Record; const isJsonObject = (value: unknown): value is JsonObject => typeof value === 'object' && value !== null && !Array.isArray(value); -const parseExtra = (extra?: string): JsonObject | undefined => { +export const parseExtra = (extra?: string): JsonObject | undefined => { if (!extra?.trim()) { return {}; } diff --git a/superset-frontend/src/components/Datasource/components/DatasourceEditor/tests/DatasourceEditorDefaultTimeFilter.test.tsx b/superset-frontend/src/components/Datasource/components/DatasourceEditor/tests/DatasourceEditorDefaultTimeFilter.test.tsx new file mode 100644 index 000000000000..578c12008b7b --- /dev/null +++ b/superset-frontend/src/components/Datasource/components/DatasourceEditor/tests/DatasourceEditorDefaultTimeFilter.test.tsx @@ -0,0 +1,79 @@ +/** + * 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 fetchMock from 'fetch-mock'; +import { + screen, + userEvent, + waitFor, + within, +} from 'spec/helpers/testing-library'; +import { + createProps, + DATASOURCE_ENDPOINT, + setupDatasourceEditorMocks, + cleanupAsyncOperations, + fastRender, + dismissDatasourceWarning, +} from './DatasourceEditor.test.utils'; + +beforeEach(() => { + fetchMock.get(DATASOURCE_ENDPOINT, [], { name: DATASOURCE_ENDPOINT }); + fetchMock.get('glob:*/api/v1/time_range/*', { + result: [{ since: '', until: '', timeRange: 'Last day' }], + }); + setupDatasourceEditorMocks(); +}); + +afterEach(async () => { + await cleanupAsyncOperations(); + fetchMock.clearHistory().removeRoutes(); +}); + +test('resets the default time filter to the instance default and keeps other metadata', async () => { + const props = createProps(); + props.datasource.extra = JSON.stringify({ + default_time_filter: 'Last day', + warning_markdown: 'Note', + }); + fastRender(props); + await dismissDatasourceWarning(); + await userEvent.click(await screen.findByTestId('collection-tab-Columns')); + const settings = screen.getByTestId('default-column-settings'); + expect( + within(settings).getByRole('button', { name: 'Default time filter' }), + ).toHaveTextContent('Last day'); + + await userEvent.click( + within(settings).getByRole('button', { name: 'Use instance default' }), + ); + + await waitFor(() => { + const { calls } = props.onChange.mock; + const [datasource] = calls[calls.length - 1]; + expect(JSON.parse(datasource.extra ?? '')).toEqual({ + warning_markdown: 'Note', + }); + }); + expect( + within(settings).getByRole('button', { name: 'Default time filter' }), + ).toHaveTextContent('Use instance default'); + expect( + within(settings).queryByRole('button', { name: 'Use instance default' }), + ).not.toBeInTheDocument(); +}); diff --git a/superset-frontend/src/explore/actions/hydrateExplore.test.ts b/superset-frontend/src/explore/actions/hydrateExplore.test.ts index a4f9e732d04f..3b47bec6e155 100644 --- a/superset-frontend/src/explore/actions/hydrateExplore.test.ts +++ b/superset-frontend/src/explore/actions/hydrateExplore.test.ts @@ -20,16 +20,34 @@ import { buildQueryContext, DatasourceType, + ensureIsArray, + getChartControlPanelRegistry, + isBinaryAdhocFilter, isFeatureEnabled, + isSimpleAdhocFilter, + NO_TIME_RANGE, QueryFormData, VizType, } from '@superset-ui/core'; +import { Dataset } from '@superset-ui/chart-controls'; import { ExplorePageState } from '../types'; -import exploreReducer from '../reducers/exploreReducer'; +import exploreReducer, { ExploreState } from '../reducers/exploreReducer'; +import { getFormDataFromControls } from '../controlUtils'; import { setStashFormData } from './exploreActions'; import { HYDRATE_CHART_NORMALIZATION } from 'src/features/versionHistory/reducer'; -import { hydrateExplore, HYDRATE_EXPLORE } from './hydrateExplore'; +import { + hydrateExplore, + HydrateExplore, + HYDRATE_EXPLORE, +} from './hydrateExplore'; import { exploreInitialData } from '../fixtures'; +import { + dynamicPluginControlsReady, + RootState, +} from 'src/components/Chart/chartAction'; +import tableControlPanel from '../../../plugins/plugin-chart-table/src/controlPanel'; +import calendarControlPanel from '../../../plugins/plugin-chart-calendar/src/controlPanel'; +import pieControlPanel from '../../../plugins/plugin-chart-echarts/src/Pie/controlPanel'; jest.mock('@superset-ui/core', () => ({ ...jest.requireActual('@superset-ui/core'), @@ -489,6 +507,298 @@ test('uses configured default time range if not set', () => { ); }); +const instanceRange = 'Last year'; +const datasetRange = 'Last day'; +const datasetExtra = JSON.stringify({ + default_time_filter: datasetRange, + warning_markdown: 'Note', +}); + +// Table and Pie use ad hoc time filters; the calendar uses a Time range +// control. +function withControlPanels(run: () => T): T { + const registry = getChartControlPanelRegistry(); + const panels = { + [VizType.Table]: tableControlPanel, + [VizType.Pie]: pieControlPanel, + cal_heatmap: calendarControlPanel, + }; + const previous = Object.keys(panels).map( + key => [key, registry.get(key)] as const, + ); + Object.entries(panels).forEach(([key, panel]) => + registry.registerValue(key, panel), + ); + try { + return run(); + } finally { + previous.forEach(([key, panel]) => + panel ? registry.registerValue(key, panel) : registry.remove(key), + ); + } +} + +type NewChartOptions = { + vizType?: string; + extra?: string; + formData?: Partial; + slice?: typeof exploreInitialData.slice; + dataset?: Partial; +}; + +// The dataset's default datetime column is not its first temporal column. +function hydrateNewChart({ + vizType = VizType.Table, + extra = datasetExtra, + formData = {}, + slice = null, + dataset = {}, +}: NewChartOptions = {}): HydrateExplore['data'] { + const dispatch = jest.fn(); + hydrateExplore({ + ...exploreInitialData, + dataset: { + ...exploreInitialData.dataset, + columns: [ + { column_name: 'ingested_at', is_dttm: true }, + { column_name: 'created_at', is_dttm: true }, + ], + main_dttm_col: 'created_at', + extra, + ...dataset, + }, + form_data: { + datasource: '8__table', + viz_type: vizType, + adhoc_filters: [], + ...formData, + }, + slice, + })( + dispatch, + () => + ({ + user: {}, + charts: {}, + datasources: {}, + common: { conf: { DEFAULT_TIME_FILTER: instanceRange } }, + explore: {}, + }) as unknown as ExplorePageState, + ); + return dispatch.mock.calls[0][0].data; +} + +function hydrateNewChartQuery(options?: NewChartOptions): QueryFormData { + const { charts } = withControlPanels(() => hydrateNewChart(options)); + return Object.values(charts)[0].latestQueryFormData as QueryFormData; +} + +// Returns [column, range] from either an ad hoc filter or the Time range +// control. A query must not send both, since the backend then replaces the +// range of every ad hoc time filter with the Time range. +function getTimeFilter(formData: QueryFormData) { + const filter = ensureIsArray(formData.adhoc_filters) + .filter(isSimpleAdhocFilter) + .filter(isBinaryAdhocFilter) + .find(adhocFilter => adhocFilter.operator === 'TEMPORAL_RANGE'); + if (filter && formData.time_range) { + throw new Error('The query sends both a Time range and a time filter'); + } + return filter + ? [filter.subject, filter.comparator] + : [formData.granularity_sqla, formData.time_range]; +} + +test.each([ + [VizType.Table, datasetExtra, datasetRange], + ['cal_heatmap', datasetExtra, datasetRange], + [VizType.Table, `{"default_time_filter": "${NO_TIME_RANGE}"}`, NO_TIME_RANGE], + [VizType.Table, '{}', instanceRange], +])( + 'a new %s chart on a dataset with extra %s starts with %s on the default datetime column', + (vizType, extra, range) => { + expect(getTimeFilter(hydrateNewChartQuery({ vizType, extra }))).toEqual([ + 'created_at', + range, + ]); + }, +); + +test('a new cal_heatmap chart keeps the time range supplied in its form data', () => { + const query = hydrateNewChartQuery({ + vizType: 'cal_heatmap', + formData: { time_range: NO_TIME_RANGE }, + }); + expect(getTimeFilter(query)).toEqual(['created_at', NO_TIME_RANGE]); +}); + +// SQL Lab opens new charts with `time_range: 'No filter'` +// (EXPLORE_CHART_DEFAULT), which must not override either default. +test.each([ + ['the dataset default', datasetExtra, datasetRange], + ['the instance default', '{}', instanceRange], +])( + "a new Table chart opened with time_range 'No filter' starts with %s", + (_, extra, range) => { + const query = hydrateNewChartQuery({ + extra, + formData: { time_range: NO_TIME_RANGE }, + }); + expect(getTimeFilter(query)).toEqual(['created_at', range]); + }, +); + +test('a saved Table chart with its own time_range and no time filter opens with the instance default', () => { + const query = hydrateNewChartQuery({ + slice: exploreInitialData.slice, + formData: { time_range: 'Last week' }, + }); + expect(getTimeFilter({ ...query, time_range: undefined })).toEqual([ + 'created_at', + instanceRange, + ]); +}); + +test('an ad hoc time filter supplied to a new chart is its only time filter', () => { + const filter = { + expressionType: 'SIMPLE', + clause: 'WHERE', + subject: 'ingested_at', + operator: 'TEMPORAL_RANGE', + comparator: 'Last week', + } as const; + const query = hydrateNewChartQuery({ formData: { adhoc_filters: [filter] } }); + expect(query.adhoc_filters).toEqual([expect.objectContaining(filter)]); +}); + +test('a saved chart ignores the dataset default time filter', () => { + const query = hydrateNewChartQuery({ + vizType: 'cal_heatmap', + slice: exploreInitialData.slice, + }); + expect(query.time_range).toBe(instanceRange); +}); + +test.each([VizType.Table, 'cal_heatmap'])( + 'a new %s chart on another time column starts with the dataset default time filter', + vizType => { + const query = hydrateNewChartQuery({ + vizType, + formData: { granularity_sqla: 'ingested_at' }, + }); + expect(getTimeFilter(query)).toEqual(['ingested_at', datasetRange]); + }, +); + +test.each([ + ['a new chart', null, datasetRange], + ['a saved chart', exploreInitialData.slice, instanceRange], +])( + 'controls rebuilt for a late-loading plugin keep the time range %s opens with', + (_, slice, range) => { + const timeFilter = withControlPanels(() => { + const { explore } = hydrateNewChart({ + slice, + formData: { time_range: NO_TIME_RANGE }, + }); + const dispatch = jest.fn(); + dynamicPluginControlsReady()( + dispatch, + () => + ({ + explore, + common: { conf: { DEFAULT_TIME_FILTER: instanceRange } }, + }) as unknown as RootState, + undefined, + ); + return getTimeFilter( + getFormDataFromControls(dispatch.mock.calls[0][0].controlsState), + ); + }); + expect(timeFilter).toEqual(['created_at', range]); + }, +); + +function switchNewChartDataset(dataset: Partial) { + const { explore } = hydrateNewChart({ extra: '{}' }); + return exploreReducer(explore as ExploreState, { + type: 'UPDATE_FORM_DATA_BY_DATASOURCE', + prevDatasource: explore.datasource, + newDatasource: { + ...explore.datasource, + id: 9, + uid: '9__table', + ...dataset, + }, + }); +} + +function changeChartType(explore: ExploreState, vizType: string) { + const { controls } = exploreReducer(explore, { + type: 'SET_FIELD_VALUE', + controlName: 'viz_type', + value: vizType, + }); + return getFormDataFromControls(controls); +} + +const otherTimeColumn = { + columns: [{ column_name: 'event_date', is_dttm: true }], + main_dttm_col: 'event_date', +}; + +test.each([ + [datasetExtra, datasetRange], + ['{}', instanceRange], +])( + 'switching to a dataset with extra %s re-creates a dropped time filter with %s', + (extra, range) => { + const { controls } = withControlPanels(() => + switchNewChartDataset({ ...otherTimeColumn, extra }), + ); + expect(getTimeFilter(getFormDataFromControls(controls))).toEqual([ + 'event_date', + range, + ]); + }, +); + +test('switching to a dataset keeps a time filter that carries over', () => { + const { controls } = withControlPanels(() => + switchNewChartDataset({ extra: datasetExtra }), + ); + expect(getTimeFilter(getFormDataFromControls(controls))).toEqual([ + 'created_at', + instanceRange, + ]); +}); + +test.each([ + [VizType.Table, VizType.Pie], + ['cal_heatmap', VizType.Table], +])( + 'changing a new %s chart to %s keeps the dataset default time filter', + (from, to) => { + const formData = withControlPanels(() => + changeChartType( + hydrateNewChart({ vizType: from }).explore as ExploreState, + to, + ), + ); + expect(getTimeFilter(formData)).toEqual(['created_at', datasetRange]); + }, +); + +test('changing the chart type after a dataset switch keeps that dataset default', () => { + const formData = withControlPanels(() => + changeChartType( + switchNewChartDataset({ ...otherTimeColumn, extra: datasetExtra }), + VizType.Pie, + ), + ); + expect(getTimeFilter(formData)).toEqual(['event_date', datasetRange]); +}); + test('extracts currency formats from metrics in dataset', () => { const dispatch = jest.fn(); const getState = jest.fn(() => ({ diff --git a/superset-frontend/src/explore/actions/hydrateExplore.ts b/superset-frontend/src/explore/actions/hydrateExplore.ts index 2a12317ffee6..648e87004ffd 100644 --- a/superset-frontend/src/explore/actions/hydrateExplore.ts +++ b/superset-frontend/src/explore/actions/hydrateExplore.ts @@ -16,7 +16,10 @@ * specific language governing permissions and limitations * under the License. */ -import { ControlStateMapping } from '@superset-ui/chart-controls'; +import { + ControlStateMapping, + getDatasetDefaultTimeFilter, +} from '@superset-ui/chart-controls'; import { ChartState, @@ -112,12 +115,12 @@ export const hydrateExplore = : [initialSlice, initialFormData]; const initialSliceName = primarySliceNameSource?.slice_name ?? fallbackSliceNameSource?.slice_name; + const isNewChart = !initialSlice && !sliceId; // Only identities and empty filter containers are free of selections. // Stamp before defaults, controls and chart query snapshots are constructed. // The replaced state's stash is discarded by HYDRATE_EXPLORE, so it is ignored. if ( - !initialSlice && - !sliceId && + isNewChart && dataset.type === DatasourceType.SemanticView && dataset.semantic_selection_version && Object.entries(initialFormData).every(isNeutralNewChartEntry) @@ -130,9 +133,12 @@ export const hydrateExplore = initialFormData.viz_type = getUrlParam(URL_PARAMS.vizType) || defaultVizType; } + const initialTimeRange = + (isNewChart && getDatasetDefaultTimeFilter(dataset)) || + common?.conf?.DEFAULT_TIME_FILTER || + NO_TIME_RANGE; if (!initialFormData.time_range) { - initialFormData.time_range = - common?.conf?.DEFAULT_TIME_FILTER || NO_TIME_RANGE; + initialFormData.time_range = initialTimeRange; } if ( initialFormData.include_time && @@ -248,10 +254,11 @@ export const hydrateExplore = // apply initial mapStateToProps for all controls, must execute AFTER // bootstrapState has initialized `controls`. Order of execution is not // guaranteed, so controls shouldn't rely on each other's mapped state. + const controlPanelState = { ...exploreState, initialTimeRange }; Object.entries(exploreState.controls).forEach(([key, controlState]) => { exploreState.controls[key] = applyMapStateToPropsToControl( controlState, - exploreState, + controlPanelState, ); }); const hydratedFormData = { diff --git a/superset-frontend/src/explore/components/ControlPanelsContainer.test.tsx b/superset-frontend/src/explore/components/ControlPanelsContainer.test.tsx index dd01f517171d..d00281d2f654 100644 --- a/superset-frontend/src/explore/components/ControlPanelsContainer.test.tsx +++ b/superset-frontend/src/explore/components/ControlPanelsContainer.test.tsx @@ -968,6 +968,96 @@ describe('ControlPanelsContainer', () => { }); }); + const datasourceWithDefaultTimeFilter: Dataset = { + id: 1, + type: DatasourceType.Table, + datasource_name: 'events', + description: null, + column_formats: {}, + verbose_map: {}, + main_dttm_col: 'ds', + always_filter_main_dttm: false, + columns: [{ column_name: 'ds', is_dttm: true }], + metrics: [], + extra: JSON.stringify({ default_time_filter: 'Last day' }), + }; + + test('the X-axis prompt adds a time filter with the dataset default time filter', async () => { + const setControlValue = jest.fn(); + const props = { + ...getDefaultProps(), + actions: { setControlValue }, + form_data: { datasource: '1__table', viz_type: 'table', x_axis: 'ds' }, + exploreState: { datasource: datasourceWithDefaultTimeFilter }, + } as unknown as ControlPanelsContainerProps; + render(, { + useRedux: true, + initialState: { + explore: { datasource: datasourceWithDefaultTimeFilter }, + }, + }); + + await userEvent.click(await screen.findByRole('button', { name: 'Yes' })); + + expect(setControlValue).toHaveBeenCalledWith('adhoc_filters', [ + expect.objectContaining({ subject: 'ds', comparator: 'Last day' }), + ]); + }); + + test('deleting the last time filter resets it to the dataset default time filter', async () => { + getChartControlPanelRegistry().remove('table'); + getChartControlPanelRegistry().registerValue('table', { + controlPanelSections: [ + { + label: t('Query'), + expanded: true, + controlSetRows: [['adhoc_filters']], + }, + ], + }); + const filter = { + expressionType: 'SIMPLE', + clause: 'WHERE', + subject: 'ds', + operator: 'TEMPORAL_RANGE', + comparator: NO_TIME_RANGE, + }; + const formData = { datasource: '1__table', viz_type: 'table' }; + const exploreState = { + controls: {}, + form_data: formData, + datasource: datasourceWithDefaultTimeFilter, + }; + const setControlValue = jest.fn(); + const props = { + ...getDefaultProps(), + actions: { setControlValue }, + controls: { + adhoc_filters: getControlStateFromControlConfig( + sharedControls.adhoc_filters, + exploreState as Parameters< + typeof getControlStateFromControlConfig + >[1], + [filter], + ), + }, + form_data: { ...formData, adhoc_filters: [filter] }, + exploreState, + } as unknown as ControlPanelsContainerProps; + render(, { + useRedux: true, + initialState: { + explore: { datasource: datasourceWithDefaultTimeFilter }, + }, + }); + + await userEvent.click(await screen.findByTestId('remove-control-button')); + + expect(setControlValue).toHaveBeenCalledWith('adhoc_filters', [ + expect.objectContaining({ subject: 'ds', comparator: 'Last day' }), + ]); + }); + function createStoreBackedExplore() { const datasource = { id: 1, diff --git a/superset-frontend/src/explore/components/ControlPanelsContainer.tsx b/superset-frontend/src/explore/components/ControlPanelsContainer.tsx index eb4ef345ae04..6374dd28c784 100644 --- a/superset-frontend/src/explore/components/ControlPanelsContainer.tsx +++ b/superset-frontend/src/explore/components/ControlPanelsContainer.tsx @@ -37,7 +37,6 @@ import { isDefined, isAdhocColumn, JsonValue, - NO_TIME_RANGE, usePrevious, isFeatureEnabled, FeatureFlag, @@ -87,6 +86,7 @@ import { ExploreAlert } from './ExploreAlert'; import { RunQueryButton } from './RunQueryButton'; import { CONTROL_SECTIONS_ID, Operators } from '../constants'; import { Clauses } from './controls/FilterControl/types'; +import { useDefaultTimeFilter } from './controls/DateFilterControl/utils'; import StashFormDataContainer from './StashFormDataContainer'; const TABS_KEYS = { @@ -321,9 +321,7 @@ export const ControlPanelsContainer = (props: ControlPanelsContainerProps) => { string[] | undefined >(state => state.explore.controlsTransferred); - const defaultTimeFilter = useSelector( - state => state.common?.conf?.DEFAULT_TIME_FILTER || NO_TIME_RANGE, - ); + const defaultTimeFilter = useDefaultTimeFilter(props.exploreState.datasource); const { form_data, actions } = props; const { setControlValue } = actions; @@ -633,8 +631,8 @@ export const ControlPanelsContainer = (props: ControlPanelsContainerProps) => { if (!controls?.time_range?.value && isTemporalRange(valueToBeDeleted)) { const count = values.filter(isTemporalRange).length; if (count === 1) { - // if temporal filter's value is "No filter", prevent deletion - // otherwise reset the value to "No filter" + // if the temporal filter has the default time range, prevent + // deletion, otherwise reset it to the default time range if (valueToBeDeleted.comparator === defaultTimeFilter) { return t( `You cannot delete the last temporal filter as it's used for time range filters in dashboards.`, diff --git a/superset-frontend/src/explore/components/controls/DateFilterControl/DateFilterLabel.tsx b/superset-frontend/src/explore/components/controls/DateFilterControl/DateFilterLabel.tsx index f8b8a904964f..14ef8e9d5233 100644 --- a/superset-frontend/src/explore/components/controls/DateFilterControl/DateFilterLabel.tsx +++ b/superset-frontend/src/explore/components/controls/DateFilterControl/DateFilterLabel.tsx @@ -156,6 +156,7 @@ export default function DateFilterLabel(props: DateFilterControlProps) { const defaultTimeFilter = useDefaultTimeFilter(); const value = props.value ?? defaultTimeFilter; + const placeholder = props.value == null ? props.placeholder : undefined; const [actualTimeRange, setActualTimeRange] = useState(value); const [show, setShow] = useState(false); @@ -426,9 +427,9 @@ export default function DateFilterLabel(props: DateFilterControlProps) { name={name} aria-labelledby={`filter-name-${props.name}`} aria-describedby={`date-label-${props.name}`} - label={actualTimeRange} + label={placeholder ?? actualTimeRange} isActive={show} - isPlaceholder={actualTimeRange === NO_TIME_RANGE} + isPlaceholder={!!placeholder || actualTimeRange === NO_TIME_RANGE} ref={labelRef} /> diff --git a/superset-frontend/src/explore/components/controls/DateFilterControl/types.ts b/superset-frontend/src/explore/components/controls/DateFilterControl/types.ts index 6d233c7a9f8a..38757246a1a8 100644 --- a/superset-frontend/src/explore/components/controls/DateFilterControl/types.ts +++ b/superset-frontend/src/explore/components/controls/DateFilterControl/types.ts @@ -113,6 +113,7 @@ export interface DateFilterControlProps { name: string; onChange: (timeRange: string) => void; value?: string; + placeholder?: string; onOpenPopover?: () => void; onClosePopover?: () => void; isOverflowingFilterBar?: boolean; diff --git a/superset-frontend/src/explore/components/controls/DateFilterControl/utils/dateFilterUtils.ts b/superset-frontend/src/explore/components/controls/DateFilterControl/utils/dateFilterUtils.ts index d5d0737014c4..7cfb73d119fe 100644 --- a/superset-frontend/src/explore/components/controls/DateFilterControl/utils/dateFilterUtils.ts +++ b/superset-frontend/src/explore/components/controls/DateFilterControl/utils/dateFilterUtils.ts @@ -21,6 +21,10 @@ import { JsonObject, customTimeRangeDecode, } from '@superset-ui/core'; +import { + Dataset, + getDatasetDefaultTimeFilter, +} from '@superset-ui/chart-controls'; import { useSelector } from 'react-redux'; import { COMMON_RANGE_VALUES_SET, @@ -48,10 +52,11 @@ export const guessFrame = (timeRange: string): FrameType => { return 'Advanced'; }; -export function useDefaultTimeFilter() { +export function useDefaultTimeFilter(dataset?: Pick) { + const instanceDefault = useSelector( + (state: JsonObject) => state?.common?.conf?.DEFAULT_TIME_FILTER, + ); return ( - useSelector( - (state: JsonObject) => state?.common?.conf?.DEFAULT_TIME_FILTER, - ) ?? NO_TIME_RANGE + getDatasetDefaultTimeFilter(dataset) || instanceDefault || NO_TIME_RANGE ); } diff --git a/superset-frontend/src/explore/components/controls/DndColumnSelectControl/DndFilterSelect.test.tsx b/superset-frontend/src/explore/components/controls/DndColumnSelectControl/DndFilterSelect.test.tsx index b7422f6e6f08..03318fa18052 100644 --- a/superset-frontend/src/explore/components/controls/DndColumnSelectControl/DndFilterSelect.test.tsx +++ b/superset-frontend/src/explore/components/controls/DndColumnSelectControl/DndFilterSelect.test.tsx @@ -335,6 +335,28 @@ test('when disallow_adhoc_metrics is set, can drop a column from the simple colu expect(within(filterConfigPopup).getByText('column_b')).toBeInTheDocument(); }); +test('dropping a temporal column adds a time filter with the dataset default time filter', async () => { + const column = { column_name: 'ds', is_dttm: true }; + render( + setup({ + datasource: { + ...PLACEHOLDER_DATASOURCE, + columns: [column], + extra: JSON.stringify({ default_time_filter: 'Last day' }), + }, + columns: [column], + }), + { useDndKit: true, store }, + ); + + act(() => { + simulateDrop(captured, { type: DndItemType.Column, value: column }); + }); + + const filterConfigPopup = await screen.findByTestId('filter-edit-popover'); + expect(within(filterConfigPopup).getByText('Last day')).toBeInTheDocument(); +}); + test('when disallow_adhoc_metrics is set, cannot drop anything but a simple column selection', async () => { const adhocMetric = new AdhocMetric({ expression: 'AVG(birth_names.num)', diff --git a/superset-frontend/src/explore/components/controls/DndColumnSelectControl/DndFilterSelect.tsx b/superset-frontend/src/explore/components/controls/DndColumnSelectControl/DndFilterSelect.tsx index 0c50488c14f5..c66d8def0766 100644 --- a/superset-frontend/src/explore/components/controls/DndColumnSelectControl/DndFilterSelect.tsx +++ b/superset-frontend/src/explore/components/controls/DndColumnSelectControl/DndFilterSelect.tsx @@ -398,7 +398,7 @@ const DndFilterSelect = (props: DndFilterSelectProps) => { togglePopover(true); }, [togglePopover]); - const defaultTimeFilter = useDefaultTimeFilter(); + const defaultTimeFilter = useDefaultTimeFilter(props.datasource); const adhocFilter = useMemo(() => { if (isSavedMetric(droppedItem)) { return new AdhocFilter({ @@ -430,7 +430,7 @@ const DndFilterSelect = (props: DndFilterSelectProps) => { config.comparator = defaultTimeFilter; } return new AdhocFilter(config); - }, [droppedItem]); + }, [droppedItem, defaultTimeFilter]); const canDrop = useCallback( (item: DatasourcePanelDndItem) => { diff --git a/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent/AdhocFilterEditPopoverSimpleTabContent.test.tsx b/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent/AdhocFilterEditPopoverSimpleTabContent.test.tsx index 9bb76e7fc705..088a9f7f7426 100644 --- a/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent/AdhocFilterEditPopoverSimpleTabContent.test.tsx +++ b/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent/AdhocFilterEditPopoverSimpleTabContent.test.tsx @@ -476,6 +476,38 @@ test('editing a dashboard-inherited time range filter clears isExtra so the new expect(editedFilter.isExtra).toBe(false); }); +test('the date picker of a temporal filter without a time range starts with the dataset default time filter', async () => { + const timeRangeEndpoint = 'glob:*/api/v1/time_range/*'; + fetchMock.get( + timeRangeEndpoint, + { result: [{ since: '', until: '', timeRange: 'Last day' }] }, + { name: timeRangeEndpoint }, + ); + try { + setup({ + adhocFilter: new AdhocFilter({ + expressionType: ExpressionTypes.Simple, + subject: 'ds', + operatorId: Operators.GreaterThanOrEqual, + operator: + OPERATOR_ENUM_TO_OPERATOR_TYPE[Operators.GreaterThanOrEqual] + .operation, + comparator: '2024-01-01', + clause: Clauses.Where, + }), + datasource: { + ...TestDataset, + columns: [{ column_name: 'ds', is_dttm: true }], + extra: JSON.stringify({ default_time_filter: 'Last day' }), + filter_select: false, + }, + }); + expect(await screen.findByText('Last day')).toBeInTheDocument(); + } finally { + fetchMock.removeRoute(timeRangeEndpoint); + } +}); + test('editing a dashboard-inherited filter comparator clears isExtra so the new value is kept on save', () => { const inheritedFilter = new AdhocFilter({ expressionType: ExpressionTypes.Simple, diff --git a/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent/index.tsx b/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent/index.tsx index 49393c1c1574..d6524f9f4285 100644 --- a/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent/index.tsx +++ b/superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterEditPopoverSimpleTabContent/index.tsx @@ -156,7 +156,7 @@ export interface AdvancedDataTypesState { } export const useSimpleTabFilterProps = (props: Props) => { - const defaultTimeFilter = useDefaultTimeFilter(); + const defaultTimeFilter = useDefaultTimeFilter(props.datasource); const isOperatorRelevant = (operator: Operators, subject: string) => { const column = props.datasource.columns?.find( @@ -388,6 +388,7 @@ export const useSimpleTabFilterProps = (props: Props) => { isOperatorRelevant, clearOperator, onDatePickerChange, + defaultTimeFilter, }; }; @@ -398,6 +399,7 @@ const AdhocFilterEditPopoverSimpleTabContent: FC = props => { isOperatorRelevant, onComparatorChange, onDatePickerChange, + defaultTimeFilter, } = useSimpleTabFilterProps(props); const [comparator, setComparator] = useState(props.adhocFilter.comparator); const comparatorInputRef = useRef(null); @@ -592,9 +594,9 @@ const AdhocFilterEditPopoverSimpleTabContent: FC = props => { ? props.adhocFilter.subject : undefined, timeRange: - props.adhocFilter.operator === Operators.TemporalRange + (props.adhocFilter.operator === Operators.TemporalRange ? (props.adhocFilter.comparator as string | undefined) - : undefined, + : undefined) ?? defaultTimeFilter, datasource: props.datasource, onChange: onDatePickerChange, }); diff --git a/superset-frontend/src/explore/exploreUtils/index.ts b/superset-frontend/src/explore/exploreUtils/index.ts index ba3fb033a9b6..a036ba3d7e36 100644 --- a/superset-frontend/src/explore/exploreUtils/index.ts +++ b/superset-frontend/src/explore/exploreUtils/index.ts @@ -29,7 +29,12 @@ import { SupersetClient, SetDataMaskHook, JsonObject, + NO_TIME_RANGE, } from '@superset-ui/core'; +import { + Dataset, + getDatasetDefaultTimeFilter, +} from '@superset-ui/chart-controls'; import { availableDomains } from 'src/utils/hostNamesConfig'; import { safeStringify } from 'src/utils/safeStringify'; import { optionLabel } from 'src/utils/common'; @@ -530,3 +535,21 @@ export function formatSelectOptions( ): [T, string][] { return options.map(opt => [opt, opt.toString()]); } + +/** + * Returns the range of the time filter Explore adds while it opens a chart: + * the dataset's default time filter for a new chart, otherwise the instance + * default. A `time_range` carried in the form data (for example SQL Lab's + * `'No filter'`) is ignored, as it was before dataset defaults existed. + */ +export function getInitialTimeRange( + isNewChart: boolean, + dataset: Pick | null | undefined, + defaultTimeFilter?: string, +): string { + return ( + (isNewChart && getDatasetDefaultTimeFilter(dataset)) || + defaultTimeFilter || + NO_TIME_RANGE + ); +} diff --git a/superset/commands/dataset/update.py b/superset/commands/dataset/update.py index eb0a7347c758..987723c8529c 100644 --- a/superset/commands/dataset/update.py +++ b/superset/commands/dataset/update.py @@ -58,7 +58,11 @@ validate_transform, ) from superset.daos.dataset import DatasetDAO -from superset.datasets.schemas import FolderSchema +from superset.datasets.schemas import ( + FolderSchema, + get_default_time_filter, + validate_default_time_filter, +) from superset.exceptions import ( QueryClauseValidationException, SupersetParseError, @@ -172,6 +176,7 @@ def validate(self) -> None: self._validate_dataset_source(exceptions) self._validate_semantics(exceptions) + self._validate_default_time_filter(exceptions) if ( self._delete_metric_ids is not None and not DatasetDAO.validate_metrics_exist( @@ -928,6 +933,21 @@ def _validate_fetch_values_predicate( ) ) + def _validate_default_time_filter(self, exceptions: list[ValidationError]) -> None: + """ + Validate a new or changed ``extra.default_time_filter``. An unchanged value + is not checked again, so it never blocks an unrelated edit. + """ + if "extra" not in self._properties: + return + model = cast(SqlaTable, self._model) + time_range = get_default_time_filter(self._properties["extra"]) + if time_range and time_range != get_default_time_filter(model.extra): + try: + validate_default_time_filter(time_range) + except ValidationError as ex: + exceptions.append(ex) + @staticmethod def _get_duplicates(data: list[dict[str, Any]], key: str) -> list[str]: duplicates = [ diff --git a/superset/datasets/schemas.py b/superset/datasets/schemas.py index 899ceb615cb3..96510e2e8331 100644 --- a/superset/datasets/schemas.py +++ b/superset/datasets/schemas.py @@ -43,6 +43,7 @@ from superset.subjects.schemas import SubjectReferenceField from superset.utils import json from superset.utils.core import FilterOperator +from superset.utils.date_parser import get_since_until from superset.utils.number_format import is_valid_d3_format from superset.utils.schema import DiscardIsManagedExternallyMixin @@ -117,6 +118,36 @@ def validate_partition_key(value: str) -> None: ) +def get_default_time_filter(extra: Any) -> str | None: + """ + Return a dataset's ``extra.default_time_filter`` from its ``extra``, given as + a JSON string or a dict. Like Explore, treat unparseable metadata, + non-string values and empty strings as unset. + """ + if isinstance(extra, str): + try: + extra = json.loads(extra) + except ValueError: + return None + time_range = extra.get("default_time_filter") if isinstance(extra, dict) else None + return time_range if isinstance(time_range, str) and time_range else None + + +def validate_default_time_filter(time_range: str) -> None: + """ + Reject a dataset default time filter that the time range parser cannot + evaluate, since every new chart on the dataset would fail to query. + """ + try: + get_since_until(time_range=time_range) + except (ValueError, ValidationError) as ex: + # `str`, because marshmallow reads a lazy string as a list of messages. + raise ValidationError( + str(_("Invalid default time filter: %(range)s", range=time_range)), + field_name="extra", + ) from ex + + class ResolveIsCertifiedMixin(Schema): """ ``is_certified`` is derived from ``certified_by``/``certification_details``. @@ -520,6 +551,16 @@ def fix_extra(self, data: dict[str, Any], **kwargs: Any) -> dict[str, Any]: return data + @validates_schema + def validate_extra_default_time_filter( + self, data: dict[str, Any], **kwargs: Any + ) -> None: + """ + Reject a default time filter that new charts could not query. + """ + if time_range := get_default_time_filter(data.get("extra")): + validate_default_time_filter(time_range) + @validates_schema def validate_unique_child_uuids(self, data: dict[str, Any], **kwargs: Any) -> None: """ diff --git a/superset/translations/messages.pot b/superset/translations/messages.pot index 11093c8f2965..fdd19547a38e 100644 --- a/superset/translations/messages.pot +++ b/superset/translations/messages.pot @@ -5368,6 +5368,9 @@ msgstr "" msgid "Default sort" msgstr "" +msgid "Default time filter" +msgstr "" + msgid "Default value must be set when \"Filter has default value\" is checked" msgstr "" @@ -8433,6 +8436,10 @@ msgstr "" msgid "Invalid date/timestamp format" msgstr "" +#, python-format +msgid "Invalid default time filter: %(range)s" +msgstr "" + #, python-format msgid "Invalid domain(s): %s" msgstr "" @@ -16703,6 +16710,9 @@ msgstr "" msgid "Time range" msgstr "" +msgid "Time range of the time filters Explore adds for this dataset, such as on new charts." +msgstr "" + msgid "Time ratio" msgstr "" @@ -17490,6 +17500,9 @@ msgstr "" msgid "Use gradient" msgstr "" +msgid "Use instance default" +msgstr "" + msgid "Use metric definition" msgstr "" diff --git a/tests/unit_tests/commands/dataset/update_test.py b/tests/unit_tests/commands/dataset/update_test.py index 2de6aed42d7b..67806eb7285c 100644 --- a/tests/unit_tests/commands/dataset/update_test.py +++ b/tests/unit_tests/commands/dataset/update_test.py @@ -44,6 +44,7 @@ from superset.models.core import Database from superset.sql.parse import Table from superset.subjects.exceptions import SubjectsNotFoundValidationError +from superset.utils import json from tests.unit_tests.conftest import with_feature_flags @@ -2885,3 +2886,28 @@ def test_a_jinja_transform_is_rejected_on_an_unsupported_engine_too( command._validate_partition_mapping(exceptions) assert [exc.field_name for exc in exceptions] == ["partition_value_transform"] + + +@pytest.mark.parametrize( + "stored, requested, field_names", + [ + (None, "Last week", []), + (None, "Last dya", ["extra"]), + ("Last week", "Last dya", ["extra"]), + # An unchanged value is not checked again. + ("Last dya", "Last dya", []), + ], +) +def test_update_dataset_validates_a_new_default_time_filter( + stored: str | None, requested: str, field_names: list[str] +) -> None: + """Only a new or changed default time filter is validated.""" + command = UpdateDatasetCommand( + 1, {"extra": json.dumps({"default_time_filter": requested})} + ) + command._model = MagicMock(extra=json.dumps({"default_time_filter": stored})) + + exceptions: list[ValidationError] = [] + command._validate_default_time_filter(exceptions) + + assert [exc.field_name for exc in exceptions] == field_names diff --git a/tests/unit_tests/datasets/commands/importers/v1/import_test.py b/tests/unit_tests/datasets/commands/importers/v1/import_test.py index 614633387704..9a3d1c0f5277 100644 --- a/tests/unit_tests/datasets/commands/importers/v1/import_test.py +++ b/tests/unit_tests/datasets/commands/importers/v1/import_test.py @@ -1368,6 +1368,33 @@ def test_import_dataset_schema_rejects_duplicate_column_uuids() -> None: assert duplicate in str(excinfo.value.messages["columns"]) +@pytest.mark.parametrize( + "extra", [{"default_time_filter": "Last dya"}, '{"default_time_filter": "foo"}'] +) +def test_import_dataset_schema_rejects_an_invalid_default_time_filter( + extra: Any, +) -> None: + """An import with a default time filter the parser rejects fails.""" + config = {**_dataset_config_with_children(metrics=[], columns=[]), "extra": extra} + + with pytest.raises(ValidationError) as excinfo: + ImportV1DatasetSchema().load(config) + + assert "extra" in excinfo.value.messages + + +def test_import_dataset_schema_accepts_a_valid_default_time_filter() -> None: + """A valid default time filter is imported unchanged.""" + config = { + **_dataset_config_with_children(metrics=[], columns=[]), + "extra": {"default_time_filter": "Last week"}, + } + + assert ImportV1DatasetSchema().load(config)["extra"] == { + "default_time_filter": "Last week" + } + + def test_import_dataset_schema_allows_distinct_and_missing_child_uuids() -> None: """ Distinct UUIDs — and children with no UUID at all — remain valid. diff --git a/tests/unit_tests/datasets/schema_tests.py b/tests/unit_tests/datasets/schema_tests.py index bf803e2872c0..ea3f8ee07749 100644 --- a/tests/unit_tests/datasets/schema_tests.py +++ b/tests/unit_tests/datasets/schema_tests.py @@ -23,6 +23,8 @@ from pytest_mock import MockerFixture from superset.datasets.schemas import ( + get_default_time_filter, + validate_default_time_filter, validate_partition_key, validate_python_date_format, ) @@ -55,6 +57,40 @@ def test_validate_python_date_format_raises(payload) -> None: validate_python_date_format(payload) +@pytest.mark.parametrize( + "extra, expected", + [ + ('{"default_time_filter": "Last week", "warning_markdown": "x"}', "Last week"), + ({"default_time_filter": "No filter"}, "No filter"), + ('{"default_time_filter": ""}', None), + ('{"default_time_filter": 7}', None), + ("{bad", None), + ("[]", None), + (None, None), + ], +) +def test_get_default_time_filter(extra: Any, expected: str | None) -> None: + """Unparseable extra, non-string and empty values count as unset.""" + assert get_default_time_filter(extra) == expected + + +@pytest.mark.parametrize( + "time_range", + ["No filter", "Last week", "Current day", "2024-01-01 : now", "yesterday : today"], +) +def test_validate_default_time_filter(time_range: str) -> None: + """Ranges the time range parser can evaluate are accepted.""" + validate_default_time_filter(time_range) + + +@pytest.mark.parametrize("time_range", ["Last dya", " ", "now : 2024-01-01"]) +def test_validate_default_time_filter_raises(time_range: str) -> None: + """Ranges the parser rejects are reported on the extra field.""" + with pytest.raises(ValidationError) as excinfo: + validate_default_time_filter(time_range) + assert excinfo.value.field_name == "extra" + + def test_drill_info_user_schema_does_not_expose_email() -> None: """ Regression test: the drill_info-local ``UserSchema`` used to declare an