diff --git a/superset-frontend/playwright/pages/CreateDatasetPage.ts b/superset-frontend/playwright/pages/CreateDatasetPage.ts index 62bd943849ea..22e12ed2f9d4 100644 --- a/superset-frontend/playwright/pages/CreateDatasetPage.ts +++ b/superset-frontend/playwright/pages/CreateDatasetPage.ts @@ -17,7 +17,7 @@ * under the License. */ -import { Page } from '@playwright/test'; +import { expect, Page } from '@playwright/test'; import { Button, Select } from '../components/core'; import { gotoWithRetry } from '../helpers/navigation'; @@ -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 */ @@ -80,27 +64,48 @@ export class CreateDatasetPage { } /** - * Select a database from the dropdown + * Select a database through the connection/schema popover * @param databaseName - The name of the database to select */ async selectDatabase(databaseName: string): Promise { + await this.page.getByTestId('database-selector-trigger').click(); await this.getDatabaseSelect().selectOption(databaseName); + const popover = this.page.getByRole('group', { + name: 'Select Database and Schema', + }); + await popover.getByRole('button', { name: 'Select', exact: true }).click(); + await expect(popover).toBeHidden(); } /** - * 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.getByTestId('database-selector-trigger').click(); + const dialog = this.page.getByRole('group', { + name: 'Select Database and Schema', + }); + await new Select( + this.page, + dialog.getByRole('combobox', { name: /^Select schema/ }), + ).selectOption(schemaName); + await dialog.getByRole('button', { name: 'Select', exact: true }).click(); + await expect(dialog).toBeHidden(); } /** - * 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(); } /** @@ -134,6 +139,8 @@ export class CreateDatasetPage { * Wait for the page to load */ async waitForPageLoad(): Promise { - await this.getDatabaseSelect().element.waitFor({ state: 'visible' }); + await this.page + .getByTestId('database-selector-trigger') + .waitFor({ state: 'visible' }); } } diff --git a/superset-frontend/src/SqlLab/components/SqlEditorLeftBar/index.tsx b/superset-frontend/src/SqlLab/components/SqlEditorLeftBar/index.tsx index 945f5b97ac37..12c08deb1703 100644 --- a/superset-frontend/src/SqlLab/components/SqlEditorLeftBar/index.tsx +++ b/superset-frontend/src/SqlLab/components/SqlEditorLeftBar/index.tsx @@ -16,22 +16,14 @@ * specific language governing permissions and limitations * under the License. */ -import { useCallback, useState } from 'react'; +import { useCallback } from 'react'; import { useAppDispatch } from 'src/SqlLab/hooks/useAppDispatch'; import { resetState } from 'src/SqlLab/actions/sqlLab'; -import { - Button, - EmptyState, - Flex, - Icons, - Popover, - Typography, -} from '@superset-ui/core/components'; +import { Button, Icons } from '@superset-ui/core/components'; import { t } from '@apache-superset/core/translation'; import { styled, css } from '@apache-superset/core/theme'; -import type { SchemaOption, CatalogOption } from 'src/hooks/apiResources'; -import { DatabaseSelector, type DatabaseObject } from 'src/components'; +import { DatabaseSelectorPopover } from 'src/components/DatabaseSelector'; import { EMPTY_STATE_QE_ID } from 'src/SqlLab/hooks/useQueryEditor'; import useDatabaseSelector from '../SqlEditorTopBar/useDatabaseSelector'; @@ -70,145 +62,20 @@ const SqlEditorLeftBar = ({ }: SqlEditorLeftBarProps) => { const activeQEId = queryEditorId || EMPTY_STATE_QE_ID; const dbSelectorProps = useDatabaseSelector(activeQEId); - const { db, catalog, schema, onDbChange, onCatalogChange, onSchemaChange } = - dbSelectorProps; const dispatch = useAppDispatch(); const shouldShowReset = window.location.search === '?reset=1'; - // Modal state for Database/Catalog/Schema selector - const [selectorModalOpen, setSelectorModalOpen] = useState(false); - const [modalDb, setModalDb] = useState(undefined); - const [modalCatalog, setModalCatalog] = useState< - CatalogOption | null | undefined - >(undefined); - const [modalSchema, setModalSchema] = useState( - undefined, - ); - - const openSelectorModal = useCallback(() => { - setModalDb(db ?? undefined); - setModalCatalog( - catalog ? { label: catalog, value: catalog, title: catalog } : undefined, - ); - setModalSchema( - schema ? { label: schema, value: schema, title: schema } : undefined, - ); - setSelectorModalOpen(true); - }, [db, catalog, schema]); - - const closeSelectorModal = useCallback(() => { - setSelectorModalOpen(false); - }, []); - - const handleModalOk = useCallback(() => { - if (modalDb && modalDb.id !== db?.id) { - onDbChange?.(modalDb); - } - if (modalCatalog?.value !== catalog) { - onCatalogChange?.(modalCatalog?.value); - } - if (modalSchema?.value !== schema) { - onSchemaChange?.(modalSchema?.value ?? ''); - } - setSelectorModalOpen(false); - }, [ - modalDb, - modalCatalog, - modalSchema, - db, - catalog, - schema, - onDbChange, - onCatalogChange, - onSchemaChange, - ]); - const handleResetState = useCallback(() => { dispatch(resetState()); }, [dispatch]); - const popoverContent = ( - - - {t('Select Database and Schema')} - - } - getDbList={dbSelectorProps.getDbList} - handleError={dbSelectorProps.handleError} - onDbChange={setModalDb} - onCatalogChange={cat => - setModalCatalog( - cat ? { label: cat, value: cat, title: cat } : undefined, - ) - } - catalog={modalCatalog?.value} - onSchemaChange={sch => - setModalSchema( - sch ? { label: sch, value: sch, title: sch } : undefined, - ) - } - schema={modalSchema?.value} - sqlLabMode={false} - filterBySqlLab - /> - - - - - - ); - const dbSelectorTrigger = ( - !open && closeSelectorModal()} - placement="bottomLeft" - trigger="click" - > - {/* Wrap in a span so the Popover can attach a ref without relying - on findDOMNode (deprecated in React 18+). */} - - } - sqlLabMode - compactMode={collapsed} - onOpenModal={openSelectorModal} - /> - - + ); if (collapsed) { diff --git a/superset-frontend/src/SqlLab/components/SqlEditorTopBar/useDatabaseSelector.test.ts b/superset-frontend/src/SqlLab/components/SqlEditorTopBar/useDatabaseSelector.test.ts index a3ad33924208..cd4ea2e184c0 100644 --- a/superset-frontend/src/SqlLab/components/SqlEditorTopBar/useDatabaseSelector.test.ts +++ b/superset-frontend/src/SqlLab/components/SqlEditorTopBar/useDatabaseSelector.test.ts @@ -177,6 +177,30 @@ test('dispatches queryEditorSetSchema action on onSchemaChange', () => { ); }); +test('dispatches empty string schema when onSchemaChange receives undefined', () => { + const store = mockStore(createInitialState()); + const { result } = renderHook( + () => useDatabaseSelector(defaultQueryEditor.id), + { + wrapper: createWrapper({ + useRedux: true, + store, + }), + }, + ); + + act(() => { + result.current.onSchemaChange(undefined); + }); + + expect(store.getActions()).toContainEqual( + expect.objectContaining({ + type: 'QUERY_EDITOR_SET_SCHEMA', + schema: '', + }), + ); +}); + test('dispatches setDatabases action on getDbList', () => { const store = mockStore(createInitialState()); const { result } = renderHook( diff --git a/superset-frontend/src/SqlLab/components/SqlEditorTopBar/useDatabaseSelector.ts b/superset-frontend/src/SqlLab/components/SqlEditorTopBar/useDatabaseSelector.ts index dccccae13729..2035ac64c1fb 100644 --- a/superset-frontend/src/SqlLab/components/SqlEditorTopBar/useDatabaseSelector.ts +++ b/superset-frontend/src/SqlLab/components/SqlEditorTopBar/useDatabaseSelector.ts @@ -77,9 +77,9 @@ export default function useDatabaseSelector(queryEditorId: string) { ); const handleSchemaChange = useCallback( - (schema: string) => { + (schema?: string) => { if (queryEditor) { - dispatch(queryEditorSetSchema(queryEditor, schema)); + dispatch(queryEditorSetSchema(queryEditor, schema ?? '')); } }, [dispatch, queryEditor], 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..63d393282bc2 --- /dev/null +++ b/superset-frontend/src/SqlLab/components/TableExploreTree/TableBrowser.test.tsx @@ -0,0 +1,437 @@ +/** + * 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 { useState, type ReactNode } from 'react'; +import fetchMock from 'fetch-mock'; +import { Tree } from 'react-arborist'; +import { + fireEvent, + createStore, + render, + screen, + userEvent, + waitFor, +} from 'spec/helpers/testing-library'; +import { TableBrowser } from '.'; +import TreeNodeRenderer from './TreeNodeRenderer'; +import type { TableReference, TreeNodeData } from './types'; +import reducerIndex from 'spec/helpers/reducerIndex'; +import type { RootState } from 'src/views/store'; +import { initialState } from 'src/SqlLab/fixtures'; +import { ToastType } from 'src/components/MessageToasts/types'; +import { + LocalStorageKeys, + getItem, + setItem, +} from 'src/utils/localStorageHelpers'; + +jest.mock('react-virtualized-auto-sizer', () => ({ + AutoSizer: ({ + renderProp, + }: { + renderProp: (size: { height: number }) => ReactNode; + }) => renderProp({ height: 500 }), +})); + +let metadataColumns: { name: string; type: string }[]; +let metadataShouldFail: boolean; + +beforeEach(() => { + metadataColumns = [{ name: 'order_id', type: 'INTEGER' }]; + metadataShouldFail = false; + localStorage.removeItem(LocalStorageKeys.SqllabPinnedSchemas); + 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/*', () => + metadataShouldFail + ? { status: 500, body: { message: 'Metadata unavailable' } } + : { name: 'orders', columns: metadataColumns }, + ); + fetchMock.get('glob:*/api/v1/database/1/table_metadata/extra/*', {}); +}); +afterEach(() => { + fetchMock.removeRoutes().clearHistory(); + localStorage.removeItem(LocalStorageKeys.SqllabPinnedSchemas); +}); + +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.each(['Enter', ' '])('table selection supports the %p key', async key => { + 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 }); + 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(), + ); +}); + +test('opens and loads a schema selected through the connection selector', async () => { + const onPreviewTable = jest.fn(); + render( + , + { + useRedux: true, + }, + ); + await userEvent.click(await screen.findByText('orders')); + expect(onPreviewTable).toHaveBeenCalledWith({ + schema: 'public', + table_name: 'orders', + }); +}); + +test('collapse all hides loaded tables and permits expanding the schema again', async () => { + render(, { useRedux: true }); + await userEvent.click(await screen.findByText('public')); + await userEvent.click(await screen.findByText('orders')); + await screen.findByText('order_id'); + await userEvent.click(screen.getByRole('button', { name: /minus-square/i })); + expect(screen.queryByText('orders')).not.toBeInTheDocument(); + expect(screen.queryByText('order_id')).not.toBeInTheDocument(); + await userEvent.click(screen.getByText('public')); + expect(await screen.findByText('orders')).toBeVisible(); +}); + +test('refreshing the schema list displays newly available schemas', async () => { + fetchMock.removeRoutes().clearHistory(); + let schemas = ['public']; + fetchMock.get('glob:*/api/v1/database/1/schemas/?*', () => ({ + result: schemas, + })); + render(, { useRedux: true }); + await screen.findByText('public'); + schemas = ['public', 'archive']; + await userEvent.click(screen.getByRole('button', { name: /reload/i })); + expect(await screen.findByText('archive')).toBeVisible(); +}); + +test('schema pins persist, sort the browser, and can be removed', async () => { + render(, { useRedux: true }); + await screen.findByText('sales'); + await userEvent.click(screen.getByTestId('pin-schema-sales')); + await waitFor(() => + expect(screen.getAllByRole('treeitem')[0]).toHaveTextContent('sales'), + ); + expect(getItem(LocalStorageKeys.SqllabPinnedSchemas, {})).toEqual({ + '1:': ['sales'], + }); + await userEvent.click(screen.getByTestId('unpin-schema-sales')); + await waitFor(() => + expect(screen.getAllByRole('treeitem')[0]).toHaveTextContent('public'), + ); + expect(getItem(LocalStorageKeys.SqllabPinnedSchemas, {})).toEqual({ + '1:': [], + }); +}); + +test('changing catalogs restores their own schema pins without overwriting another catalog', async () => { + setItem(LocalStorageKeys.SqllabPinnedSchemas, { + '1:main': ['sales'], + '1:archive': ['public'], + }); + const { rerender } = render(, { + useRedux: true, + }); + await waitFor(() => + expect(screen.getAllByRole('treeitem')[0]).toHaveTextContent('sales'), + ); + rerender(); + await waitFor(() => + expect(screen.getAllByRole('treeitem')[0]).toHaveTextContent('public'), + ); + expect(getItem(LocalStorageKeys.SqllabPinnedSchemas, {})).toEqual({ + '1:main': ['sales'], + '1:archive': ['public'], + }); +}); + +test('refreshing a table replaces its cached column metadata', async () => { + render(, { useRedux: true }); + await userEvent.click(await screen.findByText('public')); + await userEvent.click(await screen.findByText('orders')); + await screen.findByText('order_id'); + metadataColumns = [{ name: 'order_total', type: 'NUMERIC' }]; + await userEvent.click(screen.getByTestId('refresh-schema-public-orders')); + await waitFor(() => + expect( + fetchMock.callHistory.calls('glob:*/api/v1/database/1/table_metadata/?*') + .length, + ).toBe(2), + ); + expect(await screen.findByText('order_total')).toBeVisible(); + expect(screen.queryByText('order_id')).not.toBeInTheDocument(); +}); + +test('reports metadata failures outside SQL Lab and permits retrying the table', async () => { + metadataShouldFail = true; + const store = createStore(initialState, reducerIndex); + render(, { useRedux: true, store }); + await userEvent.click(await screen.findByText('public')); + await userEvent.click(await screen.findByText('orders')); + await waitFor(() => + expect((store.getState() as RootState).messageToasts).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + toastType: ToastType.Danger, + text: 'An error occurred while fetching table metadata for orders', + }), + ]), + ), + ); + expect(screen.queryByText('order_id')).not.toBeInTheDocument(); + metadataShouldFail = false; + await userEvent.click(screen.getByText('orders')); + await userEvent.click(screen.getByText('orders')); + expect(await screen.findByText('order_id')).toBeVisible(); +}); + +test('clearing the selected schema keeps the browser usable for choosing another table', async () => { + const { rerender } = render(, { + useRedux: true, + }); + await screen.findByText('orders'); + rerender(); + expect(await screen.findByText('orders')).toBeVisible(); + expect( + screen.getByPlaceholderText('Enter a part of the object name'), + ).toHaveValue(''); +}); + +test('keyboard expansion of a schema does not preview it as a table', async () => { + const onPreviewTable = jest.fn(); + render(, { + useRedux: true, + }); + const schemaRow = (await screen.findByText('public')).closest('.tree-node'); + expect(schemaRow).not.toBeNull(); + fireEvent.keyDown(schemaRow!, { key: 'Enter' }); + expect(await screen.findByText('orders')).toBeVisible(); + expect(onPreviewTable).not.toHaveBeenCalled(); +}); + +test('table nodes retain working pin controls when showTablePins is omitted', async () => { + const handlePinTable = jest.fn(); + const data: TreeNodeData[] = [ + { + id: 'table:1:public:orders', + name: 'orders', + schema: 'public', + type: 'table', + }, + ]; + render( + data={data} height={300} width={500}> + {nodeProps => ( + + )} + , + ); + await userEvent.click( + await screen.findByRole('button', { name: 'Pin to the result panel' }), + ); + expect(handlePinTable).toHaveBeenCalledWith('orders', 'public', null); +}); + +test('marks tables that already have a dataset when existingTableKeys is provided', async () => { + const data: TreeNodeData[] = [ + { + id: 'table:1:public:orders', + name: 'orders', + schema: 'public', + type: 'table', + }, + ]; + render( + data={data} height={300} width={500}> + {nodeProps => ( + + )} + , + ); + expect( + await screen.findByLabelText('This table already has a dataset'), + ).toBeVisible(); +}); + +test('keeps the search filter when clicking a table updates schema from the tree', async () => { + function PreviewWrapper() { + const [schema, setSchema] = useState('public'); + return ( + setSchema(table.schema)} + /> + ); + } + + render(, { useRedux: true }); + await userEvent.click(await screen.findByText('sales')); + await screen.findAllByText('orders'); + const searchInput = screen.getByPlaceholderText( + 'Enter a part of the object name', + ); + await userEvent.type(searchInput, 'orders'); + const matches = screen.getAllByText('orders'); + await userEvent.click(matches[matches.length - 1]); + expect(searchInput).toHaveValue('orders'); +}); + +test('clears highlighted and expanded table when selectedTable becomes null', async () => { + function SyncWrapper() { + const [selectedTable, setSelectedTable] = useState( + null, + ); + return ( + <> + + + + ); + } + + render(, { useRedux: true }); + await userEvent.click(await screen.findByText('public')); + await userEvent.click(await screen.findByText('orders')); + expect(await screen.findByText('order_id')).toBeVisible(); + expect(screen.getByText('orders').closest('.tree-node')).toHaveAttribute( + 'data-selected', + 'true', + ); + + await userEvent.click(screen.getByRole('button', { name: 'Clear table' })); + await waitFor(() => + expect(screen.getByText('orders').closest('.tree-node')).toHaveAttribute( + 'data-selected', + 'false', + ), + ); + expect(screen.queryByText('order_id')).not.toBeInTheDocument(); +}); + +test('keeps the parent table selected when clicking a column in preview mode', async () => { + render(, { + useRedux: true, + }); + await userEvent.click(await screen.findByText('public')); + await userEvent.click(await screen.findByText('orders')); + const column = await screen.findByText('order_id'); + await userEvent.click(column); + expect(screen.getByText('orders').closest('.tree-node')).toHaveAttribute( + 'data-selected', + 'true', + ); +}); diff --git a/superset-frontend/src/SqlLab/components/TableExploreTree/TableExploreTree.test.tsx b/superset-frontend/src/SqlLab/components/TableExploreTree/TableExploreTree.test.tsx index 0807d558a23c..2bedf44d62d4 100644 --- a/superset-frontend/src/SqlLab/components/TableExploreTree/TableExploreTree.test.tsx +++ b/superset-frontend/src/SqlLab/components/TableExploreTree/TableExploreTree.test.tsx @@ -26,9 +26,10 @@ import { waitFor, } from 'spec/helpers/testing-library'; import reducerIndex from 'spec/helpers/reducerIndex'; +import type { RootState } from 'src/views/store'; import userEvent from '@testing-library/user-event'; import { api } from 'src/hooks/apiResources/queryApi'; -import { initialState, defaultQueryEditor } from 'src/SqlLab/fixtures'; +import { initialState, defaultQueryEditor, table } from 'src/SqlLab/fixtures'; import { ViewLocations } from 'src/SqlLab/contributions'; import { @@ -416,3 +417,124 @@ test('clears the OAuth error banner after a Tables invalidateTags refetch', asyn expect(screen.queryByText('Unexpected error')).not.toBeInTheDocument(), ); }); + +test.each([undefined, 'active-tab-view'])( + 'pins and unpins tables only for the active editor (tab view: %s)', + async tabViewId => { + const catalog = tabViewId ? 'warehouse' : null; + const otherEditorTable = { + ...table, + id: 'other-editor-table', + name: 'users', + schema: 'public', + queryEditorId: 'other-editor', + persistData: { columns: mockColumns }, + }; + const store = createStore( + getInitialState({ + queryEditors: [ + { + ...defaultQueryEditor, + dbId: 1, + catalog, + schema: 'public', + tabViewId, + }, + ], + tables: [otherEditorTable], + }), + reducerIndex, + ); + render(, { + useRedux: true, + store, + }); + await userEvent.click(await screen.findByText('public')); + await userEvent.click(await screen.findByText('users')); + await screen.findByText('id'); + + await userEvent.click(screen.getByTestId('pin-public-users')); + await waitFor(() => + expect((store.getState() as RootState).sqlLab.tables).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + dbId: 1, + catalog, + schema: 'public', + name: 'users', + queryEditorId: tabViewId ?? mockedQueryEditorId, + }), + expect.objectContaining({ id: otherEditorTable.id }), + ]), + ), + ); + await userEvent.click(await screen.findByTestId('unpin-public-users')); + await waitFor(() => + expect((store.getState() as RootState).sqlLab.tables).toEqual([ + otherEditorTable, + ]), + ); + expect(await screen.findByTestId('pin-public-users')).toBeInTheDocument(); + }, +); + +test('pin keys include catalog so same-named tables do not share pin state', async () => { + const tabViewId = 'active-tab-view'; + const catalog = 'warehouse'; + const otherCatalogTable = { + ...table, + id: 'archive-users', + name: 'users', + schema: 'public', + catalog: 'archive', + queryEditorId: tabViewId, + persistData: { columns: mockColumns }, + }; + const store = createStore( + getInitialState({ + queryEditors: [ + { + ...defaultQueryEditor, + dbId: 1, + catalog, + schema: 'public', + tabViewId, + }, + ], + tables: [otherCatalogTable], + }), + reducerIndex, + ); + render(, { + useRedux: true, + store, + }); + await userEvent.click(await screen.findByText('public')); + await userEvent.click(await screen.findByText('users')); + await screen.findByText('id'); + + expect(screen.queryByTestId('pinned-public-users')).not.toBeInTheDocument(); + + await userEvent.click(screen.getByTestId('pin-public-users')); + await waitFor(() => + expect((store.getState() as RootState).sqlLab.tables).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + dbId: 1, + catalog, + schema: 'public', + name: 'users', + queryEditorId: tabViewId, + }), + expect.objectContaining({ id: otherCatalogTable.id }), + ]), + ), + ); + + await userEvent.click(await screen.findByTestId('unpin-public-users')); + await waitFor(() => + expect((store.getState() as RootState).sqlLab.tables).toEqual([ + otherCatalogTable, + ]), + ); +}); diff --git a/superset-frontend/src/SqlLab/components/TableExploreTree/TreeNodeRenderer.tsx b/superset-frontend/src/SqlLab/components/TableExploreTree/TreeNodeRenderer.tsx index 195f1636a355..5263c756edc5 100644 --- a/superset-frontend/src/SqlLab/components/TableExploreTree/TreeNodeRenderer.tsx +++ b/superset-frontend/src/SqlLab/components/TableExploreTree/TreeNodeRenderer.tsx @@ -20,11 +20,11 @@ import { handleKeyboardActivation } from '@superset-ui/core'; import { css, styled, useTheme } from '@apache-superset/core/theme'; import { t } from '@apache-superset/core/translation'; import type { NodeRendererProps } from 'react-arborist'; -import { Icons, Typography } from '@superset-ui/core/components'; +import { Icons, Tooltip, 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, getTableKey } from './types'; const StyledColumnNode = styled.div` & > .ant-flex { @@ -91,12 +91,19 @@ export interface TreeNodeRendererProps extends NodeRendererProps { schemaName: string, catalogName: string | null, ) => void; - handleUnpinTable: (tableName: string, schemaName: string) => void; + handleUnpinTable: ( + tableName: string, + schemaName: string, + catalogName: string | null, + ) => void; handlePinSchema: (schemaName: string) => void; handleUnpinSchema: (schemaName: string) => void; refreshTableSchema: (id: string) => void; sortedTables: Record; toggleSortColumns: (tableId: string) => void; + showTablePins?: boolean; + existingTableKeys?: Set; + onPreviewTable?: (table: TableReference) => void; } const TreeNodeRenderer: React.FC = ({ @@ -116,14 +123,24 @@ const TreeNodeRenderer: React.FC = ({ refreshTableSchema, sortedTables, toggleSortColumns, + showTablePins = true, + existingTableKeys, + 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; + const isTablePreviewMode = Boolean(onPreviewTable); + const nodeOpacity = + isTablePreviewMode && identifier === 'table' + ? getOpacity(!node.isSelected) + : getOpacity(data.disableCheckbox); const renderIcon = () => { if (identifier === 'schema') { @@ -174,12 +191,24 @@ const TreeNodeRenderer: React.FC = ({ // Column nodes use ColumnElement if (identifier === 'column' && data.columnData) { + const columnOpacity = isTablePreviewMode + ? getOpacity(!node.isSelected && !node.parent?.isSelected) + : 1; return ( node.select()} + onClick={e => { + if (isTablePreviewMode) { + e.stopPropagation(); + } else { + node.select(); + } + }} > = ({ data-selected={node.isSelected} onClick={e => { e.stopPropagation(); + if (data.type === 'table' && onPreviewTable) { + node.select(); + onPreviewTable(table); + } if (node.isLeaf) { node.select(); } else { @@ -226,6 +259,10 @@ const TreeNodeRenderer: React.FC = ({ } }} onKeyDown={handleKeyboardActivation(() => { + if (data.type === 'table' && onPreviewTable) { + node.select(); + onPreviewTable(table); + } if (node.isLeaf) { node.select(); } else { @@ -236,7 +273,7 @@ const TreeNodeRenderer: React.FC = ({ {renderIcon()} @@ -244,7 +281,7 @@ const TreeNodeRenderer: React.FC = ({ = ({ {identifier === 'table' && (() => { const nodeDbId = Number(_dbId); - const tableKey = `${nodeDbId}:${schema}:${tableName}`; + const tableKey = getTableKey(nodeDbId, catalog, schema, tableName); const isPinned = pinnedTableKeys.has(tableKey); + const hasExistingDataset = existingTableKeys?.has(tableKey) ?? false; const selectStar = selectStarMap[tableKey]; return ( // Pure event-boundary wrapper: only stops the click/keydown from @@ -332,6 +370,18 @@ const TreeNodeRenderer: React.FC = ({ onClick={e => e.stopPropagation()} onKeyDown={e => e.stopPropagation()} > + {hasExistingDataset && ( + + + + )} {isPinned && (
= ({ `} /> } - onClick={() => handleUnpinTable(tableName, schema)} + onClick={() => + handleUnpinTable(tableName, schema, catalog ?? null) + } />
)} @@ -384,30 +436,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, catalog ?? null) + : handlePinTable(tableName, schema, catalog ?? null) + } + /> + )} ; + pinnedTableKeys?: Set; + onPinTable?: (table: string, schema: string, catalog: string | null) => void; + onUnpinTable?: ( + table: string, + schema: string, + catalog: string | null, + ) => void; + toolbarViewId?: string; + existingTableKeys?: Set; + selectedTable?: TableReference | null; + onPreviewTable?: (table: TableReference) => void; +} + +const EMPTY_PINNED_TABLES = {}; +const EMPTY_PINNED_KEYS = new Set(); +const ignorePin = () => {}; const StyledTreeContainer = styled.div` - flex: 1 1 auto; + flex: 1 1 0; + min-height: 0; + overflow: hidden; .tree-node { display: flex; align-items: center; @@ -163,32 +186,22 @@ const savePinnedSchemasToStorage = ( }); }; -const TableExploreTree: React.FC = ({ queryEditorId }) => { - const dispatch = useAppDispatch(); +export const TableBrowser = ({ + dbId, + catalog, + supportsSchemas, + schema, + pinnedTables = EMPTY_PINNED_TABLES, + pinnedTableKeys = EMPTY_PINNED_KEYS, + onPinTable: handlePinTable = ignorePin, + onUnpinTable: handleUnpinTable = ignorePin, + toolbarViewId, + existingTableKeys = EMPTY_PINNED_KEYS, + selectedTable, + 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,45 +217,16 @@ 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), ); const previousDbIdRef = useRef(dbId); const previousCatalogRef = useRef(catalog); + const selectedTableIdRef = useRef(null); // Single effect handles both loading and persisting pinned schemas. // Using refs to detect source changes avoids the race condition where the @@ -255,6 +239,7 @@ const TableExploreTree: React.FC = ({ queryEditorId }) => { if (dbChanged || catalogChanged) { previousDbIdRef.current = dbId; previousCatalogRef.current = catalog; + selectedTableIdRef.current = null; setPinnedSchemas(getPinnedSchemasFromStorage(dbId, catalog)); return; } @@ -331,6 +316,46 @@ const TableExploreTree: React.FC = ({ queryEditorId }) => { const manuallyOpenedNodesRef = useRef(manuallyOpenedNodes); manuallyOpenedNodesRef.current = manuallyOpenedNodes; + // Collapse the previously previewed table when a different table is selected. + const treeSelectedSchemaRef = useRef(undefined); + const handlePreviewTable = useCallback( + (table: TableReference) => { + const tableId = `table:${dbId}:${table.schema}:${table.table_name}`; + const previousId = selectedTableIdRef.current; + if (previousId && previousId !== tableId) { + treeRef.current?.close(previousId); + setManuallyOpenedNodes(prev => + prev[previousId] ? { ...prev, [previousId]: false } : prev, + ); + } + selectedTableIdRef.current = tableId; + treeSelectedSchemaRef.current = + dbId && table.schema ? `schema:${dbId}:${table.schema}` : undefined; + onPreviewTable?.(table); + }, + [dbId, onPreviewTable], + ); + const previewTableHandler = onPreviewTable ? handlePreviewTable : undefined; + const selectedTableId = + dbId && selectedTable + ? `table:${dbId}:${selectedTable.schema}:${selectedTable.table_name}` + : undefined; + + useEffect(() => { + if (selectedTable === undefined) return; + const previousId = selectedTableIdRef.current; + if (previousId && previousId !== selectedTableId) { + treeRef.current?.close(previousId); + setManuallyOpenedNodes(prev => + prev[previousId] ? { ...prev, [previousId]: false } : prev, + ); + } + if (!selectedTableId) { + treeRef.current?.deselectAll(); + } + selectedTableIdRef.current = selectedTableId ?? null; + }, [selectedTable, selectedTableId]); + // When treeData changes (e.g., children arrive after an async fetch), // react-arborist may reset the open state of nodes that just received children. // Explicitly re-open every node the user has manually opened so children @@ -341,6 +366,22 @@ const TableExploreTree: React.FC = ({ queryEditorId }) => { .forEach(([id]) => treeRef.current?.open(id)); }, [treeData]); + const revealedSchemaRef = useRef(undefined); + useEffect(() => { + const schemaId = dbId && schema ? `schema:${dbId}:${schema}` : undefined; + if (revealedSchemaRef.current === schemaId) return; + revealedSchemaRef.current = schemaId; + const fromTree = treeSelectedSchemaRef.current === schemaId; + treeSelectedSchemaRef.current = undefined; + if (!fromTree) { + setSearchTerm(''); + } + if (!schemaId) return; + setManuallyOpenedNodes(previous => ({ ...previous, [schemaId]: true })); + handleToggle(schemaId, true); + treeRef.current?.open(schemaId); + }, [dbId, schema, handleToggle]); + // Custom search match function for react-arborist const searchMatch = useCallback( (node: NodeApi, term: string): boolean => { @@ -409,6 +450,9 @@ const TableExploreTree: React.FC = ({ queryEditorId }) => { refreshTableSchema={refreshTableSchema} sortedTables={sortedTables} toggleSortColumns={toggleSortColumns} + showTablePins={Boolean(toolbarViewId)} + existingTableKeys={existingTableKeys} + onPreviewTable={previewTableHandler} /> ), [ @@ -427,9 +471,35 @@ const TableExploreTree: React.FC = ({ queryEditorId }) => { loadingNodes, manuallyOpenedNodes, deferredSearchTerm, + toolbarViewId, + existingTableKeys, + previewTableHandler, ], ); + const toolbarActions = ( + <> + + + + + } + > + + + + + ); +} + export type { DatabaseObject }; diff --git a/superset-frontend/src/components/DatabaseSelector/types.ts b/superset-frontend/src/components/DatabaseSelector/types.ts index 6e40d0d957d6..0f16f71ba5b8 100644 --- a/superset-frontend/src/components/DatabaseSelector/types.ts +++ b/superset-frontend/src/components/DatabaseSelector/types.ts @@ -55,6 +55,8 @@ export interface DatabaseSelectorProps { readOnly?: boolean; sqlLabMode?: boolean; filterBySqlLab?: boolean; + showSchema?: boolean; compactMode?: boolean; onOpenModal?: () => void; + onLoadingChange?: (loading: boolean) => void; } diff --git a/superset-frontend/src/features/datasets/AddDataset/LeftPanel/LeftPanel.test.tsx b/superset-frontend/src/features/datasets/AddDataset/LeftPanel/LeftPanel.test.tsx index c1e95ddbdce9..72b6b4057cec 100644 --- a/superset-frontend/src/features/datasets/AddDataset/LeftPanel/LeftPanel.test.tsx +++ b/superset-frontend/src/features/datasets/AddDataset/LeftPanel/LeftPanel.test.tsx @@ -16,303 +16,88 @@ * specific language governing permissions and limitations * under the License. */ -import fetchMock from 'fetch-mock'; -import { - render, - screen, - userEvent, - waitFor, -} from 'spec/helpers/testing-library'; -import LeftPanel from 'src/features/datasets/AddDataset/LeftPanel'; -import { exampleDataset } from 'src/features/datasets/AddDataset/DatasetPanel/fixtures'; - -const databasesEndpoint = 'glob:*/api/v1/database/?q*'; -const schemasEndpoint = 'glob:*/api/v1/database/*/schemas*'; -const tablesEndpoint = 'glob:*/api/v1/database/*/tables/?q*'; - -beforeEach(() => { - fetchMock.get(databasesEndpoint, { - count: 2, - description_columns: {}, - ids: [1, 2], - label_columns: { - allow_file_upload: 'Allow Csv Upload', - allow_ctas: 'Allow Ctas', - allow_cvas: 'Allow Cvas', - allow_dml: 'Allow DDL and DML', - allow_multi_schema_metadata_fetch: 'Allow Multi Schema Metadata Fetch', - allow_run_async: 'Allow Run Async', - allows_cost_estimate: 'Allows Cost Estimate', - allows_subquery: 'Allows Subquery', - allows_virtual_table_explore: 'Allows Virtual Table Explore', - disable_data_preview: 'Disables SQL Lab Data Preview', - disable_drill_to_detail: 'Disable Drill To Detail', - backend: 'Backend', - changed_on: 'Changed On', - changed_on_delta_humanized: 'Changed On Delta Humanized', - 'created_by.first_name': 'Created By First Name', - 'created_by.last_name': 'Created By Last Name', - database_name: 'Database Name', - explore_database_id: 'Explore Database Id', - expose_in_sqllab: 'Expose In Sqllab', - force_ctas_schema: 'Force Ctas Schema', - id: 'Id', - }, - list_columns: [ - 'allow_file_upload', - 'allow_ctas', - 'allow_cvas', - 'allow_dml', - 'allow_multi_schema_metadata_fetch', - 'allow_run_async', - 'allows_cost_estimate', - 'allows_subquery', - 'allows_virtual_table_explore', - 'disable_data_preview', - 'disable_drill_to_detail', - 'backend', - 'changed_on', - 'changed_on_delta_humanized', - 'created_by.first_name', - 'created_by.last_name', - 'database_name', - 'explore_database_id', - 'expose_in_sqllab', - 'force_ctas_schema', - 'id', - ], - list_title: 'List Database', - order_columns: [ - 'allow_file_upload', - 'allow_dml', - 'allow_run_async', - 'changed_on', - 'changed_on_delta_humanized', - 'created_by.first_name', - 'database_name', - 'expose_in_sqllab', - ], - result: [ - { - allow_file_upload: false, - allow_ctas: false, - allow_cvas: false, - allow_dml: false, - allow_multi_schema_metadata_fetch: false, - allow_run_async: false, - allows_cost_estimate: null, - allows_subquery: true, - allows_virtual_table_explore: true, - disable_data_preview: false, - disable_drill_to_detail: false, - backend: 'postgresql', - changed_on: '2021-03-09T19:02:07.141095', - changed_on_delta_humanized: 'a day ago', - created_by: null, - database_name: 'test-postgres', - explore_database_id: 1, - expose_in_sqllab: true, - force_ctas_schema: null, - id: 1, - }, - { - allow_csv_upload: false, - allow_ctas: false, - allow_cvas: false, - allow_dml: false, - allow_multi_schema_metadata_fetch: false, - allow_run_async: false, - allows_cost_estimate: null, - allows_subquery: true, - allows_virtual_table_explore: true, - disable_data_preview: false, - disable_drill_to_detail: false, - backend: 'mysql', - changed_on: '2021-03-09T19:02:07.141095', - changed_on_delta_humanized: 'a day ago', - created_by: null, - database_name: 'test-mysql', - explore_database_id: 1, - expose_in_sqllab: true, - force_ctas_schema: null, - id: 2, - }, - ], - }); - - fetchMock.get(schemasEndpoint, { - result: ['information_schema', 'public'], - }); - - fetchMock.get(tablesEndpoint, { - count: 3, - result: [ - { value: 'Sheet1', type: 'table', extra: null }, - { value: 'Sheet2', type: 'table', extra: null }, - { value: 'Sheet3', type: 'table', extra: null }, - ], - }); -}); - -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(); +import { render, screen, userEvent } from 'spec/helpers/testing-library'; +import type { DatabaseSelectorProps } from 'src/components/DatabaseSelector/types'; +import type { TableBrowserProps } from 'src/SqlLab/components/TableExploreTree'; +import LeftPanel from '.'; +import { DatasetActionType } from '../types'; + +jest.mock('src/components/DatabaseSelector', () => ({ + DatabaseSelectorPopover: ({ + onDbChange, + onSchemaChange, + schema, + }: DatabaseSelectorProps) => ( + <> + + Selected schema: {schema} + + + ), +})); +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', + schema: 'public', + }, +}; +afterEach(() => jest.clearAllMocks()); + +test('supplies the selected connection to the browser', () => { + render(, { useRedux: true }); + expect(screen.getByText('Browser 1:main')).toBeVisible(); + expect(screen.getByText('Selected schema: public')).toBeVisible(); }); -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, - }); - - // 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('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' } }, }); }); -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(); +test('changing the schema dispatches the existing table-reset action', async () => { + render(, { useRedux: true }); + await userEvent.click(screen.getByText('Change schema')); + expect(props.setDataset).toHaveBeenCalledWith({ + type: DatasetActionType.SelectSchema, + payload: { name: 'schema', value: 'sales' }, }); - - 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..a33374905817 100644 --- a/superset-frontend/src/features/datasets/AddDataset/LeftPanel/index.tsx +++ b/superset-frontend/src/features/datasets/AddDataset/LeftPanel/index.tsx @@ -16,205 +16,131 @@ * specific language governing permissions and limitations * under the License. */ -import { useEffect, SetStateAction, Dispatch, useCallback } from 'react'; +import { useEffect, useCallback, useMemo, 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, Divider } from '@superset-ui/core/components'; +import { DatabaseSelectorPopover } from 'src/components/DatabaseSelector'; +import type { DatabaseObject } from 'src/components'; +import { TableBrowser } from 'src/SqlLab/components/TableExploreTree'; +import { + getTableKey, + 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; + datasetNames?: (string | null | 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 existingTableKeys = useMemo( + () => + new Set( + (datasetNames ?? []) + .filter((name): name is string => Boolean(name)) + .map(name => + getTableKey( + dataset?.db?.id, + dataset?.catalog, + dataset?.schema ?? '', + name, + ), + ), + ), + [dataset?.db?.id, dataset?.catalog, dataset?.schema, datasetNames], + ); 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.SelectSchema, + payload: { name: 'schema', value: schema }, + }) + } + onCatalogChange={catalog => + setDataset({ + type: DatasetActionType.SelectCatalog, + payload: { name: 'catalog', value: catalog }, + }) + } /> - + + {dataset?.db ? ( + + ) : ( + + )} + ); } diff --git a/superset-frontend/src/features/datasets/AddDataset/types.tsx b/superset-frontend/src/features/datasets/AddDataset/types.tsx index 2dd8c51acd6a..e760f9382285 100644 --- a/superset-frontend/src/features/datasets/AddDataset/types.tsx +++ b/superset-frontend/src/features/datasets/AddDataset/types.tsx @@ -38,7 +38,7 @@ export interface DatasetObject { export interface DatasetReducerPayloadType { name: string; - value?: string; + value?: string | null; } export type Schema = { 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={