From b7a42656a939066b193778d37c8ee20f80cd0c2f Mon Sep 17 00:00:00 2001 From: Haseeb702 <80732008+Haseeb702@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:54:15 -0500 Subject: [PATCH 01/16] feat(datasets): reuse SQL Lab table browser for dataset creation --- .../TableExploreTree/TableBrowser.test.tsx | 114 ++++++ .../TableExploreTree/TreeNodeRenderer.tsx | 64 ++-- .../components/TableExploreTree/index.tsx | 229 ++++++----- .../components/TableExploreTree/types.ts | 6 + .../TableExploreTree/useTreeData.ts | 23 +- .../src/components/DatabaseSelector/index.tsx | 6 +- .../src/components/DatabaseSelector/types.ts | 1 + .../AddDataset/LeftPanel/LeftPanel.test.tsx | 356 ++++-------------- .../datasets/AddDataset/LeftPanel/index.tsx | 222 +++-------- .../src/hooks/apiResources/tables.ts | 3 +- .../DatasetCreation/DatasetCreation.test.tsx | 184 ++++++++- .../src/pages/DatasetCreation/index.tsx | 34 +- 12 files changed, 623 insertions(+), 619 deletions(-) create mode 100644 superset-frontend/src/SqlLab/components/TableExploreTree/TableBrowser.test.tsx diff --git a/superset-frontend/src/SqlLab/components/TableExploreTree/TableBrowser.test.tsx b/superset-frontend/src/SqlLab/components/TableExploreTree/TableBrowser.test.tsx new file mode 100644 index 000000000000..2c063dab549e --- /dev/null +++ b/superset-frontend/src/SqlLab/components/TableExploreTree/TableBrowser.test.tsx @@ -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 type { ReactNode } from 'react'; +import fetchMock from 'fetch-mock'; +import { + fireEvent, + render, + screen, + userEvent, + waitFor, +} from 'spec/helpers/testing-library'; +import { TableBrowser } from '.'; + +jest.mock( + 'react-virtualized-auto-sizer', + () => + ({ children }: { children: (size: { height: number }) => ReactNode }) => + children({ height: 500 }), +); + +beforeEach(() => { + fetchMock.get('glob:*/api/v1/database/1/schemas/?*', { + result: ['public', 'sales'], + }); + fetchMock.get('glob:*/api/v1/database/1/tables/*', { + result: [{ label: 'orders', value: 'orders', type: 'table' }], + count: 1, + }); + fetchMock.get('glob:*/api/v1/database/1/table_metadata/*', { + name: 'orders', + columns: [{ name: 'order_id', type: 'INTEGER' }], + }); + fetchMock.get('glob:*/api/v1/database/1/table_metadata/extra/*', {}); +}); +afterEach(() => fetchMock.removeRoutes().clearHistory()); + +test('loads tables and reports a selection without a SQL Lab query editor', async () => { + const onPreviewTable = jest.fn(); + render(, { + useRedux: true, + }); + await userEvent.click(await screen.findByText('public')); + await userEvent.click(await screen.findByText('orders')); + expect(onPreviewTable).toHaveBeenCalledWith({ + schema: 'public', + table_name: 'orders', + }); + expect(await screen.findByText('order_id')).toBeVisible(); + expect( + screen.queryByRole('button', { name: 'Pin to the result panel' }), + ).not.toBeInTheDocument(); +}); + +test('table selection supports keyboard activation', async () => { + const onPreviewTable = jest.fn(); + render(, { + useRedux: true, + }); + await userEvent.click(await screen.findByText('public')); + const tableRow = (await screen.findByText('orders')).closest('.tree-node'); + expect(tableRow).not.toBeNull(); + fireEvent.keyDown(tableRow!, { key: 'Enter' }); + expect(onPreviewTable).toHaveBeenCalledWith({ + schema: 'public', + table_name: 'orders', + }); +}); + +test('schema-less databases use an empty schema value for table selections', async () => { + const onPreviewTable = jest.fn(); + render( + , + { useRedux: true }, + ); + await userEvent.click(await screen.findByText('Tables')); + await userEvent.click(await screen.findByText('orders')); + expect(onPreviewTable).toHaveBeenCalledWith({ + schema: '', + table_name: 'orders', + }); +}); + +test('shows an empty result when no loaded table matches the search', async () => { + render(, { useRedux: true }); + await userEvent.click(await screen.findByText('public')); + await screen.findByText('orders'); + await userEvent.type( + screen.getByPlaceholderText('Enter a part of the object name'), + 'missing_table', + ); + await waitFor(() => + expect(screen.getByText('No matching results found')).toBeVisible(), + ); +}); diff --git a/superset-frontend/src/SqlLab/components/TableExploreTree/TreeNodeRenderer.tsx b/superset-frontend/src/SqlLab/components/TableExploreTree/TreeNodeRenderer.tsx index 195f1636a355..3d25675e7ca4 100644 --- a/superset-frontend/src/SqlLab/components/TableExploreTree/TreeNodeRenderer.tsx +++ b/superset-frontend/src/SqlLab/components/TableExploreTree/TreeNodeRenderer.tsx @@ -24,7 +24,7 @@ import { Icons, Typography } from '@superset-ui/core/components'; import ColumnElement from 'src/SqlLab/components/ColumnElement'; import { ActionButton } from '@superset-ui/core/components/ActionButton'; import copyTextToClipboard from 'src/utils/copy'; -import type { TreeNodeData } from './types'; +import { type TreeNodeData, type TableReference } from './types'; const StyledColumnNode = styled.div` & > .ant-flex { @@ -97,6 +97,8 @@ export interface TreeNodeRendererProps extends NodeRendererProps { refreshTableSchema: (id: string) => void; sortedTables: Record; toggleSortColumns: (tableId: string) => void; + showTablePins?: boolean; + onPreviewTable?: (table: TableReference) => void; } const TreeNodeRenderer: React.FC = ({ @@ -116,12 +118,16 @@ const TreeNodeRenderer: React.FC = ({ refreshTableSchema, sortedTables, toggleSortColumns, + showTablePins = true, + onPreviewTable, }) => { const theme = useTheme(); const { data } = node; const parts = data.id.split(':'); - const [identifier, _dbId, schema, tableName] = parts; - + const [identifier, _dbId, parsedSchema, parsedTable] = parts; + const schema = data.schema ?? parsedSchema; + const tableName = data.type === 'table' ? data.name : parsedTable; + const table = { schema, table_name: tableName }; const isManuallyOpen = node.isOpen && !node.data.disableCheckbox; const isLoading = loadingNodes[data.id] ?? false; @@ -219,6 +225,7 @@ const TreeNodeRenderer: React.FC = ({ data-selected={node.isSelected} onClick={e => { e.stopPropagation(); + if (data.type === 'table') onPreviewTable?.(table); if (node.isLeaf) { node.select(); } else { @@ -226,6 +233,7 @@ const TreeNodeRenderer: React.FC = ({ } }} onKeyDown={handleKeyboardActivation(() => { + if (data.type === 'table') onPreviewTable?.(table); if (node.isLeaf) { node.select(); } else { @@ -384,30 +392,32 @@ const TreeNodeRenderer: React.FC = ({ icon={} onClick={() => refreshTableSchema(data.id)} /> - - ) : ( - - ) - } - onClick={() => - isPinned - ? handleUnpinTable(tableName, schema) - : handlePinTable(tableName, schema, catalog ?? null) - } - /> + {showTablePins && ( + + ) : ( + + ) + } + onClick={() => + isPinned + ? handleUnpinTable(tableName, schema) + : handlePinTable(tableName, schema, catalog ?? null) + } + /> + )} ; + pinnedTableKeys?: Set; + onPinTable?: (table: string, schema: string, catalog: string | null) => void; + onUnpinTable?: (table: string, schema: string) => void; + toolbarViewId?: string; + onPreviewTable?: (table: TableReference) => void; +} + +const EMPTY_PINNED_TABLES = {}; +const EMPTY_PINNED_KEYS = new Set(); +const ignorePin = () => {}; const StyledTreeContainer = styled.div` flex: 1 1 auto; @@ -163,32 +177,19 @@ const savePinnedSchemasToStorage = ( }); }; -const TableExploreTree: React.FC = ({ queryEditorId }) => { - const dispatch = useAppDispatch(); +export const TableBrowser = ({ + dbId, + catalog, + supportsSchemas, + pinnedTables = EMPTY_PINNED_TABLES, + pinnedTableKeys = EMPTY_PINNED_KEYS, + onPinTable: handlePinTable = ignorePin, + onUnpinTable: handleUnpinTable = ignorePin, + toolbarViewId, + onPreviewTable, +}: TableBrowserProps) => { const theme = useTheme(); const treeRef = useRef>(null); - const tables = useSelector( - ({ sqlLab }: SqlLabRootState) => sqlLab.tables, - shallowEqual, - ); - const queryEditor = useQueryEditor(queryEditorId, [ - 'dbId', - 'catalog', - 'tabViewId', - ]); - const { dbId, catalog } = queryEditor; - const editorId = queryEditor.tabViewId ?? queryEditor.id; - const pinnedTables = useMemo( - () => - Object.fromEntries( - tables.map(({ queryEditorId, dbId, schema, name, persistData }) => [ - editorId === queryEditorId ? `${dbId}:${schema}:${name}` : '', - persistData, - ]), - ), - [tables, editorId], - ); - // Tree data hook - manages schema/table/column data fetching and tree structure const { treeData, @@ -204,39 +205,9 @@ const TableExploreTree: React.FC = ({ queryEditorId }) => { dbId, catalog, pinnedTables, + supportsSchemas, }); - const pinnedTableKeys = useMemo( - () => - new Set( - tables - .filter(({ queryEditorId: qeId }) => editorId === qeId) - .map(({ dbId, schema, name }) => `${dbId}:${schema}:${name}`), - ), - [tables, editorId], - ); - - const handlePinTable = useCallback( - (tableName: string, schemaName: string, catalogName: string | null) => - dispatch(addTable(queryEditor, tableName, catalogName, schemaName)), - [dispatch, queryEditor], - ); - - const handleUnpinTable = useCallback( - (tableName: string, schemaName: string) => { - const table = tables.find( - t => - t.queryEditorId === editorId && - t.dbId === dbId && - t.schema === schemaName && - t.name === tableName, - ); - if (table) { - dispatch(removeTables([table])); - } - }, - [dispatch, tables, editorId, dbId], - ); const [pinnedSchemas, setPinnedSchemas] = useState>(() => getPinnedSchemasFromStorage(dbId, catalog), ); @@ -409,6 +380,8 @@ const TableExploreTree: React.FC = ({ queryEditorId }) => { refreshTableSchema={refreshTableSchema} sortedTables={sortedTables} toggleSortColumns={toggleSortColumns} + showTablePins={Boolean(toolbarViewId)} + onPreviewTable={onPreviewTable} /> ), [ @@ -427,9 +400,33 @@ const TableExploreTree: React.FC = ({ queryEditorId }) => { loadingNodes, manuallyOpenedNodes, deferredSearchTerm, + toolbarViewId, + onPreviewTable, ], ); + const toolbarActions = ( + <> + + {showSchema && Schema dropdown} + + ), +})); +jest.mock('src/SqlLab/components/TableExploreTree', () => ({ + TableBrowser: ({ dbId, catalog, onPreviewTable }: TableBrowserProps) => ( + <> + {`Browser ${dbId}:${catalog ?? ''}`} + + + ), +})); + +const props = { + setDataset: jest.fn(), + onPreviewTable: jest.fn(), + dataset: { db: { id: 1, database_name: 'examples' }, catalog: 'main' }, +}; +afterEach(() => jest.clearAllMocks()); + +test('supplies the selected connection to the browser and hides the schema dropdown', () => { + render(, { useRedux: true }); + expect(screen.getByText('Browser 1:main')).toBeVisible(); + expect(screen.queryByText('Schema dropdown')).not.toBeInTheDocument(); }); -afterEach(() => { - fetchMock.clearHistory().removeRoutes(); -}); - -const mockFun = jest.fn(); - -test('should render', async () => { - render(, { - useRedux: true, - }); - expect( - await screen.findByText(/Select database or type to search databases/i), - ).toBeInTheDocument(); -}); - -test('should render schema selector, database selector container, and selects', async () => { - render(, { useRedux: true }); - - expect( - await screen.findByText(/Select database or type to search databases/i), - ).toBeVisible(); - - const databaseSelect = screen.getByRole('combobox', { - name: 'Select database or type to search databases', - }); - const schemaSelect = screen.getByRole('combobox', { - name: 'Select schema', - }); - expect(databaseSelect).toBeInTheDocument(); - expect(schemaSelect).toBeInTheDocument(); -}); - -test('does not render blank state if there is nothing selected', async () => { - render(, { useRedux: true }); - - expect( - await screen.findByText(/Select database or type to search databases/i), - ).toBeInTheDocument(); - const emptyState = screen.queryByRole('img', { name: /empty/i }); - expect(emptyState).not.toBeInTheDocument(); -}); - -test('renders list of options when user clicks on schema', async () => { - render(, { - useRedux: true, - }); - - // Click 'test-postgres' database to access schemas - const databaseSelect = screen.getByRole('combobox', { - name: 'Select database or type to search databases', - }); - await userEvent.click(databaseSelect); - expect(await screen.findByText('test-postgres')).toBeInTheDocument(); - await userEvent.click(screen.getByText('test-postgres')); - - // Schema select will be automatically populated if there is only one schema - const schemaSelect = screen.getByRole('combobox', { - name: /select schema/i, - }); - await waitFor(() => { - expect(schemaSelect).toBeEnabled(); +test('notifies the dataset page of the selected table and schema', async () => { + render(, { useRedux: true }); + await userEvent.click(screen.getByText('Preview orders')); + expect(props.onPreviewTable).toHaveBeenCalledWith({ + schema: 'public', + table_name: 'orders', }); }); -test('searches for a table name', async () => { - render(, { - useRedux: true, +test('changing the connection dispatches the existing source-reset action', async () => { + render(, { useRedux: true }); + await userEvent.click(screen.getByText('Change connection')); + expect(props.setDataset).toHaveBeenCalledWith({ + type: DatasetActionType.SelectDatabase, + payload: { db: { id: 2, database_name: 'other' } }, }); - - // Click 'test-postgres' database to access schemas - const databaseSelect = screen.getByRole('combobox', { - name: /select database or type to search databases/i, - }); - await userEvent.click(databaseSelect); - await userEvent.click(await screen.findByText('test-postgres')); - - const schemaSelect = screen.getByRole('combobox', { - name: /select schema/i, - }); - const tableSelect = screen.getByRole('combobox', { - name: /select table or type to search tables/i, - }); - - await waitFor(() => expect(schemaSelect).toBeEnabled()); - - // Click 'public' schema to access tables - await userEvent.click(schemaSelect); - await userEvent.click(screen.getByText('public')); - await waitFor(() => - expect(fetchMock.callHistory.calls(tablesEndpoint).length).toBe(1), - ); - await userEvent.click(tableSelect); - - await waitFor(() => { - expect( - screen.queryByRole('option', { name: /Sheet1/i }), - ).toBeInTheDocument(); - expect( - screen.queryByRole('option', { name: /Sheet2/i }), - ).toBeInTheDocument(); - }); - - await userEvent.type(tableSelect, 'Sheet3'); - - await waitFor(() => { - expect(screen.queryByText(/Sheet1/i)).not.toBeInTheDocument(); - expect(screen.queryByText(/Sheet2/i)).not.toBeInTheDocument(); - expect( - screen.queryByRole('option', { name: /Sheet3/i }), - ).toBeInTheDocument(); - }); -}); - -test('renders a warning icon when a table name has a preexisting dataset', async () => { - render( - , - { - useRedux: true, - }, - ); - - // Click 'test-postgres' database to access schemas - const databaseSelect = screen.getByRole('combobox', { - name: /select database or type to search databases/i, - }); - await userEvent.click(databaseSelect); - await userEvent.click(await screen.findByText('test-postgres')); - - const schemaSelect = screen.getByRole('combobox', { - name: /select schema/i, - }); - const tableSelect = screen.getByRole('combobox', { - name: /select table or type to search tables/i, - }); - - await waitFor(() => expect(schemaSelect).toBeEnabled()); - - // Warning icon should not show yet - expect( - screen.queryByRole('img', { name: 'warning' }), - ).not.toBeInTheDocument(); - - // Click 'public' schema to access tables - await userEvent.click(schemaSelect); - await userEvent.click(screen.getByText('public')); - await userEvent.click(tableSelect); - - await waitFor(() => { - expect( - screen.queryByRole('option', { name: /Sheet2/i }), - ).toBeInTheDocument(); - }); - - await userEvent.type(tableSelect, 'Sheet2'); - - // Sheet2 should now show the warning icon - expect(screen.getByRole('img', { name: 'warning' })).toBeInTheDocument(); }); diff --git a/superset-frontend/src/features/datasets/AddDataset/LeftPanel/index.tsx b/superset-frontend/src/features/datasets/AddDataset/LeftPanel/index.tsx index ef90f1815ebd..fe2a8d94262b 100644 --- a/superset-frontend/src/features/datasets/AddDataset/LeftPanel/index.tsx +++ b/superset-frontend/src/features/datasets/AddDataset/LeftPanel/index.tsx @@ -16,205 +16,87 @@ * specific language governing permissions and limitations * under the License. */ -import { useEffect, SetStateAction, Dispatch, useCallback } from 'react'; +import { useEffect, useCallback, type Dispatch } from 'react'; import { t } from '@apache-superset/core/translation'; -import { styled } from '@apache-superset/core/theme'; -import TableSelector, { TableOption } from 'src/components/TableSelector'; -import { EmptyState } from '@superset-ui/core/components'; -import { type DatabaseObject } from 'src/components'; +import { useTheme } from '@apache-superset/core/theme'; +import { Flex, EmptyState } from '@superset-ui/core/components'; +import { DatabaseSelector } from 'src/components/DatabaseSelector'; +import type { DatabaseObject } from 'src/components'; +import { TableBrowser } from 'src/SqlLab/components/TableExploreTree'; +import type { TableReference } from 'src/SqlLab/components/TableExploreTree/types'; import { useToasts } from 'src/components/MessageToasts/withToasts'; import { LocalStorageKeys, getItem } from 'src/utils/localStorageHelpers'; import { DatasetActionType, DatasetObject, -} from 'src/features/datasets/AddDataset/types'; -import { Table } from 'src/hooks/apiResources'; -import { Typography } from '@superset-ui/core/components/Typography'; -import { ensureAppRoot } from 'src/utils/navigationUtils'; + DSReducerActionType, +} from '../types'; interface LeftPanelProps { - setDataset: Dispatch>; + setDataset: Dispatch; dataset?: Partial | null; - datasetNames?: (string | null | undefined)[] | undefined; + onPreviewTable: (table: TableReference) => void; } -const LeftPanelStyle = styled.div` - ${({ theme }) => ` - padding: ${theme.sizeUnit * 4}px; - height: 100%; - background-color: ${theme.colorBgContainer}; - position: relative; - .emptystate { - height: auto; - margin-top: ${theme.sizeUnit * 17.5}px; - } - .section-title { - margin-top: ${theme.sizeUnit * 5.5}px; - margin-bottom: ${theme.sizeUnit * 11}px; - font-weight: ${theme.fontWeightStrong}; - } - .table-title { - margin-top: ${theme.sizeUnit * 11}px; - margin-bottom: ${theme.sizeUnit * 6}px; - font-weight: ${theme.fontWeightStrong}; - } - .options-list { - overflow: auto; - position: absolute; - bottom: 0; - top: ${theme.sizeUnit * 92.25}px; - left: ${theme.sizeUnit * 3.25}px; - right: 0; - - .no-scrollbar { - margin-right: ${theme.sizeUnit * 4}px; - } - - .options { - cursor: pointer; - padding: ${theme.sizeUnit * 1.75}px; - border-radius: ${theme.borderRadius}px; - :hover { - background-color: ${theme.colorFillTertiary} - } - } - - .options-highlighted { - cursor: pointer; - padding: ${theme.sizeUnit * 1.75}px; - border-radius: ${theme.borderRadius}px; - background-color: ${theme.colorPrimaryText}; - color: ${theme.colorTextLightSolid}; - } - - .options, .options-highlighted { - display: flex; - align-items: center; - justify-content: space-between; - } - } - form > span[aria-label="refresh"] { - position: absolute; - top: ${theme.sizeUnit * 69}px; - left: ${theme.sizeUnit * 42.75}px; - font-size: ${theme.sizeUnit * 4.25}px; - } - .table-form { - margin-bottom: ${theme.sizeUnit * 8}px; - } - .loading-container { - position: absolute; - top: ${theme.sizeUnit * 89.75}px; - left: 0; - right: 0; - text-align: center; - img { - width: ${theme.sizeUnit * 20}px; - margin-bottom: ${theme.sizeUnit * 2.5}px; - } - p { - color: ${theme.colorTextSecondary}; - } - } -`} -`; - export default function LeftPanel({ setDataset, dataset, - datasetNames, + onPreviewTable, }: LeftPanelProps) { + const theme = useTheme(); const { addDangerToast } = useToasts(); - const setDatabase = useCallback( - (db: Partial) => { + (db: DatabaseObject) => { setDataset({ type: DatasetActionType.SelectDatabase, payload: { db } }); }, [setDataset], ); - const setCatalog = (catalog: string | null) => { - if (catalog) { - setDataset({ - type: DatasetActionType.SelectCatalog, - payload: { name: 'catalog', value: catalog }, - }); - } - }; - const setSchema = (schema: string) => { - if (schema) { - setDataset({ - type: DatasetActionType.SelectSchema, - payload: { name: 'schema', value: schema }, - }); - } - }; - const setTable = (tableName: string) => { - setDataset({ - type: DatasetActionType.SelectTable, - payload: { name: 'table_name', value: tableName }, - }); - }; + useEffect(() => { - const currentUserSelectedDb = getItem( + const previous = getItem( LocalStorageKeys.Database, null, - ) as DatabaseObject; - if (currentUserSelectedDb) { - setDatabase(currentUserSelectedDb); - } + ) as DatabaseObject | null; + if (previous) setDatabase(previous); }, [setDatabase]); - const customTableOptionLabelRenderer = useCallback( - (table: Table) => ( - - ), - [datasetNames], - ); - const getDatabaseEmptyState = (emptyResultsWithSearch: boolean) => ( - - {t('Manage your databases')}{' '} - - {t('here')} - - - } - size="small" - /> - ); - return ( - - + + setDataset({ + type: DatasetActionType.SelectCatalog, + payload: { name: 'catalog', value: catalog }, + }) + } /> - + {dataset?.db ? ( + + ) : ( + + )} + ); } diff --git a/superset-frontend/src/hooks/apiResources/tables.ts b/superset-frontend/src/hooks/apiResources/tables.ts index c3c07db9218d..d5c3d43a5bfa 100644 --- a/superset-frontend/src/hooks/apiResources/tables.ts +++ b/superset-frontend/src/hooks/apiResources/tables.ts @@ -117,8 +117,9 @@ const tableApi = api.injectEndpoints({ hasMore: json.count > json.result.length, }), }), - serializeQueryArgs: ({ queryArgs: { dbId, schema } }) => ({ + serializeQueryArgs: ({ queryArgs: { dbId, catalog, schema } }) => ({ dbId, + catalog, schema, }), }), diff --git a/superset-frontend/src/pages/DatasetCreation/DatasetCreation.test.tsx b/superset-frontend/src/pages/DatasetCreation/DatasetCreation.test.tsx index 4d845a830cde..127b9e83902e 100644 --- a/superset-frontend/src/pages/DatasetCreation/DatasetCreation.test.tsx +++ b/superset-frontend/src/pages/DatasetCreation/DatasetCreation.test.tsx @@ -16,32 +16,182 @@ * specific language governing permissions and limitations * under the License. */ -import { render, screen } from 'spec/helpers/testing-library'; -import AddDataset from 'src/pages/DatasetCreation'; +import type { ReactNode } from 'react'; +import fetchMock from 'fetch-mock'; +import rison from 'rison'; +import { + render, + screen, + userEvent, + waitFor, +} from 'spec/helpers/testing-library'; +import { LocalStorageKeys, setItem } from 'src/utils/localStorageHelpers'; +import AddDataset, { datasetReducer } from '.'; +import { DatasetActionType } from 'src/features/datasets/AddDataset/types'; const mockHistoryPush = jest.fn(); jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), - useHistory: () => ({ - push: mockHistoryPush, - }), + useHistory: () => ({ push: mockHistoryPush }), useParams: () => ({ datasetId: undefined }), })); +jest.mock( + 'react-virtualized-auto-sizer', + () => + ({ children }: { children: (size: { height: number }) => ReactNode }) => + children({ height: 500 }), +); -// eslint-disable-next-line no-restricted-globals -- TODO: Migrate from describe blocks -describe('AddDataset', () => { - test('renders a blank state AddDataset', async () => { - render(, { useRedux: true, useRouter: true }); +const database = { + id: 1, + database_name: 'examples', + backend: 'postgresql', + allow_multi_catalog: true, +}; +beforeEach(() => { + localStorage.removeItem(LocalStorageKeys.Database); + mockHistoryPush.mockClear(); + fetchMock.get('glob:*/api/v1/database/?q*', { + count: 2, + result: [ + database, + { id: 2, database_name: 'analytics', backend: 'postgresql' }, + ], + }); + fetchMock.get('glob:*/api/v1/database/1/catalogs/*', { + result: ['main', 'archive'], + count: 2, + }); + fetchMock.get('glob:*/api/v1/database/*/schemas/?*', { result: ['public'] }); + fetchMock.get('glob:*/api/v1/database/1/tables/*', call => { + const query = new URL(call.url, 'http://localhost').searchParams.get('q'); + const { catalog_name: catalog } = rison.decode(query ?? '()') as { + catalog_name?: string; + }; + const tableName = catalog === 'archive' ? 'archived_orders' : 'orders'; + return { + result: [{ label: tableName, value: tableName, type: 'table' }], + count: 1, + }; + }); + fetchMock.get('glob:*/api/v1/database/1/table_metadata/*', { + name: 'orders', + columns: [{ name: 'order_id', type: 'INTEGER' }], + }); + fetchMock.get('glob:*/api/v1/database/1/table_metadata/extra/*', {}); + fetchMock.get('glob:*/api/v1/dataset/?q*', { result: [], count: 0 }); +}); +afterEach(() => { + fetchMock.removeRoutes().clearHistory(); + localStorage.removeItem(LocalStorageKeys.Database); +}); - const blankeStateImgs = screen.getAllByRole('img', { name: /empty/i }); +async function selectOrders() { + await userEvent.click(await screen.findByText('public', { exact: true })); + await userEvent.click(await screen.findByText('orders', { exact: true })); + await waitFor(() => + expect(screen.getAllByText('order_id').length).toBeGreaterThan(0), + ); + await waitFor(() => + expect( + screen.getByRole('button', { + name: 'Create and explore dataset', + }), + ).toBeEnabled(), + ); +} - // Header - expect(await screen.findByText(/new dataset/i)).toBeVisible(); - // Left panel - expect(blankeStateImgs[0]).toBeVisible(); - // Footer - expect(screen.getByText(/Cancel/i)).toBeVisible(); +test('selects a table through the browser and clears its preview when the connection changes', async () => { + setItem(LocalStorageKeys.Database, { + ...database, + allow_multi_catalog: false, + }); + render(, { useRedux: true, useRouter: true }); + await selectOrders(); + const connection = screen.getByRole('combobox', { + name: /Select (database|data connection) or type/i, + }); + await userEvent.click(connection); + await userEvent.click(await screen.findByText('analytics', { exact: true })); + await waitFor(() => + expect(screen.queryByText('order_id')).not.toBeInTheDocument(), + ); + expect( + screen.getByRole('button', { + name: 'Create and explore dataset', + }), + ).toBeDisabled(); + expect(screen.getByText('New dataset')).toBeVisible(); +}); + +test('changing the catalog clears the selected table and column preview', async () => { + setItem(LocalStorageKeys.Database, database); + render(, { useRedux: true, useRouter: true }); + const catalog = screen.getByRole('combobox', { + name: 'Select catalog or type to search catalogs', + }); + await userEvent.click(catalog); + await userEvent.click(await screen.findByText('main', { exact: true })); + await selectOrders(); + await userEvent.click(catalog); + await userEvent.click(await screen.findByText('archive', { exact: true })); + await userEvent.click(await screen.findByText('public', { exact: true })); + expect( + await screen.findByText('archived_orders', { exact: true }), + ).toBeVisible(); + expect(screen.queryByText('orders', { exact: true })).not.toBeInTheDocument(); + await waitFor(() => + expect(screen.queryByText('order_id')).not.toBeInTheDocument(), + ); + expect( + screen.getByRole('button', { + name: 'Create and explore dataset', + }), + ).toBeDisabled(); +}); - expect(blankeStateImgs.length).toBe(1); +test('single-table creation submits the selected schema and keeps the existing explore redirect', async () => { + setItem(LocalStorageKeys.Database, { + ...database, + allow_multi_catalog: false, }); + fetchMock.post('glob:*/api/v1/dataset/', { id: 10 }); + render(, { useRedux: true, useRouter: true }); + await selectOrders(); + await userEvent.click( + screen.getByRole('button', { + name: 'Create and explore dataset', + }), + ); + await waitFor(() => + expect(mockHistoryPush).toHaveBeenCalledWith('/chart/add/?dataset=orders'), + ); + const call = fetchMock.callHistory.lastCall('glob:*/api/v1/dataset/'); + expect(JSON.parse(String(call?.options.body))).toEqual({ + database: 1, + catalog: null, + schema: 'public', + table_name: 'orders', + }); +}); + +test('source changes clear the selected table in the dataset reducer', () => { + const selected = { + db: database, + catalog: 'main', + schema: 'public', + table_name: 'orders', + }; + expect( + datasetReducer(selected, { + type: DatasetActionType.SelectDatabase, + payload: { db: { id: 2, database_name: 'analytics' } }, + }), + ).toMatchObject({ table_name: null, schema: null, catalog: null }); + expect( + datasetReducer(selected, { + type: DatasetActionType.SelectCatalog, + payload: { name: 'catalog', value: 'archive' }, + }), + ).toMatchObject({ table_name: null, schema: null, catalog: 'archive' }); }); diff --git a/superset-frontend/src/pages/DatasetCreation/index.tsx b/superset-frontend/src/pages/DatasetCreation/index.tsx index fb77e7eeb4b5..6235d68f256a 100644 --- a/superset-frontend/src/pages/DatasetCreation/index.tsx +++ b/superset-frontend/src/pages/DatasetCreation/index.tsx @@ -16,8 +16,9 @@ * specific language governing permissions and limitations * under the License. */ -import { useReducer, Reducer, useEffect, useState } from 'react'; +import { useCallback, useReducer, useState } from 'react'; import { useParams } from 'react-router-dom'; +import type { TableReference } from 'src/SqlLab/components/TableExploreTree/types'; import useDatasetsList from 'src/features/datasets/hooks/useDatasetLists'; import Header from 'src/features/datasets/AddDataset/Header'; import EditPage from 'src/features/datasets/AddDataset/EditDataset'; @@ -31,14 +32,10 @@ import { } from 'src/features/datasets/AddDataset/types'; import DatasetLayout from 'src/features/datasets/DatasetLayout'; -type Schema = { - schema: string; -}; - export function datasetReducer( - state: DatasetObject | null, + state: Partial | null, action: DSReducerActionType, -): Partial | Schema | null { +): Partial | null { const trimmedState = { ...state, }; @@ -84,11 +81,8 @@ const prevUrl = '/tablemodelview/list/?pageIndex=0&sortColumn=changed_on_delta_humanized&sortOrder=desc'; export default function AddDataset() { - const [dataset, setDataset] = useReducer< - Reducer | null, DSReducerActionType> - >(datasetReducer, null); + const [dataset, setDataset] = useReducer(datasetReducer, null); const [hasColumns, setHasColumns] = useState(false); - const [editPageIsVisible, setEditPageIsVisible] = useState(false); const { datasets, datasetNames } = useDatasetsList( dataset?.db, @@ -96,11 +90,17 @@ export default function AddDataset() { ); const { datasetId: id } = useParams<{ datasetId: string }>(); - useEffect(() => { - if (!Number.isNaN(parseInt(id, 10))) { - setEditPageIsVisible(true); - } - }, [id]); + const editPageIsVisible = !Number.isNaN(parseInt(id, 10)); + const handleTableSelection = useCallback((table: TableReference) => { + setDataset({ + type: DatasetActionType.SelectSchema, + payload: { name: 'schema', value: table.schema }, + }); + setDataset({ + type: DatasetActionType.SelectTable, + payload: { name: 'table_name', value: table.table_name }, + }); + }, []); const HeaderComponent = () => (
@@ -110,7 +110,7 @@ export default function AddDataset() { ); From 2ec826927b11577233146df472947b70dec6f33b Mon Sep 17 00:00:00 2001 From: Haseeb702 <80732008+Haseeb702@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:20:05 -0500 Subject: [PATCH 02/16] fix(datasets): updated tests for table browser --- .../playwright/pages/CreateDatasetPage.ts | 34 +++++------ .../DatasetLayout/DatasetLayout.test.tsx | 14 ++++- superset/translations/messages.pot | 61 ++++++------------- 3 files changed, 45 insertions(+), 64 deletions(-) diff --git a/superset-frontend/playwright/pages/CreateDatasetPage.ts b/superset-frontend/playwright/pages/CreateDatasetPage.ts index 62bd943849ea..018b2ab9b948 100644 --- a/superset-frontend/playwright/pages/CreateDatasetPage.ts +++ b/superset-frontend/playwright/pages/CreateDatasetPage.ts @@ -33,8 +33,6 @@ export class CreateDatasetPage { */ private static readonly SELECTORS = { DATABASE: '[data-test="select-database"]', - SCHEMA: '[data-test="Select schema"]', - TABLE: '[data-test="Select table or type to search tables"]', } as const; constructor(page: Page) { @@ -48,20 +46,6 @@ export class CreateDatasetPage { return new Select(this.page, CreateDatasetPage.SELECTORS.DATABASE); } - /** - * Gets the schema selector using data-test attribute - */ - getSchemaSelect(): Select { - return new Select(this.page, CreateDatasetPage.SELECTORS.SCHEMA); - } - - /** - * Gets the table selector using data-test attribute - */ - getTableSelect(): Select { - return new Select(this.page, CreateDatasetPage.SELECTORS.TABLE); - } - /** * Gets the create and explore button */ @@ -88,19 +72,29 @@ export class CreateDatasetPage { } /** - * Select a schema from the dropdown + * Expand a schema in the table browser * @param schemaName - The name of the schema to select */ async selectSchema(schemaName: string): Promise { - await this.getSchemaSelect().selectOption(schemaName); + await this.page.getByPlaceholder('Enter a part of the object name').clear(); + await this.page + .getByRole('treeitem') + .getByText(schemaName, { exact: true }) + .click(); } /** - * Select a table from the dropdown + * Filter the table browser and select a table * @param tableName - The name of the table to select */ async selectTable(tableName: string): Promise { - await this.getTableSelect().selectOption(tableName); + await this.page + .getByPlaceholder('Enter a part of the object name') + .fill(tableName); + await this.page + .getByRole('treeitem') + .getByText(tableName, { exact: true }) + .click(); } /** diff --git a/superset-frontend/src/features/datasets/DatasetLayout/DatasetLayout.test.tsx b/superset-frontend/src/features/datasets/DatasetLayout/DatasetLayout.test.tsx index 8da08b88575b..c9e4f8162478 100644 --- a/superset-frontend/src/features/datasets/DatasetLayout/DatasetLayout.test.tsx +++ b/superset-frontend/src/features/datasets/DatasetLayout/DatasetLayout.test.tsx @@ -55,7 +55,11 @@ describe('DatasetLayout', () => { test('renders a LeftPanel when passed in', async () => { render( - null} />} />, + null} onPreviewTable={jest.fn()} /> + } + />, { useRedux: true, useRouter: true }, ); @@ -95,7 +99,9 @@ describe('DatasetLayout', () => { test('layout has proper flex constraints to prevent viewport overflow', () => { const { container } = render( null} />} + leftPanel={ + null} onPreviewTable={jest.fn()} /> + } datasetPanel={} footer={