Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(sqllab): Remove functionNames from sqlLab state #24026

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
2 changes: 1 addition & 1 deletion superset-frontend/spec/helpers/testing-library.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export function createWrapper(options?: Options) {
result = <DndProvider backend={HTML5Backend}>{result}</DndProvider>;
}

if (useRedux) {
if (useRedux || store) {
const mockStore =
store ?? createStore(initialState, reducers || reducerIndex);
result = <Provider store={mockStore}>{result}</Provider>;
Expand Down
31 changes: 0 additions & 31 deletions superset-frontend/src/SqlLab/actions/sqlLab.js
Original file line number Diff line number Diff line change
Expand Up @@ -1555,34 +1555,3 @@ export function createCtasDatasource(vizOptions) {
});
};
}

export function queryEditorSetFunctionNames(queryEditor, dbId) {
return function (dispatch) {
return SupersetClient.get({
endpoint: encodeURI(`/api/v1/database/${dbId}/function_names/`),
})
.then(({ json }) =>
dispatch({
type: QUERY_EDITOR_SET_FUNCTION_NAMES,
queryEditor,
functionNames: json.function_names,
}),
)
.catch(err => {
if (err.status === 404) {
// for databases that have been deleted, just reset the function names
dispatch({
type: QUERY_EDITOR_SET_FUNCTION_NAMES,
queryEditor,
functionNames: [],
});
} else {
dispatch(
addDangerToast(
t('An error occurred while fetching function names.'),
),
);
}
});
};
}
25 changes: 17 additions & 8 deletions superset-frontend/src/SqlLab/components/AceEditorWrapper/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,14 @@
*/
import React, { useState, useEffect, useRef, useMemo } from 'react';
import { useDispatch } from 'react-redux';
import { css, styled, usePrevious } from '@superset-ui/core';
import { css, styled, usePrevious, t } from '@superset-ui/core';

import { areArraysShallowEqual } from 'src/reduxUtils';
import sqlKeywords from 'src/SqlLab/utils/sqlKeywords';
import {
queryEditorSetSelectedText,
queryEditorSetFunctionNames,
addTable,
addDangerToast,
} from 'src/SqlLab/actions/sqlLab';
import {
SCHEMA_AUTOCOMPLETE_SCORE,
Expand All @@ -40,6 +40,7 @@ import {
} from 'src/components/AsyncAceEditor';
import useQueryEditor from 'src/SqlLab/hooks/useQueryEditor';
import { useSchemas, useTables } from 'src/hooks/apiResources';
import { useDatabaseFunctionsQuery } from 'src/hooks/apiResources/databaseFunctions';

type HotKey = {
key: string;
Expand Down Expand Up @@ -95,7 +96,6 @@ const AceEditorWrapper = ({
'id',
'dbId',
'sql',
'functionNames',
'validationResult',
'schema',
]);
Expand All @@ -109,8 +109,20 @@ const AceEditorWrapper = ({
}),
});

const { data: functionNames, isError } = useDatabaseFunctionsQuery(
{ dbId: queryEditor.dbId },
{ skip: !autocomplete || !queryEditor.dbId },
);

useEffect(() => {
if (isError) {
dispatch(
addDangerToast(t('An error occurred while fetching function names.')),
);
}
}, [dispatch, isError]);

const currentSql = queryEditor.sql ?? '';
const functionNames = queryEditor.functionNames ?? [];

