Skip to content
Open
114 changes: 114 additions & 0 deletions superset-frontend/src/dashboard/actions/datasources.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/**
* 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 { JsonObject, SupersetClient } from '@superset-ui/core';
import { Datasource, DatasourcesState, RootState } from 'src/dashboard/types';
import {
DatasourcesAction,
fetchDatasourceMetadata,
setDatasource,
} from './datasources';

const KEY = '7__table';

type ClientResponse = Awaited<ReturnType<typeof SupersetClient.get>>;

// Minimal typed stand-ins so the tests avoid `any` while exercising the thunk.
const datasource = (json: JsonObject = { uid: KEY, main_dttm_col: 'ds' }) =>
json as unknown as Datasource;

const jsonResponse = (json: JsonObject): ClientResponse =>
({ json }) as unknown as ClientResponse;

const buildGetState =
(datasources: DatasourcesState = {}) =>
() =>
({ datasources }) as unknown as RootState;

afterEach(() => {
jest.restoreAllMocks();
});

test('fetchDatasourceMetadata uses the cached datasource without a network call', () => {
const getSpy = jest.spyOn(SupersetClient, 'get');
const dispatch = jest.fn();
const cached = datasource();

fetchDatasourceMetadata(KEY)(dispatch, buildGetState({ [KEY]: cached }));

expect(getSpy).not.toHaveBeenCalled();
expect(dispatch).toHaveBeenCalledWith(setDatasource(cached, KEY));
});

test('fetchDatasourceMetadata fetches and caches an uncached datasource', async () => {
const json = { uid: KEY, main_dttm_col: 'ds' };
const getSpy = jest
.spyOn(SupersetClient, 'get')
.mockResolvedValue(jsonResponse(json));
const dispatch = jest.fn();

await fetchDatasourceMetadata(KEY)(dispatch, buildGetState());

expect(getSpy).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledWith(
expect.objectContaining({
type: DatasourcesAction.SetDatasource,
key: KEY,
datasource: json,
}),
);
});

test('fetchDatasourceMetadata deduplicates concurrent in-flight requests for the same key', async () => {
let resolveGet: (value: ClientResponse) => void = () => {};
const getSpy = jest.spyOn(SupersetClient, 'get').mockReturnValue(
new Promise<ClientResponse>(resolve => {
resolveGet = resolve;
}),
);
const dispatch = jest.fn();
const getState = buildGetState();

// Two filters using the same dataset mount and dispatch before the first
// request resolves and populates the cache.
fetchDatasourceMetadata(KEY)(dispatch, getState);
fetchDatasourceMetadata(KEY)(dispatch, getState);

expect(getSpy).toHaveBeenCalledTimes(1);

resolveGet(jsonResponse({ uid: KEY, main_dttm_col: 'ds' }));
await Promise.resolve();
});

test('fetchDatasourceMetadata clears the in-flight key after a failed request so it can retry', async () => {
const getSpy = jest
.spyOn(SupersetClient, 'get')
.mockRejectedValueOnce(new Error('boom'))
.mockResolvedValueOnce(jsonResponse({ uid: KEY }));
const dispatch = jest.fn();
const getState = buildGetState();

await expect(
fetchDatasourceMetadata(KEY)(dispatch, getState),
).rejects.toThrow('boom');

// The failed key is no longer in flight, so a subsequent dispatch retries.
await fetchDatasourceMetadata(KEY)(dispatch, getState);

expect(getSpy).toHaveBeenCalledTimes(2);
});
17 changes: 16 additions & 1 deletion superset-frontend/src/dashboard/actions/datasources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ export function setDatasource(datasource: Datasource, key: string) {
};
}

const inFlightDatasourceKeys = new Set<string>();

export function fetchDatasourceMetadata(key: string) {
return (dispatch: Dispatch, getState: () => RootState) => {
const { datasources } = getState();
Expand All @@ -61,8 +63,21 @@ export function fetchDatasourceMetadata(key: string) {
return dispatch(setDatasource(datasource, key));
}

if (inFlightDatasourceKeys.has(key)) {
return undefined;
Comment thread
rusackas marked this conversation as resolved.
Resolved
}

inFlightDatasourceKeys.add(key);
return SupersetClient.get({
endpoint: `/superset/fetch_datasource_metadata?datasourceKey=${key}`,
}).then(({ json }) => dispatch(setDatasource(json as Datasource, key)));
})
.then(({ json }) => {
inFlightDatasourceKeys.delete(key);
return dispatch(setDatasource(json as Datasource, key));
})
.catch((err: unknown) => {
inFlightDatasourceKeys.delete(key);
throw err;
});
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
*/

import { ChartDataResponseResult } from '@superset-ui/core';
import { applyTimeGrainAllowlist } from './FilterValue';
import { applyTimeGrainAllowlist, resolveGranularitySqla } from './FilterValue';

