The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Library in Data Reference (#76917)
Nick Fitzpatrickc2decd2881da
diff --git a/e2e/test/scenarios/native/native.cy.spec.js b/e2e/test/scenarios/native/native.cy.spec.jsindex 2eb8fd33787..8088ca0e6ba 100644--- a/e2e/test/scenarios/native/native.cy.spec.js+++ b/e2e/test/scenarios/native/native.cy.spec.js@@ -7,7 +7,7 @@ import {import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";import { THIRD_COLLECTION_ID } from "e2e/support/cypress_sample_instance_data";-const { ORDERS_ID, ORDERS } = SAMPLE_DATABASE;+const { ORDERS_ID, PRODUCTS_ID, ORDERS } = SAMPLE_DATABASE;const ORDERS_SCALAR_METRIC = {name: "Count of orders",@@ -665,6 +665,48 @@ describe("scenarios > native question > data reference sidebar", () => {});});+ it("should show library tables grouped by the query's database and regroup them when the database changes", function () {+ const SECOND_DB_NAME = "Second database";++ H.activateToken("pro-self-hosted");+ H.addSqliteDatabase(SECOND_DB_NAME);+ H.createLibrary();++ cy.log("publish a table in each of two databases");+ H.publishTables({ table_ids: [ORDERS_ID, PRODUCTS_ID] });++ H.startNewNativeQuestion({ database: SAMPLE_DB_ID });++ cy.log("open the Library pane from the data reference main pane");+ dataReferenceSidebar().within(() => {+ sidebarHeaderTitle().findByText("Sample Database").click();+ cy.findByText("Library").click();+ });++ cy.log("the query's tables are grouped apart from the other database's");+ dataReferenceSidebar().within(() => {+ cy.findByText("In this database").should("be.visible");+ cy.findByText("Orders").should("be.visible");+ cy.findByText("Products").should("be.visible");++ cy.findByText("In other databases").should("not.exist");+ });++ cy.log("switching the query database regroups the tables");+ cy.findByTestId("gui-builder-data").click();+ H.popover().findByText(SECOND_DB_NAME).click();++ dataReferenceSidebar().within(() => {+ cy.findByText("In this database").should("exist");+ cy.findByText("No tables").should("exist");++ cy.findByText("In other databases").should("be.visible");+ cy.findByText("Orders").should("be.visible");+ cy.findByText("Products").should("be.visible");+ cy.findAllByText("Sample Database").should("have.length", 2);+ });+ });+it("should show models", () => {H.createNativeQuestion({diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/DataReferenceLibraryPane.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/DataReferenceLibraryPane.tsxnew file mode 100644index 00000000000..31587b676d3--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/DataReferenceLibraryPane.tsx@@ -0,0 +1,201 @@+import { useMemo } from "react";+import { t } from "ttag";++import { skipToken, useSearchQuery } from "metabase/api";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { SidebarContent } from "metabase/common/components/SidebarContent";+import CS from "metabase/css/core/index.css";+import {+ NodeListContainer,+ NodeListItemIcon,+ NodeListItemLink,+ NodeListTitle,+ NodeListTitleText,+} from "metabase/querying/components/DataReference/NodeList";+import type {+ DataReferenceLibraryItem,+ DataReferencePaneProps,+ OnItemClick,+} from "metabase/querying/components/DataReference/types";+import { Box, Ellipsified, Text } from "metabase/ui";+import { type SearchResult, isConcreteTableId } from "metabase-types/api";++import { useGetLibraryCollection } from "./utils";++type DataReferenceLibraryPaneProps =+ DataReferencePaneProps<DataReferenceLibraryItem>;++const byName = (a: SearchResult, b: SearchResult) =>+ a.name.localeCompare(b.name);++export const DataReferenceLibraryPane = ({+ onBack,+ onClose,+ onItemClick,+ queryDatabaseId,+}: DataReferenceLibraryPaneProps) => {+ const {+ data: libraryCollection,+ isLoading: isLoadingCollection,+ error: libraryCollectionError,+ } = useGetLibraryCollection();++ const {+ data: searchResponse,+ isLoading: isLoadingSearch,+ error: searchError,+ } = useSearchQuery(+ libraryCollection+ ? {+ collection: libraryCollection.id,+ models: ["table"],+ context: "library",+ }+ : skipToken,+ );++ const isLoading = isLoadingCollection || isLoadingSearch;+ const error = libraryCollectionError || searchError;++ const { targetTables, otherTables } = useMemo(() => {+ const tables = (searchResponse?.data ?? []).filter(+ (result) => result.model === "table",+ );+ const targetTables = tables+ .filter((table) => table.database_id === queryDatabaseId)+ .sort(byName);+ const otherTables = tables+ .filter((table) => table.database_id !== queryDatabaseId)+ .sort(byName);+ return { targetTables, otherTables };+ }, [searchResponse, queryDatabaseId]);++ const hasTables = targetTables.length > 0 || otherTables.length > 0;+ const hasTarget = queryDatabaseId != null;++ return (+ <LoadingAndErrorWrapper+ loading={isLoading}+ error={error}+ className={CS.fullHeight}+ >+ <SidebarContent+ title={t`Library`}+ icon="repository"+ onBack={onBack}+ onClose={onClose}+ >+ <SidebarContent.Pane>+ {hasTables ? (+ <NodeListContainer>+ {hasTarget && (+ <LibraryTableList+ title={t`In this database`}+ tables={targetTables}+ onItemClick={onItemClick}+ emptyMessage={t`No tables`}+ data-testid="library-tables-current-database"+ />+ )}+ {otherTables.length > 0 && (+ <LibraryTableList+ title={hasTarget ? t`In other databases` : t`Tables`}+ tables={otherTables}+ onItemClick={onItemClick}+ showDatabaseName={hasTarget}+ mt={hasTarget ? 16 : undefined}+ data-testid={+ hasTarget+ ? "library-tables-other-databases"+ : "library-tables"+ }+ />+ )}+ </NodeListContainer>+ ) : (+ <Box ta="center" py="lg" px="md">+ <Text c="text-secondary">+ {t`No published tables in your library yet.`}+ </Text>+ </Box>+ )}+ </SidebarContent.Pane>+ </SidebarContent>+ </LoadingAndErrorWrapper>+ );+};++type LibraryTableListProps = {+ title: string;+ tables: SearchResult[];+ onItemClick: OnItemClick;+ showDatabaseName?: boolean;+ emptyMessage?: string;+ mt?: number;+ "data-testid"?: string;+};++const LibraryTableList = ({+ title,+ tables,+ onItemClick,+ showDatabaseName,+ emptyMessage,+ mt,+ "data-testid": dataTestId,+}: LibraryTableListProps) => {+ if (tables.length === 0 && !emptyMessage) {+ return null;+ }++ return (+ <li data-testid={dataTestId}>+ <NodeListTitle mt={mt}>+ <NodeListTitleText ml={undefined}>{title}</NodeListTitleText>+ </NodeListTitle>+ {tables.length > 0 ? (+ <ul>+ {tables.map((table) => {+ const isSyncing = table.initial_sync_status !== "complete";+ return (+ <li key={table.id}>+ <NodeListItemLink+ disabled={isSyncing}+ onClick={() => {+ if (isConcreteTableId(table.id)) {+ onItemClick({ type: "table", id: table.id });+ }+ }}+ >+ <NodeListItemIcon+ disabled={isSyncing}+ name="table"+ style={{ flexShrink: 0 }}+ />+ <Ellipsified fw={700} ml="sm">+ {table.name}+ </Ellipsified>+ {showDatabaseName && table.database_name && (+ <Ellipsified+ c="text-secondary"+ fw="normal"+ fz="sm"+ ml="sm"+ flex={"1 0 30%"}+ >+ {table.database_name}+ </Ellipsified>+ )}+ </NodeListItemLink>+ </li>+ );+ })}+ </ul>+ ) : (+ <Text c="text-secondary" px="sm" pb="sm">+ {emptyMessage}+ </Text>+ )}+ </li>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/DataReferenceLibraryPane.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/DataReferenceLibraryPane.unit.spec.tsxnew file mode 100644index 00000000000..198fb21875f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/DataReferenceLibraryPane.unit.spec.tsx@@ -0,0 +1,235 @@+import userEvent from "@testing-library/user-event";++import {+ setupLibraryEndpoints,+ setupSearchEndpoints,+} from "__support__/server-mocks";+import {+ renderWithProviders,+ screen,+ waitForLoaderToBeRemoved,+ within,+} from "__support__/ui";+import type { DatabaseId, SearchResult } from "metabase-types/api";+import { createMockSearchResult } from "metabase-types/api/mocks";++import { DataReferenceLibraryPane } from "./DataReferenceLibraryPane";++const TARGET_DB_ID = 1;++const libraryTable = (overrides: Partial<SearchResult>): SearchResult =>+ createMockSearchResult({+ model: "table",+ initial_sync_status: "complete",+ ...overrides,+ });++type SetupOpts = {+ tables?: SearchResult[];+ queryDatabaseId?: DatabaseId;+};++const setup = (opts: SetupOpts = {}) => {+ const { tables = [] } = opts;+ const queryDatabaseId =+ "queryDatabaseId" in opts ? opts.queryDatabaseId : TARGET_DB_ID;+ const onItemClick = jest.fn();+ const onBack = jest.fn();+ const onClose = jest.fn();++ setupLibraryEndpoints(true);+ setupSearchEndpoints(tables);++ renderWithProviders(+ <DataReferenceLibraryPane+ type="library"+ onBack={onBack}+ onClose={onClose}+ onItemClick={onItemClick}+ queryDatabaseId={queryDatabaseId}+ />,+ );++ return { onItemClick, onBack, onClose };+};++describe("DataReferenceLibraryPane", () => {+ it("separates the query database's tables from the tables in other databases", async () => {+ setup({+ tables: [+ libraryTable({ id: 1, name: "Zebra", database_id: TARGET_DB_ID }),+ libraryTable({ id: 2, name: "Apple", database_id: TARGET_DB_ID }),+ libraryTable({ id: 3, name: "Mango", database_id: 2 }),+ libraryTable({ id: 4, name: "Banana", database_id: 3 }),+ ],+ });+ await waitForLoaderToBeRemoved();++ const currentDatabase = within(+ screen.getByTestId("library-tables-current-database"),+ );+ expect(currentDatabase.getByText("Apple")).toBeInTheDocument();+ expect(currentDatabase.getByText("Zebra")).toBeInTheDocument();+ expect(currentDatabase.getAllByRole("listitem")).toHaveLength(2);++ const otherDatabases = within(+ screen.getByTestId("library-tables-other-databases"),+ );+ expect(otherDatabases.getByText("Banana")).toBeInTheDocument();+ expect(otherDatabases.getByText("Mango")).toBeInTheDocument();+ expect(otherDatabases.getAllByRole("listitem")).toHaveLength(2);+ });++ it("shows a 'No tables' message in this database when only other databases have tables", async () => {+ setup({+ tables: [+ libraryTable({ id: 1, name: "Mango", database_id: 2 }),+ libraryTable({ id: 2, name: "Banana", database_id: 3 }),+ ],+ });+ await waitForLoaderToBeRemoved();++ // "In this database" is always shown, with a "No tables" message+ const currentDatabase = within(+ screen.getByTestId("library-tables-current-database"),+ );+ expect(screen.getByText("In this database")).toBeInTheDocument();+ expect(currentDatabase.getByText("No tables")).toBeInTheDocument();+ expect(currentDatabase.queryAllByRole("listitem")).toHaveLength(0);++ // "In other databases" is shown because those databases have tables+ const otherDatabases = within(+ screen.getByTestId("library-tables-other-databases"),+ );+ expect(screen.getByText("In other databases")).toBeInTheDocument();+ expect(otherDatabases.getByText("Mango")).toBeInTheDocument();+ expect(otherDatabases.getByText("Banana")).toBeInTheDocument();+ });++ it("hides 'In other databases' but still shows this database's tables when other databases have none", async () => {+ setup({+ tables: [+ libraryTable({ id: 1, name: "Orders", database_id: TARGET_DB_ID }),+ ],+ });+ await waitForLoaderToBeRemoved();++ expect(screen.queryByText("In other databases")).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("library-tables-other-databases"),+ ).not.toBeInTheDocument();++ const currentDatabase = within(+ screen.getByTestId("library-tables-current-database"),+ );+ expect(screen.getByText("In this database")).toBeInTheDocument();+ expect(currentDatabase.getByText("Orders")).toBeInTheDocument();+ // No empty message when there are tables to show+ expect(currentDatabase.queryByText("No tables")).not.toBeInTheDocument();+ });++ it("shows the database name only for tables in other databases", async () => {+ setup({+ tables: [+ libraryTable({+ id: 1,+ name: "Local table",+ database_id: TARGET_DB_ID,+ database_name: "Analytics DB",+ }),+ libraryTable({+ id: 2,+ name: "Remote table",+ database_id: 2,+ database_name: "Sales DB",+ }),+ ],+ });+ await waitForLoaderToBeRemoved();++ const currentDatabase = within(+ screen.getByTestId("library-tables-current-database"),+ );+ expect(currentDatabase.getByText("Local table")).toBeInTheDocument();+ // The current database's own name is not repeated on its tables+ expect(currentDatabase.queryByText("Analytics DB")).not.toBeInTheDocument();++ const otherDatabases = within(+ screen.getByTestId("library-tables-other-databases"),+ );+ expect(otherDatabases.getByText("Remote table")).toBeInTheDocument();+ expect(otherDatabases.getByText("Sales DB")).toBeInTheDocument();+ });++ it("renders a single 'Tables' list with no database names when there is no query database", async () => {+ setup({+ queryDatabaseId: undefined,+ tables: [+ libraryTable({+ id: 1,+ name: "Apple",+ database_id: 2,+ database_name: "Sales DB",+ }),+ libraryTable({+ id: 2,+ name: "Banana",+ database_id: 3,+ database_name: "Marketing DB",+ }),+ ],+ });+ await waitForLoaderToBeRemoved();++ expect(screen.getByText("Tables")).toBeInTheDocument();+ expect(+ screen.queryByTestId("library-tables-current-database"),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("library-tables-other-databases"),+ ).not.toBeInTheDocument();++ const tables = within(screen.getByTestId("library-tables"));+ expect(tables.getByText("Apple")).toBeInTheDocument();+ expect(tables.getByText("Banana")).toBeInTheDocument();+ expect(tables.getAllByRole("listitem")).toHaveLength(2);+ // Database names are not shown when there is no split+ expect(tables.queryByText("Sales DB")).not.toBeInTheDocument();+ });++ it("calls onItemClick with the table when a table is clicked", async () => {+ const { onItemClick } = setup({+ tables: [+ libraryTable({ id: 42, name: "Orders", database_id: TARGET_DB_ID }),+ ],+ });+ await waitForLoaderToBeRemoved();++ await userEvent.click(screen.getByText("Orders"));++ expect(onItemClick).toHaveBeenCalledWith({ type: "table", id: 42 });+ });++ it("shows an empty state when the library has no published tables", async () => {+ setup({ tables: [] });+ await waitForLoaderToBeRemoved();++ expect(+ screen.getByText("No published tables in your library yet."),+ ).toBeInTheDocument();+ expect(screen.queryByText("In this database")).not.toBeInTheDocument();+ });++ it("calls onClose when the close button is clicked", async () => {+ const { onClose } = setup({+ tables: [+ libraryTable({ id: 1, name: "Orders", database_id: TARGET_DB_ID }),+ ],+ });+ await waitForLoaderToBeRemoved();++ await userEvent.click(screen.getByLabelText("close icon"));++ expect(onClose).toHaveBeenCalled();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/index.tsindex 13648f83b82..28995ee1439 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/index.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/index.ts@@ -2,6 +2,7 @@ import { PLUGIN_LIBRARY } from "metabase/plugins";import { useGetLibraryCollectionQuery } from "metabase-enterprise/api";import { hasPremiumFeature } from "metabase-enterprise/settings";+import { DataReferenceLibraryPane } from "./DataReferenceLibraryPane";import { CollectionPermissionsModal } from "./components/CollectionPermissionsModal";import { CreateLibraryModal } from "./components/CreateLibraryModal";import { PublishTablesModal } from "./components/PublishTablesModal";@@ -31,6 +32,7 @@ export function initializePlugin() {PLUGIN_LIBRARY.getCollectionPickerItems = getCollectionPickerItems;PLUGIN_LIBRARY.getEntityPickerSyntheticLibraryItem =getEntityPickerSyntheticLibraryItem;+ PLUGIN_LIBRARY.DataReferenceLibraryPane = DataReferenceLibraryPane;PLUGIN_LIBRARY.CreateLibraryModal = CreateLibraryModal;PLUGIN_LIBRARY.CollectionPermissionsModal = CollectionPermissionsModal;PLUGIN_LIBRARY.PublishTablesModal = PublishTablesModal;diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.tsindex 087b20fe959..b240a05da24 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.ts@@ -22,10 +22,11 @@ const isLibrary = (export const useGetLibraryCollection = ({skip = false,}: { skip?: boolean } = {}) => {- const { data, isLoading: isLoadingCollection } = useGetLibraryCollectionQuery(- undefined,- { skip },- );+ const {+ data,+ isLoading: isLoadingCollection,+ error,+ } = useGetLibraryCollectionQuery(undefined, { skip });const maybeLibrary = useMemo(() => (isLibrary(data) ? data : undefined),@@ -35,6 +36,7 @@ export const useGetLibraryCollection = ({return {isLoading: isLoadingCollection,data: maybeLibrary,+ error,};};export const useGetLibraryChildCollectionByType = ({diff --git a/frontend/src/metabase/plugins/oss/library.ts b/frontend/src/metabase/plugins/oss/library.tsindex c4081a617e7..b8aaa815755 100644--- a/frontend/src/metabase/plugins/oss/library.ts+++ b/frontend/src/metabase/plugins/oss/library.ts@@ -9,6 +9,10 @@ import type {} from "metabase/common/components/Pickers/EntityPicker/types";import type { MiniPickerCollectionFolderItem } from "metabase/common/components/Pickers/MiniPicker/types";import { PluginPlaceholder } from "metabase/plugins/components/PluginPlaceholder";+import type {+ DataReferenceLibraryItem,+ DataReferencePaneProps,+} from "metabase/querying/components/DataReference/types";import type {Collection,CollectionId,@@ -104,6 +108,9 @@ type LibraryPlugin = {items: CollectionItem[];}) => OmniPickerItem[] | undefined;getEntityPickerSyntheticLibraryItem: GetEntityPickerSyntheticLibraryItemFunction;+ DataReferenceLibraryPane: ComponentType<+ DataReferencePaneProps<DataReferenceLibraryItem>+ >;CreateLibraryModal: ComponentType<CreateLibraryModalProps>;CollectionPermissionsModal: ComponentType<CollectionPermissionsModalProps>;PublishTablesModal: ComponentType<PublishTablesModalProps>;@@ -138,6 +145,9 @@ const getDefaultPluginLibrary = (): LibraryPlugin => ({}),getCollectionPickerItems: () => undefined,getEntityPickerSyntheticLibraryItem: () => undefined,+ DataReferenceLibraryPane: PluginPlaceholder<+ DataReferencePaneProps<DataReferenceLibraryItem>+ >,CreateLibraryModal:// Unjustified type cast. FIXMEPluginPlaceholder as ComponentType<CreateLibraryModalProps>,diff --git a/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetEditorInner.tsx b/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetEditorInner.tsxindex 67bea2314d8..fa72636ff4a 100644--- a/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetEditorInner.tsx+++ b/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetEditorInner.tsx@@ -259,7 +259,13 @@ function getSidebar();}if (isShowingDataReference) {- return <DataReference {...props} onClose={toggleDataReference} />;+ return (+ <DataReference+ {...props}+ databaseId={question.databaseId() ?? undefined}+ onClose={toggleDataReference}+ />+ );}if (isShowingSnippetSidebar) {return <SnippetSidebar {...props} onClose={toggleSnippetSidebar} />;diff --git a/frontend/src/metabase/query_builder/components/view/View/NativeQueryRightSidebar/NativeQueryRightSidebar.tsx b/frontend/src/metabase/query_builder/components/view/View/NativeQueryRightSidebar/NativeQueryRightSidebar.tsxindex 34898fcf708..e1da0f098ed 100644--- a/frontend/src/metabase/query_builder/components/view/View/NativeQueryRightSidebar/NativeQueryRightSidebar.tsx+++ b/frontend/src/metabase/query_builder/components/view/View/NativeQueryRightSidebar/NativeQueryRightSidebar.tsx@@ -121,7 +121,11 @@ export const NativeQueryRightSidebar = () : null;}).with({ isShowingDataReference: true }, () => (- <DataReference {...props} onClose={toggleDataReference} />+ <DataReference+ {...props}+ databaseId={question.databaseId() ?? undefined}+ onClose={toggleDataReference}+ />)).with({ isShowingSnippetSidebar: true }, () => (<SnippetSidebar {...props} onClose={toggleSnippetSidebar} />diff --git a/frontend/src/metabase/querying/components/DataReference/DataReference.tsx b/frontend/src/metabase/querying/components/DataReference/DataReference.tsxindex 024286d3d9b..a31831f8711 100644--- a/frontend/src/metabase/querying/components/DataReference/DataReference.tsx+++ b/frontend/src/metabase/querying/components/DataReference/DataReference.tsx@@ -1,5 +1,8 @@import type { ComponentType } from "react";+import { PLUGIN_LIBRARY } from "metabase/plugins";+import type { DatabaseId } from "metabase-types/api";+import { MainPane } from "./MainPane";import {type DataReferenceItem,@@ -13,15 +16,29 @@ export const DataReference = ({pushDataReferenceStack,onClose,onBack,+ databaseId,}: {dataReferenceStack: DataReferenceItem[];popDataReferenceStack: () => void;pushDataReferenceStack: (item: DataReferenceItem) => void;onClose?: () => void;onBack?: () => void;+ databaseId?: DatabaseId;}) => {if (dataReferenceStack.length) {const page = dataReferenceStack[dataReferenceStack.length - 1];++ if (page.type === "library") {+ return (+ <PLUGIN_LIBRARY.DataReferenceLibraryPane+ {...page}+ onItemClick={pushDataReferenceStack}+ onClose={onClose}+ onBack={popDataReferenceStack}+ queryDatabaseId={databaseId}+ />+ );+ }// Unjustified type cast. FIXMEconst Pane = PANES[page.type] as ComponentType<DataReferencePaneProps<typeof page>@@ -32,6 +49,7 @@ export const DataReference = ({onItemClick={pushDataReferenceStack}onClose={onClose}onBack={popDataReferenceStack}+ queryDatabaseId={databaseId}/>);} else {diff --git a/frontend/src/metabase/querying/components/DataReference/MainPane.tsx b/frontend/src/metabase/querying/components/DataReference/MainPane.tsxindex 635d0db04a7..775a6a56522 100644--- a/frontend/src/metabase/querying/components/DataReference/MainPane.tsx+++ b/frontend/src/metabase/querying/components/DataReference/MainPane.tsx@@ -5,6 +5,7 @@ import { useListDatabasesQuery } from "metabase/api";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import { SidebarContent } from "metabase/common/components/SidebarContent";import CS from "metabase/css/core/index.css";+import { PLUGIN_LIBRARY } from "metabase/plugins";import {NodeListItemIcon,@@ -18,7 +19,15 @@ export const MainPane = ({onItemClick,onBack,}: DataReferencePaneProps) => {- const { data, isLoading, error } = useListDatabasesQuery();+ const {+ data: databases,+ isLoading: isLoadingDatabases,+ error,+ } = useListDatabasesQuery();+ const { data: libraryCollection, isLoading: isLoadingLibraryCollection } =+ PLUGIN_LIBRARY.useGetLibraryCollection();++ const isLoading = isLoadingDatabases || isLoadingLibraryCollection;if (isLoading || error) {return <LoadingAndErrorWrapper loading={isLoading} error={error} />;@@ -31,7 +40,17 @@ export const MainPane = ({{t`Browse the contents of your databases, tables, and columns. Pick a database to get started.`}</p><ul>- {data?.data?.map((database) => (+ {PLUGIN_LIBRARY.isEnabled && libraryCollection && (+ <li>+ <NodeListItemLink+ onClick={() => onItemClick({ type: "library" })}+ >+ <NodeListItemIcon name="repository" />+ <NodeListItemName>{t`Library`}</NodeListItemName>+ </NodeListItemLink>+ </li>+ )}+ {databases?.data?.map((database) => (<li key={database.id}><NodeListItemLinkonClick={() =>diff --git a/frontend/src/metabase/querying/components/DataReference/MainPane.unit.spec.tsx b/frontend/src/metabase/querying/components/DataReference/MainPane.unit.spec.tsxnew file mode 100644index 00000000000..13a45d4035d--- /dev/null+++ b/frontend/src/metabase/querying/components/DataReference/MainPane.unit.spec.tsx@@ -0,0 +1,78 @@+import userEvent from "@testing-library/user-event";++import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";+import {+ setupDatabasesEndpoints,+ setupLibraryEndpoints,+} from "__support__/server-mocks";+import { mockSettings } from "__support__/settings";+import { renderWithProviders, screen } from "__support__/ui";+import { reinitialize } from "metabase/plugins";+import { createMockState } from "metabase/redux/store/mocks/state";+import {+ createMockDatabase,+ createMockTokenFeatures,+} from "metabase-types/api/mocks";++import { MainPane } from "./MainPane";++const databases = [createMockDatabase({ id: 1, name: "Sample Database" })];++const setup = ({+ hasLibrary = false,+ hasLibraryCollection = true,+}: { hasLibrary?: boolean; hasLibraryCollection?: boolean } = {}) => {+ const onItemClick = jest.fn();++ setupDatabasesEndpoints(databases, { hasSavedQuestions: false });++ const state = createMockState({+ settings: mockSettings({+ "token-features": createMockTokenFeatures({ library: hasLibrary }),+ }),+ });++ if (hasLibrary) {+ setupEnterpriseOnlyPlugin("library");+ setupLibraryEndpoints(hasLibraryCollection);+ }++ renderWithProviders(+ <MainPane+ onItemClick={onItemClick}+ onClose={jest.fn()}+ onBack={jest.fn()}+ />,+ { storeInitialState: state },+ );++ return { onItemClick };+};++describe("MainPane", () => {+ afterEach(() => {+ reinitialize();+ });++ it("does not render a Library option when the library feature is disabled", async () => {+ setup({ hasLibrary: false });++ expect(await screen.findByText("Sample Database")).toBeInTheDocument();+ expect(screen.queryByText("Library")).not.toBeInTheDocument();+ });++ it("does not render a Library option when the feature is enabled but no library has been created", async () => {+ setup({ hasLibrary: true, hasLibraryCollection: false });++ expect(await screen.findByText("Sample Database")).toBeInTheDocument();+ expect(screen.queryByText("Library")).not.toBeInTheDocument();+ });++ it("renders a Library option that opens the library pane when the feature is enabled", async () => {+ const { onItemClick } = setup({ hasLibrary: true });++ await userEvent.click(await screen.findByText("Library"));++ expect(onItemClick).toHaveBeenCalledWith({ type: "library" });+ });+});diff --git a/frontend/src/metabase/querying/components/DataReference/types.ts b/frontend/src/metabase/querying/components/DataReference/types.tsindex 53a34a1853f..6fed2d111d7 100644--- a/frontend/src/metabase/querying/components/DataReference/types.ts+++ b/frontend/src/metabase/querying/components/DataReference/types.ts@@ -13,6 +13,8 @@ import { QuestionPane } from "./QuestionPane";import { SchemaPane } from "./SchemaPane";import { TablePane } from "./TablePane";+// The library pane is rendered from PLUGIN_LIBRARY.DataReferenceLibraryPane+// (see DataReference), so it is intentionally absent from PANES.export const PANES = {database: DatabasePane, // lists schemas, tables and models of a databaseschema: SchemaPane, // lists tables of a schema@@ -26,10 +28,14 @@ export type DataReferencePaneProps<TItem = unknown> = {onClose?: () => void;onBack?: () => void;onItemClick: OnItemClick;+ // The database the current query targets, used by the Library pane to list+ // its tables first. Not part of the navigation stack.+ queryDatabaseId?: DatabaseId;} & TItem;export type DataReferenceItem =| DataReferenceDatabaseItem+ | DataReferenceLibraryItem| DataReferenceSchemaItem| DataReferenceTableItem| DataReferenceQuestionItem@@ -40,6 +46,10 @@ export type DataReferenceDatabaseItem = {id: DatabaseId;};+export type DataReferenceLibraryItem = {+ type: "library";+};+export type DataReferenceSchemaItem = {type: "schema";schemaName: SchemaName;diff --git a/frontend/src/metabase/querying/editor/components/QueryEditor/NativeQuerySidebar/NativeQuerySidebar.tsx b/frontend/src/metabase/querying/editor/components/QueryEditor/NativeQuerySidebar/NativeQuerySidebar.tsxindex d530bb50972..3d70b1d44bd 100644--- a/frontend/src/metabase/querying/editor/components/QueryEditor/NativeQuerySidebar/NativeQuerySidebar.tsx+++ b/frontend/src/metabase/querying/editor/components/QueryEditor/NativeQuerySidebar/NativeQuerySidebar.tsx@@ -100,6 +100,7 @@ function QueryDataReferenceSidebar({popDataReferenceStack={popDataReferenceStack}pushDataReferenceStack={pushDataReferenceStack}onClose={toggleDataReference}+ databaseId={question.databaseId() ?? undefined}/>);}diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/NativeQueryModal.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/NativeQueryModal.tsxindex 418af1931c6..98684ecb6c3 100644--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/NativeQueryModal.tsx+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/NativeQueryModal.tsx@@ -438,6 +438,7 @@ export const NativeQueryModal = ({><DataReferencedataReferenceStack={dataReferenceStack}+ databaseId={modifiedQuestion.databaseId() ?? undefined}onClose={() => setIsShowingDataReference(false)}popDataReferenceStack={() => {if (dataReferenceStack.length === 1) {