// Loading schema, table and column names as auto-completable words
const { schemas, schemaWords } = useMemo(
Expand Down Expand Up @@ -139,9 +151,6 @@ const AceEditorWrapper = ({
useEffect(() => {
// Making sure no text is selected from previous mount
dispatch(queryEditorSetSelectedText(queryEditor, null));
if (queryEditor.dbId) {
dispatch(queryEditorSetFunctionNames(queryEditor, queryEditor.dbId));
}
setAutoCompleter();
}, []);

Expand Down Expand Up @@ -238,7 +247,7 @@ const AceEditorWrapper = ({
meta: 'column',
}));

const functionWords = functionNames.map(func => ({
const functionWords = (functionNames ?? []).map(func => ({
name: func,
value: func,
score: SQL_FUNCTIONS_AUTOCOMPLETE_SCORE,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ import querystring from 'query-string';

import {
queryEditorSetDb,
queryEditorSetFunctionNames,
addTable,
removeTables,
collapseTable,
Expand Down Expand Up @@ -142,7 +141,6 @@ const SqlEditorLeftBar = ({
const onDbChange = ({ id: dbId }: { id: number }) => {
setEmptyState(false);
dispatch(queryEditorSetDb(queryEditor, dbId));
dispatch(queryEditorSetFunctionNames(queryEditor, dbId));
};

const selectedTableNames = useMemo(
Expand Down
1 change: 0 additions & 1 deletion superset-frontend/src/SqlLab/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,6 @@ export const defaultQueryEditor = {
name: 'Untitled Query 1',
schema: 'main',
remoteId: null,
functionNames: [],
hideLeftBar: false,
templateParams: '{}',
};
Expand Down
2 changes: 0 additions & 2 deletions superset-frontend/src/SqlLab/reducers/getInitialState.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ export default function getInitialState({
autorun: false,
templateParams: null,
dbId: defaultDbId,
functionNames: [],
queryLimit: common.conf.DEFAULT_SQLLAB_LIMIT,
validationResult: {
id: null,
Expand Down Expand Up @@ -87,7 +86,6 @@ export default function getInitialState({
autorun: activeTab.autorun,
templateParams: activeTab.template_params || undefined,
dbId: activeTab.database_id,
functionNames: [],
schema: activeTab.schema,
queryLimit: activeTab.query_limit,
validationResult: {
Expand Down
12 changes: 0 additions & 12 deletions superset-frontend/src/SqlLab/reducers/sqlLab.js
Original file line number Diff line number Diff line change
Expand Up @@ -563,18 +563,6 @@ export default function sqlLabReducer(state = {}, action) {
),
};
},
[actions.QUERY_EDITOR_SET_FUNCTION_NAMES]() {
return {
...state,
...alterUnsavedQueryEditorState(
state,
{
functionNames: action.functionNames,
},
action.queryEditor.id,
),
};
},
[actions.QUERY_EDITOR_SET_SCHEMA]() {
return {
...state,
Expand Down
9 changes: 5 additions & 4 deletions superset-frontend/src/SqlLab/reducers/sqlLab.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -209,14 +209,15 @@ describe('sqlLabReducer', () => {
newState = sqlLabReducer(newState, action);
expect(newState.unsavedQueryEditor.sql).toBe(expectedSql);
const interceptedAction = {
type: actions.QUERY_EDITOR_SET_FUNCTION_NAMES,
type: actions.QUERY_EDITOR_PERSIST_HEIGHT,
queryEditor: newState.queryEditors[0],
functionNames: ['func1', 'func2'],
northPercent: 46,
southPercent: 54,
};
newState = sqlLabReducer(newState, interceptedAction);
expect(newState.unsavedQueryEditor.sql).toBe(expectedSql);
expect(newState.queryEditors[0].functionNames).toBe(
interceptedAction.functionNames,
expect(newState.queryEditors[0].northPercent).toBe(
interceptedAction.northPercent,
);
});
});
Expand Down
1 change: 0 additions & 1 deletion superset-frontend/src/SqlLab/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ export interface QueryEditor {
autorun: boolean;
sql: string;
remoteId: number | null;
functionNames: string[];
validationResult?: {
completed: boolean;
errors: SupersetError[];
Expand Down
92 changes: 92 additions & 0 deletions superset-frontend/src/hooks/apiResources/databaseFunctions.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/**
* 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 { act, renderHook } from '@testing-library/react-hooks';
import {
createWrapper,
defaultStore as store,
} from 'spec/helpers/testing-library';
import { api } from 'src/hooks/apiResources/queryApi';
import { useDatabaseFunctionsQuery } from './databaseFunctions';

const fakeApiResult = {
function_names: ['abs', 'avg', 'sum'],
};

const expectedResult = fakeApiResult.function_names;
const expectDbId = 'db1';
const dbFunctionNamesApiRoute = `glob:*/api/v1/database/${expectDbId}/function_names/`;

afterEach(() => {
fetchMock.reset();
act(() => {
store.dispatch(api.util.resetApiState());
});
});

beforeEach(() => {
fetchMock.get(dbFunctionNamesApiRoute, fakeApiResult);
});

test('returns api response mapping json result', async () => {
const { result, waitFor } = renderHook(
() =>
useDatabaseFunctionsQuery({
dbId: expectDbId,
}),
{
wrapper: createWrapper({
useRedux: true,
store,
}),
},
);
await waitFor(() =>
expect(fetchMock.calls(dbFunctionNamesApiRoute).length).toBe(1),
);
expect(result.current.data).toEqual(expectedResult);
expect(fetchMock.calls(dbFunctionNamesApiRoute).length).toBe(1);
act(() => {
result.current.refetch();
});
await waitFor(() =>
expect(fetchMock.calls(dbFunctionNamesApiRoute).length).toBe(2),
);
expect(result.current.data).toEqual(expectedResult);
});

test('returns cached data without api request', async () => {
const { result, waitFor, rerender } = renderHook(
() =>
useDatabaseFunctionsQuery({
dbId: expectDbId,
}),
{
wrapper: createWrapper({
store,
useRedux: true,
}),
},
);
await waitFor(() => expect(result.current.data).toEqual(expectedResult));
expect(fetchMock.calls(dbFunctionNamesApiRoute).length).toBe(1);
rerender();
await waitFor(() => expect(result.current.data).toEqual(expectedResult));
expect(fetchMock.calls(dbFunctionNamesApiRoute).length).toBe(1);
});
45 changes: 45 additions & 0 deletions superset-frontend/src/hooks/apiResources/databaseFunctions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* 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 { api } from './queryApi';

export type FetchDataFunctionsQueryParams = {
dbId?: string | number;
};

type FunctionNamesResponse = {
json: {
function_names: string[];
};
response: Response;
};

const databaseFunctionApi = api.injectEndpoints({
endpoints: builder => ({
databaseFunctions: builder.query<string[], FetchDataFunctionsQueryParams>({
providesTags: ['DatabaseFunctions'],
query: ({ dbId }) => ({
endpoint: `/api/v1/database/${dbId}/function_names/`,
transformResponse: ({ json }: FunctionNamesResponse) =>
json.function_names,
}),
}),
}),
});

export const { useDatabaseFunctionsQuery } = databaseFunctionApi;
2 changes: 1 addition & 1 deletion superset-frontend/src/hooks/apiResources/queryApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export const supersetClientQuery: BaseQueryFn<

export const api = createApi({
reducerPath: 'queryApi',
tagTypes: ['Schemas', 'Tables'],
tagTypes: ['Schemas', 'Tables', 'DatabaseFunctions'],
endpoints: () => ({}),
baseQuery: supersetClientQuery,
});