const baseResults = [
{
Expand Down Expand Up @@ -58,3 +58,26 @@ test('applyTimeGrainAllowlist should return unfiltered results when allowlist is
const filtered = applyTimeGrainAllowlist('filter_timegrain', [], baseResults);
expect(filtered).toEqual(baseResults);
});

test('resolveGranularitySqla prefers the filter own granularity_sqla', () => {
expect(resolveGranularitySqla('order_date', true, 'main_dttm')).toEqual(
'order_date',
);
expect(resolveGranularitySqla('order_date', false, 'main_dttm')).toEqual(
'order_date',
);
});

test('resolveGranularitySqla falls back to main_dttm_col when a time_range parent cascades', () => {
expect(resolveGranularitySqla(undefined, true, 'main_dttm')).toEqual(
'main_dttm',
);
});

test('resolveGranularitySqla returns undefined without a time_range dependency', () => {
expect(resolveGranularitySqla(undefined, false, 'main_dttm')).toBeUndefined();
});

test('resolveGranularitySqla returns undefined when the datasource has no main_dttm_col', () => {
expect(resolveGranularitySqla(undefined, true, undefined)).toBeUndefined();
});
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import {
isChartCustomization,
} from '@superset-ui/core';
import { styled, SupersetTheme } from '@apache-superset/core/theme';
import { logging } from '@apache-superset/core/utils';
import { useTheme } from '@emotion/react';
import { useDispatch, useSelector } from 'react-redux';
import { isEqual, isEqualWith } from 'lodash';
Expand All @@ -54,6 +55,7 @@ import {
onFiltersRefreshSuccess,
setDirectPathToChild,
} from 'src/dashboard/actions/dashboardState';
import { fetchDatasourceMetadata } from 'src/dashboard/actions/datasources';
import {
setHoveredChartCustomization,
unsetHoveredChartCustomization,
Expand Down Expand Up @@ -114,6 +116,20 @@ export const applyTimeGrainAllowlist = (
});
};

/**
* Resolve the granularity_sqla a filter should send. A filter's own
* granularity_sqla always wins. Otherwise, when a Date Range parent filter is
* cascading a time_range down, fall back to the datasource's main_dttm_col so
* the temporal WHERE clause can be applied.
*/
export const resolveGranularitySqla = (
granularitySqla: string | undefined,
hasTimeRangeDependency: boolean,
datasourceMainDttmCol: string | undefined,
): string | undefined =>
granularitySqla ||
(hasTimeRangeDependency ? datasourceMainDttmCol : undefined);

const useShouldFilterRefresh = () => {
const isDashboardRefreshing = useSelector<RootState, boolean>(
state => state.dashboardState.isRefreshing,
Expand Down Expand Up @@ -187,6 +203,35 @@ const FilterValue: FC<FilterValueProps> = ({
const [isRefreshing, setIsRefreshing] = useState(false);
const dispatch = useDispatch();

// When a Date Range parent filter is active, the child filter needs
// granularity_sqla to apply the temporal WHERE clause. Read main_dttm_col
// from the Redux datasource cache as a fallback.
//
// The dashboard datasets API (/api/v1/dashboard/:id/datasets) only returns
// datasets used by chart slices, so native-filter-only datasets are never
// in state.datasources. Dispatch fetchDatasourceMetadata at mount time to
// populate the cache explicitly for those datasets.
const datasourceMainDttmCol = useSelector<RootState, string | undefined>(
state =>
datasetId != null
? state.datasources?.[`${datasetId}__table`]?.main_dttm_col
: undefined,
);

useEffect(() => {
if (datasetId != null) {
// Best-effort prime of the datasource cache for the granularity_sqla
// fallback. A failure here is non-fatal — the filter still works, just
// without the time-range cascade fallback — so handle the rejection
// explicitly to avoid an unhandled promise rejection.
Promise.resolve(
dispatch(fetchDatasourceMetadata(`${datasetId}__table`)),
).catch(error =>
logging.warn('Failed to fetch filter datasource metadata', error),
);
}
}, [datasetId, dispatch]);
Comment thread
rusackas marked this conversation as resolved.
Resolved

const { outlinedFilterId, lastUpdated } = useFilterOutlined();

const handleFilterLoadFinish = useCallback(() => {
Expand Down Expand Up @@ -218,7 +263,11 @@ const FilterValue: FC<FilterValueProps> = ({
groupby,
adhoc_filters: adhocFilters,
time_range: timeRange,
granularity_sqla: granularitySqla,
granularity_sqla: resolveGranularitySqla(
granularitySqla,
Boolean(dependencies.time_range),
datasourceMainDttmCol,
),
dashboardId,
});
const filterOwnState = filter.dataMask?.ownState || {};
Expand Down Expand Up @@ -349,6 +398,7 @@ const FilterValue: FC<FilterValueProps> = ({
dataMaskSelected,
setHasDepsFilterValue,
transitiveParentIds,
datasourceMainDttmCol,
]);

useEffect(() => {
Expand Down
Loading