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 = (
+ <>
+ }
+ onClick={() => {
+ treeRef.current?.closeAll();
+ setManuallyOpenedNodes({});
+ }}
+ tooltip={t('Collapse all')}
+ />
+ }
+ onClick={() => refetch()}
+ loading={isFetching}
+ tooltip={t('Force refresh schema list')}
+ />
+ >
+ );
return (
<>
{/* Negative margin to align toolbar icons with other elements on the screen */}
@@ -438,31 +435,14 @@ const TableExploreTree: React.FC = ({ queryEditorId }) => {
margin-left: -${theme.sizeUnit * 2}px;
`}
>
-
- }
- onClick={() => {
- treeRef.current?.closeAll();
- setManuallyOpenedNodes({});
- }}
- tooltip={t('Collapse all')}
- />
- }
- onClick={() => refetch()}
- loading={isFetching}
- tooltip={t('Force refresh schema list')}
- />
- >
- }
- />
+ {toolbarViewId ? (
+
+ ) : (
+ {toolbarActions}
+ )}
= ({ queryEditorId }) => {
);
};
-export default TableExploreTree;
+export default function TableExploreTree({
+ queryEditorId,
+}: {
+ queryEditorId: string;
+}) {
+ const dispatch = useAppDispatch();
+ 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],
+ );
+
+ 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],
+ );
+
+ return (
+
+ );
+}
diff --git a/superset-frontend/src/SqlLab/components/TableExploreTree/types.ts b/superset-frontend/src/SqlLab/components/TableExploreTree/types.ts
index f56805c3c3d9..e624a01e517d 100644
--- a/superset-frontend/src/SqlLab/components/TableExploreTree/types.ts
+++ b/superset-frontend/src/SqlLab/components/TableExploreTree/types.ts
@@ -23,6 +23,7 @@ export interface TreeNodeData {
name: string;
type: 'schema' | 'table' | 'column' | 'empty';
tableType?: string;
+ schema?: string;
columnData?: {
name: string;
keys?: { type: ColumnKeyTypeType }[];
@@ -38,3 +39,8 @@ export interface FetchLazyTablesParams {
schema: string;
forceRefresh: boolean;
}
+
+export interface TableReference {
+ schema: string;
+ table_name: string;
+}
diff --git a/superset-frontend/src/SqlLab/components/TableExploreTree/useTreeData.ts b/superset-frontend/src/SqlLab/components/TableExploreTree/useTreeData.ts
index c26830b38972..e643a8f3338a 100644
--- a/superset-frontend/src/SqlLab/components/TableExploreTree/useTreeData.ts
+++ b/superset-frontend/src/SqlLab/components/TableExploreTree/useTreeData.ts
@@ -28,7 +28,7 @@ import {
useLazyTableMetadataQuery,
useLazyTableExtendedMetadataQuery,
} from 'src/hooks/apiResources';
-import { addDangerToast } from 'src/SqlLab/actions/sqlLab';
+import { addDangerToast } from 'src/components/MessageToasts/actions';
import type { TreeNodeData } from './types';
import { ClientErrorObject, SupersetError } from '@superset-ui/core';
@@ -118,6 +118,7 @@ function treeDataReducer(
interface UseTreeDataParams {
dbId: number | undefined;
+ supportsSchemas?: boolean;
catalog: string | null | undefined;
pinnedTables: Record;
}
@@ -148,11 +149,12 @@ const useTreeData = ({
dbId,
catalog,
pinnedTables,
+ supportsSchemas = true,
}: UseTreeDataParams): UseTreeDataResult => {
const reduxDispatch = useAppDispatch();
// Schema data from API
const {
- currentData: schemaData,
+ currentData: schemaOptions,
isFetching,
refetch,
} = useSchemas({ dbId, catalog: catalog || undefined });
@@ -405,7 +407,11 @@ const useTreeData = ({
// Build tree data
const treeData = useMemo((): TreeNodeData[] => {
- const data = schemaData?.map(schema => {
+ const schemas =
+ !supportsSchemas && dbId
+ ? [{ value: '', label: t('Tables') }]
+ : schemaOptions;
+ const data = schemas?.map(schema => {
const schemaKey = `${dbId}:${schema.value}`;
const schemaId = `schema:${dbId}:${schema.value}`;
const tablesData = tableData?.[schemaKey];
@@ -446,6 +452,7 @@ const useTreeData = ({
return {
id: tableId,
name: tableName,
+ schema: schema.value,
type: 'table' as const,
tableType,
children: tableChildren,
@@ -460,6 +467,7 @@ const useTreeData = ({
return {
id: schemaId,
name: schema.label,
+ schema: schema.value,
type: 'schema' as const,
children: schemaChildren,
disableCheckbox: !tablesData,
@@ -467,7 +475,14 @@ const useTreeData = ({
});
return data ?? [];
- }, [dbId, schemaData, tableData, tableSchemaData, pinnedTables]);
+ }, [
+ dbId,
+ schemaOptions,
+ supportsSchemas,
+ tableData,
+ tableSchemaData,
+ pinnedTables,
+ ]);
// Map of tableKey -> selectStar SQL from table metadata
const selectStarMap = useMemo(() => {
diff --git a/superset-frontend/src/components/DatabaseSelector/index.tsx b/superset-frontend/src/components/DatabaseSelector/index.tsx
index 2ff0f0851c48..bdafb64bca17 100644
--- a/superset-frontend/src/components/DatabaseSelector/index.tsx
+++ b/superset-frontend/src/components/DatabaseSelector/index.tsx
@@ -189,6 +189,7 @@ export function DatabaseSelector({
compactMode = false,
sqlLabMode = false,
filterBySqlLab = false,
+ showSchema = true,
onOpenModal,
}: DatabaseSelectorProps) {
const showCatalogSelector = !!db?.allow_multi_catalog;
@@ -608,7 +609,10 @@ export function DatabaseSelector({
{renderDatabaseSelect()}
{renderError()}
{!sqlLabCompactMode && showCatalogSelector && renderCatalogSelect()}
- {!sqlLabCompactMode && showSchemaSelector && renderSchemaSelect()}
+ {showSchema &&
+ !sqlLabCompactMode &&
+ showSchemaSelector &&
+ renderSchemaSelect()}
);
}
diff --git a/superset-frontend/src/components/DatabaseSelector/types.ts b/superset-frontend/src/components/DatabaseSelector/types.ts
index 6f5058107cdb..2ad59ae83ecd 100644
--- a/superset-frontend/src/components/DatabaseSelector/types.ts
+++ b/superset-frontend/src/components/DatabaseSelector/types.ts
@@ -51,6 +51,7 @@ export interface DatabaseSelectorProps {
readOnly?: boolean;
sqlLabMode?: boolean;
filterBySqlLab?: boolean;
+ showSchema?: boolean;
compactMode?: boolean;
onOpenModal?: () => 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..6d84e0de4bca 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,73 @@
* 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 },
- ],
- });
+import { render, screen, userEvent } from 'spec/helpers/testing-library';
+import type { TableBrowserProps } from 'src/SqlLab/components/TableExploreTree';
+import LeftPanel from '.';
+import { DatasetActionType } from '../types';
+
+jest.mock('src/components/DatabaseSelector', () => ({
+ DatabaseSelector: ({
+ onDbChange,
+ showSchema,
+ }: {
+ onDbChange: (db: { id: number; database_name: string }) => void;
+ showSchema: boolean;
+ }) => (
+ <>
+
+ {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={}
/>,
@@ -133,7 +139,9 @@ describe('DatasetLayout', () => {
const { container } = render(
null} />}
- leftPanel={ null} />}
+ leftPanel={
+ null} onPreviewTable={jest.fn()} />
+ }
datasetPanel={
\n"
"Language-Team: LANGUAGE \n"
@@ -3454,6 +3454,9 @@ msgstr ""
msgid "Choose a chart or dashboard not both"
msgstr ""
+msgid "Choose a data connection to browse schemas, tables, and views."
+msgstr ""
+
msgid "Choose a database..."
msgstr ""
@@ -3844,14 +3847,10 @@ msgstr ""
msgid "Color scheme: %s"
msgstr ""
-msgid ""
-"Color used for the arrow and symbols when the metric decreased from the "
-"comparison value. Defaults to red."
+msgid "Color used for the arrow and symbols when the metric decreased from the comparison value. Defaults to red."
msgstr ""
-msgid ""
-"Color used for the arrow and symbols when the metric increased from the "
-"comparison value. Defaults to green."
+msgid "Color used for the arrow and symbols when the metric increased from the comparison value. Defaults to green."
msgstr ""
msgid "Color used when the close value is greater than or equal to the open value."
@@ -7339,9 +7338,7 @@ msgstr ""
msgid "Fix the Extra JSON to edit certification"
msgstr ""
-msgid ""
-"Fix the JSON errors below to edit colors here; your changes sync "
-"automatically once the JSON is valid again."
+msgid "Fix the JSON errors below to edit colors here; your changes sync automatically once the JSON is valid again."
msgstr ""
msgid "Fix the trend line to the full time range specified in case filtered results do not include the start or end dates"
@@ -9032,9 +9029,6 @@ msgstr ""
msgid "Manage filters and customizations to set scoping, descriptions, and limitations. Create new elements for better dashboard insights."
msgstr ""
-msgid "Manage your databases"
-msgstr ""
-
msgid "Mandatory"
msgstr ""
@@ -9846,12 +9840,6 @@ msgstr ""
msgid "No data in file"
msgstr ""
-msgid "No databases available"
-msgstr ""
-
-msgid "No databases match your search"
-msgstr ""
-
msgid "No description available."
msgstr ""
@@ -10437,9 +10425,7 @@ msgstr ""
msgid "Optional CA_BUNDLE contents to validate HTTPS requests. Only available on certain database engines."
msgstr ""
-msgid ""
-"Optional custom color for each range band, e.g. to match a brand palette."
-" Bands left unset use the default shading."
+msgid "Optional custom color for each range band, e.g. to match a brand palette. Bands left unset use the default shading."
msgstr ""
msgid "Optional d3 date format string"
@@ -10805,11 +10791,7 @@ msgstr ""
msgid "Physical (table or view)"
msgstr ""
-msgid ""
-"Pick a color for each interval band defined above by its upper bound. "
-"Charts saved with the legacy 1-indexed \"Interval colors\" text field keep"
-" following the chosen color scheme until an interval color is "
-"edited."
+msgid "Pick a color for each interval band defined above by its upper bound. Charts saved with the legacy 1-indexed \"Interval colors\" text field keep following the chosen color scheme until an interval color is edited."
msgstr ""
msgid "Pick a dimension from which categorical colors are defined"
@@ -11463,13 +11445,13 @@ msgstr ""
msgid "Refreshing columns"
msgstr ""
-msgid "Region name"
+msgid "Region"
msgstr ""
-msgid "Region value format"
+msgid "Region name"
msgstr ""
-msgid "Region"
+msgid "Region value format"
msgstr ""
msgid "Register"
@@ -12658,6 +12640,9 @@ msgstr ""
msgid "Select a dashboard"
msgstr ""
+msgid "Select a data connection"
+msgstr ""
+
msgid "Select a database"
msgstr ""
@@ -14670,14 +14655,10 @@ msgstr ""
msgid "The feature property to use for point labels"
msgstr ""
-msgid ""
-"The filters from the link you opened could not be loaded, so this link "
-"shares the default view."
+msgid "The filters from the link you opened could not be loaded, so this link shares the default view."
msgstr ""
-msgid ""
-"The filters from this link have expired, so you’re seeing the default "
-"view."
+msgid "The filters from this link have expired, so you’re seeing the default view."
msgstr ""
msgid "The following charts could not be exported:"
@@ -15640,10 +15621,10 @@ msgstr ""
msgid "This chart has been moved to a different filter scope."
msgstr ""
-msgid "This chart is archived or unavailable. An editor can restore archived charts from Recently Archived."
+msgid "This chart is archived or unavailable."
msgstr ""
-msgid "This chart is archived or unavailable."
+msgid "This chart is archived or unavailable. An editor can restore archived charts from Recently Archived."
msgstr ""
msgid "This chart is managed externally and can't be overwritten in Superset."
@@ -17311,9 +17292,7 @@ msgstr ""
msgid "We can't seem to resolve the column \"%(column_name)s\"."
msgstr ""
-msgid ""
-"We couldn’t load the filters from this link, so you’re seeing the default"
-" view."
+msgid "We couldn’t load the filters from this link, so you’re seeing the default view."
msgstr ""
#, python-format
From 4350314e064e87f83b9797fac87c4077dd1d5382 Mon Sep 17 00:00:00 2001
From: Haseeb702 <80732008+Haseeb702@users.noreply.github.com>
Date: Wed, 18 Nov 2026 13:49:01 -0500
Subject: [PATCH 03/16] feat(datasets): modified datasource selector ui
---
.../playwright/pages/CreateDatasetPage.ts | 29 +++-
.../components/SqlEditorLeftBar/index.tsx | 149 +-----------------
.../TableExploreTree/TableBrowser.test.tsx | 15 ++
.../components/TableExploreTree/index.tsx | 14 ++
.../DatabaseSelector.test.tsx | 74 ++++++++-
.../src/components/DatabaseSelector/index.tsx | 124 +++++++++++++++
.../AddDataset/LeftPanel/LeftPanel.test.tsx | 37 +++--
.../datasets/AddDataset/LeftPanel/index.tsx | 22 ++-
.../DatasetCreation/DatasetCreation.test.tsx | 32 +++-
9 files changed, 322 insertions(+), 174 deletions(-)
diff --git a/superset-frontend/playwright/pages/CreateDatasetPage.ts b/superset-frontend/playwright/pages/CreateDatasetPage.ts
index 018b2ab9b948..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';
@@ -64,11 +64,17 @@ 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();
}
/**
@@ -76,11 +82,16 @@ export class CreateDatasetPage {
* @param schemaName - The name of the schema to select
*/
async selectSchema(schemaName: string): Promise {
- await this.page.getByPlaceholder('Enter a part of the object name').clear();
- await this.page
- .getByRole('treeitem')
- .getByText(schemaName, { exact: true })
- .click();
+ 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();
}
/**
@@ -128,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/TableExploreTree/TableBrowser.test.tsx b/superset-frontend/src/SqlLab/components/TableExploreTree/TableBrowser.test.tsx
index 53ed0ea60da5..df9179976984 100644
--- a/superset-frontend/src/SqlLab/components/TableExploreTree/TableBrowser.test.tsx
+++ b/superset-frontend/src/SqlLab/components/TableExploreTree/TableBrowser.test.tsx
@@ -113,3 +113,18 @@ test('shows an empty result when no loaded table matches the search', async () =
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',
+ });
+});
diff --git a/superset-frontend/src/SqlLab/components/TableExploreTree/index.tsx b/superset-frontend/src/SqlLab/components/TableExploreTree/index.tsx
index 8aa4f5b5054f..a743b4d4afce 100644
--- a/superset-frontend/src/SqlLab/components/TableExploreTree/index.tsx
+++ b/superset-frontend/src/SqlLab/components/TableExploreTree/index.tsx
@@ -60,6 +60,7 @@ import { ErrorMessageWithStackTrace } from 'src/components';
export interface TableBrowserProps {
dbId?: number;
supportsSchemas?: boolean;
+ schema?: string;
catalog?: string | null;
pinnedTables?: Record;
pinnedTableKeys?: Set;
@@ -181,6 +182,7 @@ export const TableBrowser = ({
dbId,
catalog,
supportsSchemas,
+ schema,
pinnedTables = EMPTY_PINNED_TABLES,
pinnedTableKeys = EMPTY_PINNED_KEYS,
onPinTable: handlePinTable = ignorePin,
@@ -312,6 +314,18 @@ export const TableBrowser = ({
.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;
+ 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 => {
diff --git a/superset-frontend/src/components/DatabaseSelector/DatabaseSelector.test.tsx b/superset-frontend/src/components/DatabaseSelector/DatabaseSelector.test.tsx
index 88b837406dac..81ca95c21428 100644
--- a/superset-frontend/src/components/DatabaseSelector/DatabaseSelector.test.tsx
+++ b/superset-frontend/src/components/DatabaseSelector/DatabaseSelector.test.tsx
@@ -25,10 +25,11 @@ import {
screen,
userEvent,
waitFor,
+ within,
} from 'spec/helpers/testing-library';
import { api } from 'src/hooks/apiResources/queryApi';
import { EmptyState } from '@superset-ui/core/components';
-import { DatabaseSelector } from '.';
+import { DatabaseSelector, DatabaseSelectorPopover } from '.';
import type { DatabaseSelectorProps } from './types';
const createProps = (): DatabaseSelectorProps => ({
@@ -529,3 +530,74 @@ test('should include expose_in_sqllab filter when filterBySqlLab is true', async
expect(lastCall.url).toContain('expose_in_sqllab');
});
});
+
+test('popover keeps schema edits staged and discards them on cancel', async () => {
+ const props = createProps();
+ render(, { useRedux: true, store });
+ await userEvent.click(screen.getByTestId('database-selector-trigger'));
+ const dialog = within(
+ await screen.findByRole('group', { name: 'Select Database and Schema' }),
+ );
+ await userEvent.click(
+ dialog.getByRole('combobox', { name: /^Select schema/ }),
+ );
+ await userEvent.click(
+ await screen.findByText('information_schema', { exact: true }),
+ );
+ expect(props.onSchemaChange).not.toHaveBeenCalled();
+ await userEvent.click(dialog.getByRole('button', { name: 'Cancel' }));
+ expect(props.onDbChange).not.toHaveBeenCalled();
+ expect(props.onSchemaChange).not.toHaveBeenCalled();
+ await userEvent.click(screen.getByTestId('database-selector-trigger'));
+ expect(
+ await within(
+ await screen.findByRole('group', { name: 'Select Database and Schema' }),
+ ).findByRole('combobox', {
+ name: 'Select schema: public',
+ }),
+ ).toBeInTheDocument();
+});
+
+test('popover applies a new database and its schema only after confirmation', async () => {
+ const props = createProps();
+ render(, { useRedux: true, store });
+ await userEvent.click(screen.getByTestId('database-selector-trigger'));
+ const dialog = within(
+ await screen.findByRole('group', { name: 'Select Database and Schema' }),
+ );
+ await userEvent.click(
+ dialog.getByRole('combobox', {
+ name: /Select database or type to search databases/,
+ }),
+ );
+ await userEvent.click(await screen.findByText('test-mysql', { exact: true }));
+ await userEvent.click(
+ dialog.getByRole('combobox', { name: /^Select schema/ }),
+ );
+ await userEvent.click(await screen.findByRole('option', { name: 'public' }));
+ expect(props.onDbChange).not.toHaveBeenCalled();
+ expect(props.onSchemaChange).not.toHaveBeenCalled();
+ await userEvent.click(dialog.getByRole('button', { name: 'Select' }));
+ expect(props.onDbChange).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 2 }),
+ );
+ expect(props.onSchemaChange).toHaveBeenCalledWith('public');
+ expect(
+ fetchMock.callHistory.calls(databaseApiRoute).at(-1)?.url,
+ ).not.toContain('expose_in_sqllab');
+});
+
+test('confirming an unchanged popover selection preserves the current source', async () => {
+ const props = createProps();
+ render(, { useRedux: true, store });
+ await userEvent.click(screen.getByTestId('database-selector-trigger'));
+ await userEvent.click(
+ within(
+ await screen.findByRole('group', { name: 'Select Database and Schema' }),
+ ).getByRole('button', {
+ name: 'Select',
+ }),
+ );
+ expect(props.onDbChange).not.toHaveBeenCalled();
+ expect(props.onSchemaChange).not.toHaveBeenCalled();
+});
diff --git a/superset-frontend/src/components/DatabaseSelector/index.tsx b/superset-frontend/src/components/DatabaseSelector/index.tsx
index 573dce85bd57..90c196f0160d 100644
--- a/superset-frontend/src/components/DatabaseSelector/index.tsx
+++ b/superset-frontend/src/components/DatabaseSelector/index.tsx
@@ -43,6 +43,10 @@ import {
LabeledValue as AntdLabeledValue,
Button,
Icons,
+ EmptyState,
+ Flex,
+ Popover,
+ Typography,
} from '@superset-ui/core/components';
import { ErrorMessageWithStackTrace } from 'src/components';
@@ -630,4 +634,124 @@ export function DatabaseSelector({
);
}
+/** Render SQL Lab's connection/schema summary with a staged selection popover. */
+export function DatabaseSelectorPopover({
+ db,
+ catalog,
+ schema,
+ onDbChange,
+ onCatalogChange,
+ onSchemaChange,
+ compactMode,
+ ...selectorProps
+}: Omit) {
+ const [open, setOpen] = useState(false);
+ const [selectionSession, setSelectionSession] = useState(0);
+ const [draftDb, setDraftDb] = useState();
+ const [draftCatalog, setDraftCatalog] = useState();
+ const [draftSchema, setDraftSchema] = useState();
+
+ const openSelector = () => {
+ setSelectionSession(session => session + 1);
+ setDraftDb(db ?? undefined);
+ setDraftCatalog(catalog ?? undefined);
+ setDraftSchema(schema);
+ setOpen(true);
+ };
+
+ const applySelection = () => {
+ const databaseChanged = draftDb?.id !== db?.id;
+ const catalogChanged = draftCatalog !== (catalog ?? undefined);
+ if (draftDb && databaseChanged) onDbChange?.(draftDb);
+ if (databaseChanged || catalogChanged) onCatalogChange?.(draftCatalog);
+ if (databaseChanged || catalogChanged || draftSchema !== schema) {
+ onSchemaChange?.(draftSchema);
+ }
+ setOpen(false);
+ };
+
+ return (
+ {
+ if (nextOpen) openSelector();
+ else setOpen(false);
+ }}
+ placement="bottomLeft"
+ trigger="click"
+ content={
+
+
+ {t('Select Database and Schema')}
+
+ }
+ onDbChange={nextDb => {
+ setDraftDb(nextDb);
+ setDraftCatalog(undefined);
+ setDraftSchema(undefined);
+ }}
+ onCatalogChange={nextCatalog => {
+ setDraftCatalog(nextCatalog);
+ setDraftSchema(undefined);
+ }}
+ onSchemaChange={setDraftSchema}
+ />
+
+
+
+
+
+ }
+ >
+
+
+
+
+ );
+}
+
export type { DatabaseObject };
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 6d84e0de4bca..72b6b4057cec 100644
--- a/superset-frontend/src/features/datasets/AddDataset/LeftPanel/LeftPanel.test.tsx
+++ b/superset-frontend/src/features/datasets/AddDataset/LeftPanel/LeftPanel.test.tsx
@@ -17,26 +17,28 @@
* under the License.
*/
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', () => ({
- DatabaseSelector: ({
+ DatabaseSelectorPopover: ({
onDbChange,
- showSchema,
- }: {
- onDbChange: (db: { id: number; database_name: string }) => void;
- showSchema: boolean;
- }) => (
+ onSchemaChange,
+ schema,
+ }: DatabaseSelectorProps) => (
<>
- {showSchema && Schema dropdown}
+ Selected schema: {schema}
+
>
),
}));
@@ -59,14 +61,18 @@ jest.mock('src/SqlLab/components/TableExploreTree', () => ({
const props = {
setDataset: jest.fn(),
onPreviewTable: jest.fn(),
- dataset: { db: { id: 1, database_name: 'examples' }, catalog: 'main' },
+ dataset: {
+ db: { id: 1, database_name: 'examples' },
+ catalog: 'main',
+ schema: 'public',
+ },
};
afterEach(() => jest.clearAllMocks());
-test('supplies the selected connection to the browser and hides the schema dropdown', () => {
+test('supplies the selected connection to the browser', () => {
render(, { useRedux: true });
expect(screen.getByText('Browser 1:main')).toBeVisible();
- expect(screen.queryByText('Schema dropdown')).not.toBeInTheDocument();
+ expect(screen.getByText('Selected schema: public')).toBeVisible();
});
test('notifies the dataset page of the selected table and schema', async () => {
@@ -86,3 +92,12 @@ test('changing the connection dispatches the existing source-reset action', asyn
payload: { db: { id: 2, database_name: 'other' } },
});
});
+
+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' },
+ });
+});
diff --git a/superset-frontend/src/features/datasets/AddDataset/LeftPanel/index.tsx b/superset-frontend/src/features/datasets/AddDataset/LeftPanel/index.tsx
index fe2a8d94262b..8015e646568e 100644
--- a/superset-frontend/src/features/datasets/AddDataset/LeftPanel/index.tsx
+++ b/superset-frontend/src/features/datasets/AddDataset/LeftPanel/index.tsx
@@ -19,8 +19,8 @@
import { useEffect, useCallback, type Dispatch } from 'react';
import { t } from '@apache-superset/core/translation';
import { useTheme } from '@apache-superset/core/theme';
-import { Flex, EmptyState } from '@superset-ui/core/components';
-import { DatabaseSelector } from 'src/components/DatabaseSelector';
+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 type { TableReference } from 'src/SqlLab/components/TableExploreTree/types';
@@ -64,14 +64,24 @@ export default function LeftPanel({
-
+ setDataset({
+ type: DatasetActionType.SelectSchema,
+ payload: { name: 'schema', value: schema },
+ })
+ }
onCatalogChange={catalog =>
setDataset({
type: DatasetActionType.SelectCatalog,
@@ -79,11 +89,13 @@ export default function LeftPanel({
})
}
/>
+
{dataset?.db ? (
diff --git a/superset-frontend/src/pages/DatasetCreation/DatasetCreation.test.tsx b/superset-frontend/src/pages/DatasetCreation/DatasetCreation.test.tsx
index 8edcc3570436..8b88266a1c4a 100644
--- a/superset-frontend/src/pages/DatasetCreation/DatasetCreation.test.tsx
+++ b/superset-frontend/src/pages/DatasetCreation/DatasetCreation.test.tsx
@@ -24,6 +24,7 @@ import {
screen,
userEvent,
waitFor,
+ within,
} from 'spec/helpers/testing-library';
import { LocalStorageKeys, setItem } from 'src/utils/localStorageHelpers';
import AddDataset, { datasetReducer } from '.';
@@ -87,8 +88,14 @@ afterEach(() => {
localStorage.removeItem(LocalStorageKeys.Database);
});
-async function selectOrders() {
- await userEvent.click(await screen.findByText('public', { exact: true }));
+async function selectOrders(schemaSelected = false) {
+ if (!schemaSelected) {
+ await userEvent.click(
+ within(await screen.findByRole('tree')).getByText('public', {
+ exact: true,
+ }),
+ );
+ }
await userEvent.click(await screen.findByText('orders', { exact: true }));
await waitFor(() =>
expect(screen.getAllByText('order_id').length).toBeGreaterThan(0),
@@ -109,11 +116,13 @@ test('selects a table through the browser and clears its preview when the connec
});
render(, { useRedux: true, useRouter: true });
await selectOrders();
- const connection = screen.getByRole('combobox', {
+ await userEvent.click(screen.getByTestId('database-selector-trigger'));
+ const connection = await screen.findByRole('combobox', {
name: /Select (database|data connection) or type/i,
});
await userEvent.click(connection);
await userEvent.click(await screen.findByText('analytics', { exact: true }));
+ await userEvent.click(screen.getByRole('button', { name: 'Select' }));
await waitFor(() =>
expect(screen.queryByText('order_id')).not.toBeInTheDocument(),
);
@@ -128,15 +137,22 @@ test('selects a table through the browser and clears its preview when the connec
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(screen.getByTestId('database-selector-trigger'));
+ const catalog = await screen.findByRole('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(screen.getByRole('button', { name: 'Select' }));
+ await selectOrders(true);
+ await userEvent.click(screen.getByTestId('database-selector-trigger'));
+ await userEvent.click(
+ await screen.findByRole('combobox', {
+ name: /^Select catalog or type to search catalogs/,
+ }),
+ );
await userEvent.click(await screen.findByText('archive', { exact: true }));
- await userEvent.click(await screen.findByText('public', { exact: true }));
+ await userEvent.click(screen.getByRole('button', { name: 'Select' }));
expect(
await screen.findByText('archived_orders', { exact: true }),
).toBeVisible();
From b9e642e726475b89324044c137d8509f6d26e8b7 Mon Sep 17 00:00:00 2001
From: Haseeb702 <80732008+Haseeb702@users.noreply.github.com>
Date: Wed, 18 Nov 2026 21:47:42 -0500
Subject: [PATCH 04/16] test(datasets): add test for table pin controls
---
.../TableExploreTree/TableBrowser.test.tsx | 43 +++++++++++++++++++
1 file changed, 43 insertions(+)
diff --git a/superset-frontend/src/SqlLab/components/TableExploreTree/TableBrowser.test.tsx b/superset-frontend/src/SqlLab/components/TableExploreTree/TableBrowser.test.tsx
index 84886a3b7ac7..84c5746ad9da 100644
--- a/superset-frontend/src/SqlLab/components/TableExploreTree/TableBrowser.test.tsx
+++ b/superset-frontend/src/SqlLab/components/TableExploreTree/TableBrowser.test.tsx
@@ -18,6 +18,7 @@
*/
import type { ReactNode } from 'react';
import fetchMock from 'fetch-mock';
+import { Tree } from 'react-arborist';
import {
fireEvent,
createStore,
@@ -27,6 +28,8 @@ import {
waitFor,
} from 'spec/helpers/testing-library';
import { TableBrowser } from '.';
+import TreeNodeRenderer from './TreeNodeRenderer';
+import type { TreeNodeData } from './types';
import reducerIndex from 'spec/helpers/reducerIndex';
import type { RootState } from 'src/views/store';
import { initialState } from 'src/SqlLab/fixtures';
@@ -277,3 +280,43 @@ test('keyboard expansion of a schema does not preview it as a table', async () =
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);
+});
From 0e3b53608d8d7105298581edff292861f3f135cc Mon Sep 17 00:00:00 2001
From: Haseeb702 <80732008+Haseeb702@users.noreply.github.com>
Date: Tue, 24 Nov 2026 00:13:55 -0500
Subject: [PATCH 05/16] fix(datasets): fixed left panel clipping
---
.../src/SqlLab/components/TableExploreTree/index.tsx | 4 +++-
.../src/features/datasets/AddDataset/LeftPanel/index.tsx | 2 ++
2 files changed, 5 insertions(+), 1 deletion(-)
diff --git a/superset-frontend/src/SqlLab/components/TableExploreTree/index.tsx b/superset-frontend/src/SqlLab/components/TableExploreTree/index.tsx
index a743b4d4afce..2794219e6bf0 100644
--- a/superset-frontend/src/SqlLab/components/TableExploreTree/index.tsx
+++ b/superset-frontend/src/SqlLab/components/TableExploreTree/index.tsx
@@ -75,7 +75,9 @@ 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;
diff --git a/superset-frontend/src/features/datasets/AddDataset/LeftPanel/index.tsx b/superset-frontend/src/features/datasets/AddDataset/LeftPanel/index.tsx
index 8015e646568e..7df5e9ff89a0 100644
--- a/superset-frontend/src/features/datasets/AddDataset/LeftPanel/index.tsx
+++ b/superset-frontend/src/features/datasets/AddDataset/LeftPanel/index.tsx
@@ -66,6 +66,8 @@ export default function LeftPanel({
gap="small"
style={{
height: '100%',
+ minHeight: 0,
+ overflow: 'hidden',
padding: theme.sizeUnit * 4,
position: 'relative',
}}
From 47613f4a83898fc89239d79b264fbbbe1a051980 Mon Sep 17 00:00:00 2001
From: Haseeb702 <80732008+Haseeb702@users.noreply.github.com>
Date: Tue, 24 Nov 2026 02:29:26 -0500
Subject: [PATCH 06/16] fix(datasets): removed white opacity caching and allow
only 1 table drop down
---
.../TableExploreTree/TreeNodeRenderer.tsx | 25 ++++++++++++++++---
.../components/TableExploreTree/index.tsx | 25 +++++++++++++++++--
2 files changed, 44 insertions(+), 6 deletions(-)
diff --git a/superset-frontend/src/SqlLab/components/TableExploreTree/TreeNodeRenderer.tsx b/superset-frontend/src/SqlLab/components/TableExploreTree/TreeNodeRenderer.tsx
index 3d25675e7ca4..0205003faa5d 100644
--- a/superset-frontend/src/SqlLab/components/TableExploreTree/TreeNodeRenderer.tsx
+++ b/superset-frontend/src/SqlLab/components/TableExploreTree/TreeNodeRenderer.tsx
@@ -130,6 +130,11 @@ const TreeNodeRenderer: React.FC = ({
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') {
@@ -180,10 +185,16 @@ 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()}
>
@@ -225,7 +236,10 @@ const TreeNodeRenderer: React.FC = ({
data-selected={node.isSelected}
onClick={e => {
e.stopPropagation();
- if (data.type === 'table') onPreviewTable?.(table);
+ if (data.type === 'table' && onPreviewTable) {
+ node.select();
+ onPreviewTable(table);
+ }
if (node.isLeaf) {
node.select();
} else {
@@ -233,7 +247,10 @@ const TreeNodeRenderer: React.FC = ({
}
}}
onKeyDown={handleKeyboardActivation(() => {
- if (data.type === 'table') onPreviewTable?.(table);
+ if (data.type === 'table' && onPreviewTable) {
+ node.select();
+ onPreviewTable(table);
+ }
if (node.isLeaf) {
node.select();
} else {
@@ -244,7 +261,7 @@ const TreeNodeRenderer: React.FC = ({
{renderIcon()}
@@ -252,7 +269,7 @@ const TreeNodeRenderer: React.FC = ({
(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
@@ -230,6 +231,7 @@ export const TableBrowser = ({
if (dbChanged || catalogChanged) {
previousDbIdRef.current = dbId;
previousCatalogRef.current = catalog;
+ selectedTableIdRef.current = null;
setPinnedSchemas(getPinnedSchemasFromStorage(dbId, catalog));
return;
}
@@ -306,6 +308,24 @@ export const TableBrowser = ({
const manuallyOpenedNodesRef = useRef(manuallyOpenedNodes);
manuallyOpenedNodesRef.current = manuallyOpenedNodes;
+ // Collapse the previously previewed table when a different table is selected.
+ 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;
+ onPreviewTable?.(table);
+ },
+ [dbId, onPreviewTable],
+ );
+ const previewTableHandler = onPreviewTable ? handlePreviewTable : undefined;
+
// 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
@@ -397,7 +417,7 @@ export const TableBrowser = ({
sortedTables={sortedTables}
toggleSortColumns={toggleSortColumns}
showTablePins={Boolean(toolbarViewId)}
- onPreviewTable={onPreviewTable}
+ onPreviewTable={previewTableHandler}
/>
),
[
@@ -417,7 +437,7 @@ export const TableBrowser = ({
manuallyOpenedNodes,
deferredSearchTerm,
toolbarViewId,
- onPreviewTable,
+ previewTableHandler,
],
);
@@ -430,6 +450,7 @@ export const TableBrowser = ({
onClick={() => {
treeRef.current?.closeAll();
setManuallyOpenedNodes({});
+ selectedTableIdRef.current = null;
}}
tooltip={t('Collapse all')}
/>
From 449dfe0a69d9e277600f28efc9b4d1b8c496f41d Mon Sep 17 00:00:00 2001
From: Haseeb702 <80732008+Haseeb702@users.noreply.github.com>
Date: Wed, 25 Nov 2026 00:01:09 -0500
Subject: [PATCH 07/16] fix(datasets): addressed AI review bot comments
---
.../TableExploreTree.test.tsx | 63 +++++++++++++++++++
.../TableExploreTree/TreeNodeRenderer.tsx | 16 +++--
.../components/TableExploreTree/index.tsx | 33 +++++++---
.../components/TableExploreTree/types.ts | 13 ++++
.../TableExploreTree/useTreeData.ts | 15 ++---
.../src/components/DatabaseSelector/index.tsx | 19 +++++-
.../src/components/DatabaseSelector/types.ts | 1 +
.../features/datasets/AddDataset/types.tsx | 2 +-
.../DatasetCreation/DatasetCreation.test.tsx | 30 +++++++++
.../src/pages/DatasetCreation/index.tsx | 3 +-
10 files changed, 172 insertions(+), 23 deletions(-)
diff --git a/superset-frontend/src/SqlLab/components/TableExploreTree/TableExploreTree.test.tsx b/superset-frontend/src/SqlLab/components/TableExploreTree/TableExploreTree.test.tsx
index 2a938c411cda..cf087028aece 100644
--- a/superset-frontend/src/SqlLab/components/TableExploreTree/TableExploreTree.test.tsx
+++ b/superset-frontend/src/SqlLab/components/TableExploreTree/TableExploreTree.test.tsx
@@ -477,3 +477,66 @@ test.each([undefined, 'active-tab-view'])(
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 0205003faa5d..51a4dfcfcdc9 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, type TableReference } from './types';
+import { type TreeNodeData, type TableReference, getTableKey } from './types';
const StyledColumnNode = styled.div`
& > .ant-flex {
@@ -91,7 +91,11 @@ 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;
@@ -345,7 +349,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 selectStar = selectStarMap[tableKey];
return (
@@ -369,7 +373,9 @@ const TreeNodeRenderer: React.FC = ({
`}
/>
}
- onClick={() => handleUnpinTable(tableName, schema)}
+ onClick={() =>
+ handleUnpinTable(tableName, schema, catalog ?? null)
+ }
/>
)}
@@ -430,7 +436,7 @@ const TreeNodeRenderer: React.FC = ({
}
onClick={() =>
isPinned
- ? handleUnpinTable(tableName, schema)
+ ? handleUnpinTable(tableName, schema, catalog ?? null)
: handlePinTable(tableName, schema, catalog ?? null)
}
/>
diff --git a/superset-frontend/src/SqlLab/components/TableExploreTree/index.tsx b/superset-frontend/src/SqlLab/components/TableExploreTree/index.tsx
index 188f18cba6bb..906ee90e31ec 100644
--- a/superset-frontend/src/SqlLab/components/TableExploreTree/index.tsx
+++ b/superset-frontend/src/SqlLab/components/TableExploreTree/index.tsx
@@ -53,7 +53,7 @@ import {
import PanelToolbar from 'src/components/PanelToolbar';
import TreeNodeRenderer from './TreeNodeRenderer';
import useTreeData, { EMPTY_NODE_ID_PREFIX } from './useTreeData';
-import { type TreeNodeData, type TableReference } from './types';
+import { type TreeNodeData, type TableReference, getTableKey } from './types';
import type { TableMetaData } from 'src/hooks/apiResources';
import { ErrorMessageWithStackTrace } from 'src/components';
@@ -65,7 +65,11 @@ export interface TableBrowserProps {
pinnedTables?: Record;
pinnedTableKeys?: Set;
onPinTable?: (table: string, schema: string, catalog: string | null) => void;
- onUnpinTable?: (table: string, schema: string) => void;
+ onUnpinTable?: (
+ table: string,
+ schema: string,
+ catalog: string | null,
+ ) => void;
toolbarViewId?: string;
onPreviewTable?: (table: TableReference) => void;
}
@@ -594,10 +598,20 @@ export default function TableExploreTree({
const pinnedTables = useMemo(
() =>
Object.fromEntries(
- tables.map(({ queryEditorId, dbId, schema, name, persistData }) => [
- editorId === queryEditorId ? `${dbId}:${schema}:${name}` : '',
- persistData,
- ]),
+ tables
+ .filter(({ queryEditorId: qeId }) => editorId === qeId)
+ .map(
+ ({
+ dbId: tableDbId,
+ catalog: tableCatalog,
+ schema,
+ name,
+ persistData,
+ }) => [
+ getTableKey(tableDbId, tableCatalog, schema, name),
+ persistData,
+ ],
+ ),
),
[tables, editorId],
);
@@ -607,7 +621,9 @@ export default function TableExploreTree({
new Set(
tables
.filter(({ queryEditorId: qeId }) => editorId === qeId)
- .map(({ dbId, schema, name }) => `${dbId}:${schema}:${name}`),
+ .map(({ dbId: tableDbId, catalog: tableCatalog, schema, name }) =>
+ getTableKey(tableDbId, tableCatalog, schema, name),
+ ),
),
[tables, editorId],
);
@@ -619,11 +635,12 @@ export default function TableExploreTree({
);
const handleUnpinTable = useCallback(
- (tableName: string, schemaName: string) => {
+ (tableName: string, schemaName: string, catalogName: string | null) => {
const table = tables.find(
t =>
t.queryEditorId === editorId &&
t.dbId === dbId &&
+ (t.catalog ?? null) === catalogName &&
t.schema === schemaName &&
t.name === tableName,
);
diff --git a/superset-frontend/src/SqlLab/components/TableExploreTree/types.ts b/superset-frontend/src/SqlLab/components/TableExploreTree/types.ts
index e624a01e517d..2170bc272398 100644
--- a/superset-frontend/src/SqlLab/components/TableExploreTree/types.ts
+++ b/superset-frontend/src/SqlLab/components/TableExploreTree/types.ts
@@ -44,3 +44,16 @@ export interface TableReference {
schema: string;
table_name: string;
}
+
+export const getSchemaKey = (
+ dbId: number | string | undefined,
+ catalog: string | null | undefined,
+ schema: string,
+): string => `${dbId}:${catalog ?? ''}:${schema}`;
+
+export const getTableKey = (
+ dbId: number | string | undefined,
+ catalog: string | null | undefined,
+ schema: string,
+ tableName: string,
+): string => `${getSchemaKey(dbId, catalog, schema)}:${tableName}`;
diff --git a/superset-frontend/src/SqlLab/components/TableExploreTree/useTreeData.ts b/superset-frontend/src/SqlLab/components/TableExploreTree/useTreeData.ts
index e643a8f3338a..ec5ba3e5cd21 100644
--- a/superset-frontend/src/SqlLab/components/TableExploreTree/useTreeData.ts
+++ b/superset-frontend/src/SqlLab/components/TableExploreTree/useTreeData.ts
@@ -29,7 +29,7 @@ import {
useLazyTableExtendedMetadataQuery,
} from 'src/hooks/apiResources';
import { addDangerToast } from 'src/components/MessageToasts/actions';
-import type { TreeNodeData } from './types';
+import { getSchemaKey, getTableKey, type TreeNodeData } from './types';
import { ClientErrorObject, SupersetError } from '@superset-ui/core';
export const EMPTY_NODE_ID_PREFIX = 'empty:';
@@ -237,7 +237,7 @@ const useTreeData = ({
const parts = id.split(':');
const [, databaseId, schema, table] = parts;
const parsedDbId = Number(databaseId);
- const tableKey = `${parsedDbId}:${schema}:${table}`;
+ const tableKey = getTableKey(parsedDbId, catalog, schema, table);
dispatch({ type: 'SET_LOADING_NODE', nodeId: id, loading: true });
@@ -296,7 +296,7 @@ const useTreeData = ({
const parsedDbId = Number(databaseId);
if (identifier === 'schema') {
- const schemaKey = `${parsedDbId}:${schema}`;
+ const schemaKey = getSchemaKey(parsedDbId, catalog, schema);
if (!tableData?.[schemaKey]) {
dispatch({ type: 'SET_LOADING_NODE', nodeId: id, loading: true });
@@ -333,7 +333,7 @@ const useTreeData = ({
}
if (identifier === 'table') {
- const tableKey = `${parsedDbId}:${schema}:${table}`;
+ const tableKey = getTableKey(parsedDbId, catalog, schema, table);
// Check pinnedTables first (it's stable)
if (pinnedTables[tableKey]) return;
@@ -364,7 +364,7 @@ const useTreeData = ({
catalog: string | null | undefined;
schema: string;
}) => {
- const schemaKey = `${refreshDbId}:${schema}`;
+ const schemaKey = getSchemaKey(refreshDbId, refreshCatalog, schema);
const nodeId = `schema:${refreshDbId}:${schema}`;
dispatch({ type: 'SET_LOADING_NODE', nodeId, loading: true });
@@ -412,7 +412,7 @@ const useTreeData = ({
? [{ value: '', label: t('Tables') }]
: schemaOptions;
const data = schemas?.map(schema => {
- const schemaKey = `${dbId}:${schema.value}`;
+ const schemaKey = getSchemaKey(dbId, catalog, schema.value);
const schemaId = `schema:${dbId}:${schema.value}`;
const tablesData = tableData?.[schemaKey];
const tables = tablesData?.options;
@@ -425,7 +425,7 @@ const useTreeData = ({
} else if (tables && tables.length > 0) {
// Has tables
schemaChildren = tables.map(({ value: tableName, type: tableType }) => {
- const tableKey = `${dbId}:${schema.value}:${tableName}`;
+ const tableKey = getTableKey(dbId, catalog, schema.value, tableName);
const tableId = `table:${dbId}:${schema.value}:${tableName}`;
const columnsData =
tableSchemaData[tableKey] ?? pinnedTables[tableKey];
@@ -476,6 +476,7 @@ const useTreeData = ({
return data ?? [];
}, [
+ catalog,
dbId,
schemaOptions,
supportsSchemas,
diff --git a/superset-frontend/src/components/DatabaseSelector/index.tsx b/superset-frontend/src/components/DatabaseSelector/index.tsx
index 269ca0ac4032..2c2924aa4ef3 100644
--- a/superset-frontend/src/components/DatabaseSelector/index.tsx
+++ b/superset-frontend/src/components/DatabaseSelector/index.tsx
@@ -200,6 +200,7 @@ export function DatabaseSelector({
filterBySqlLab = false,
showSchema = true,
onOpenModal,
+ onLoadingChange,
}: DatabaseSelectorProps) {
const showCatalogSelector = !!db?.allow_multi_catalog;
const [currentDb, setCurrentDb] = useState();
@@ -416,6 +417,19 @@ export function DatabaseSelector({
: currentCatalog;
const sqlLabCompactMode = sqlLabMode && compactMode;
+ useEffect(() => {
+ onLoadingChange?.(
+ (showCatalogSelector && loadingCatalogs) ||
+ (showSchemaSelector && loadingSchemas),
+ );
+ }, [
+ onLoadingChange,
+ showCatalogSelector,
+ showSchemaSelector,
+ loadingCatalogs,
+ loadingSchemas,
+ ]);
+
function changeDatabase(
value: { label: string; value: number },
database: DatabaseValue,
@@ -662,12 +676,14 @@ export function DatabaseSelectorPopover({
const [draftDb, setDraftDb] = useState();
const [draftCatalog, setDraftCatalog] = useState();
const [draftSchema, setDraftSchema] = useState();
+ const [loading, setLoading] = useState(false);
const openSelector = () => {
setSelectionSession(session => session + 1);
setDraftDb(db ?? undefined);
setDraftCatalog(catalog ?? undefined);
setDraftSchema(schema);
+ setLoading(false);
setOpen(true);
};
@@ -725,6 +741,7 @@ export function DatabaseSelectorPopover({
setDraftSchema(undefined);
}}
onSchemaChange={setDraftSchema}
+ onLoadingChange={setLoading}
/>