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
Remove tables entity (#74575)
Romeo Van Snick6b7b4e2eedff
diff --git a/enterprise/frontend/src/embedding/data-picker/DataSelector/DataSelector.jsx b/enterprise/frontend/src/embedding/data-picker/DataSelector/DataSelector.jsxindex d0fc1c25b68..4b1b5cd861a 100644--- a/enterprise/frontend/src/embedding/data-picker/DataSelector/DataSelector.jsx+++ b/enterprise/frontend/src/embedding/data-picker/DataSelector/DataSelector.jsx@@ -15,9 +15,9 @@ import { EmptyState } from "metabase/common/components/EmptyState";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import CS from "metabase/css/core/index.css";import { Questions } from "metabase/entities/questions";-import { Tables } from "metabase/entities/tables";import { entityCompatibleQuery } from "metabase/entities/utils";import { connect } from "metabase/redux";+import { fetchTableMetadata } from "metabase/redux/tables";import { getMetadata } from "metabase/selectors/metadata";import { getSetting } from "metabase/selectors/settings";import { canUserCreateQueries } from "metabase/selectors/user";@@ -970,8 +970,7 @@ const DataSelector = _.compose(databaseApi.endpoints.listDatabases,{ forceRefetch: false },),- fetchFields: (tableId) =>- dispatch(Tables.actions.fetchMetadata({ id: tableId })),+ fetchFields: (tableId) => dispatch(fetchTableMetadata({ id: tableId })),fetchQuestion: (id) =>dispatch(Questions.actions.fetch({diff --git a/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.tsx b/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.tsxindex b2bb29bf121..5e83f57462a 100644--- a/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.tsx+++ b/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.tsx@@ -20,8 +20,10 @@ import { Radio } from "metabase/common/components/Radio";import { useToggle } from "metabase/common/hooks/use-toggle";import CS from "metabase/css/core/index.css";import { EntityName } from "metabase/entities/containers/EntityName";+import { useTranslateContent } from "metabase/i18n/hooks";import { GTAPApi } from "metabase/services";import { Button, Center, Icon, Loader } from "metabase/ui";+import { getName } from "metabase/utils/name";import type {GroupTableAccessPolicyDraft,GroupTableAccessPolicyParams,@@ -327,6 +329,7 @@ interface PolicySummaryProps {}const PolicySummary = ({ policy, policyTable }: PolicySummaryProps) => {+ const tc = useTranslateContent();const headingId = _.uniqueId();return (<div aria-labelledby={headingId}>@@ -357,9 +360,7 @@ const PolicySummary = ({ policy, policyTable }: PolicySummaryProps) => {</strong>)} question`: jt`rows in the ${(- <strong key="table-name">- <EntityName entityType="tables" entityId={policy.table_id} />- </strong>+ <strong key="table-name">{tc(getName(policyTable))}</strong>)} table`}/>diff --git a/frontend/src/metabase/admin/databases/components/DatabaseConnectionInfoSection/DatabaseConnectionInfoSection.tsx b/frontend/src/metabase/admin/databases/components/DatabaseConnectionInfoSection/DatabaseConnectionInfoSection.tsxindex 4239577a830..d930a591189 100644--- a/frontend/src/metabase/admin/databases/components/DatabaseConnectionInfoSection/DatabaseConnectionInfoSection.tsx+++ b/frontend/src/metabase/admin/databases/components/DatabaseConnectionInfoSection/DatabaseConnectionInfoSection.tsx@@ -3,13 +3,14 @@ import { push } from "react-router-redux";import { t } from "ttag";import {+ tableApi,useDismissDatabaseSyncSpinnerMutation,useRescanDatabaseFieldValuesMutation,useSyncDatabaseSchemaMutation,} from "metabase/api";+import { listTag } from "metabase/api/tags";import { ActionButton } from "metabase/common/components/ActionButton";import { isDbModifiable } from "metabase/common/utils/database";-import { Tables } from "metabase/entities/tables";import { useDispatch } from "metabase/redux";import { Button, Flex, Tooltip } from "metabase/ui";import { isSyncCompleted } from "metabase/utils/syncing";@@ -37,8 +38,8 @@ export const DatabaseConnectionInfoSection = ({const handleSyncDatabaseSchema = async () => {await syncDatabaseSchema(database.id).unwrap();- // FIXME remove when MetadataEditor uses RTK query directly to load tables- dispatch({ type: Tables.actionTypes.INVALIDATE_LISTS_ACTION });+ // refresh any table lists now that the schema may have changed+ dispatch(tableApi.util.invalidateTags([listTag("table")]));};const handleDismissSyncSpinner = useCallback(diff --git a/frontend/src/metabase/admin/datamodel/hoc/FilteredToUrlTable.tsx b/frontend/src/metabase/admin/datamodel/hoc/FilteredToUrlTable.tsxindex 4cebf80d74f..d447e6f3249 100644--- a/frontend/src/metabase/admin/datamodel/hoc/FilteredToUrlTable.tsx+++ b/frontend/src/metabase/admin/datamodel/hoc/FilteredToUrlTable.tsx@@ -4,14 +4,14 @@ import { type ComponentType, type ReactNode, useState } from "react";import { push } from "react-router-redux";import { t } from "ttag";+import { skipToken, useGetTableQuery } from "metabase/api";import { FieldSet } from "metabase/common/components/FieldSet";import CS from "metabase/css/core/index.css";-import { Tables } from "metabase/entities/tables";import { DatabaseSchemaAndTableDataSelector } from "metabase/querying/common/components/DataSelector";-import { connect } from "metabase/redux";-import type { State } from "metabase/redux/store";+import { connect, useSelector } from "metabase/redux";+import { getMetadata } from "metabase/selectors/metadata";import { Icon } from "metabase/ui";-import type { ConcreteTableId, Segment, Table } from "metabase-types/api";+import type { ConcreteTableId, Segment } from "metabase-types/api";type LocationWithQuery = Location<{table?: string;@@ -76,20 +76,17 @@ export function FilteredToUrlTable(return connect(null, { push })(Inner);}-type TableSelectorInnerProps = {- table?: Table & {- // Attributes from entity framework object wrapper- displayName(): string;- };+type TableSelectorProps = {tableId: ConcreteTableId | null;setTableId: (tableId: ConcreteTableId | null) => void;};-function TableSelectorInner({- table,- tableId,- setTableId,-}: TableSelectorInnerProps) {+function TableSelector({ tableId, setTableId }: TableSelectorProps) {+ useGetTableQuery(tableId != null ? { id: tableId } : skipToken);+ const table = useSelector((state) =>+ tableId != null ? getMetadata(state).table(tableId) : null,+ );+return (<FieldSetnoPadding@@ -129,9 +126,3 @@ function TableSelectorInner({</FieldSet>);}--const TableSelector = Tables.load({- id: (_state: State, props: { tableId: ConcreteTableId | null }) =>- props.tableId,- loadingAndErrorWrapper: false,-})(TableSelectorInner);diff --git a/frontend/src/metabase/admin/permissions/permissions.ts b/frontend/src/metabase/admin/permissions/permissions.tsindex d1fd8e25cbd..7d403cc4121 100644--- a/frontend/src/metabase/admin/permissions/permissions.ts+++ b/frontend/src/metabase/admin/permissions/permissions.ts@@ -19,9 +19,9 @@ import {updateTablesPermission,} from "metabase/admin/permissions/utils/graph";import { getGroupFocusPermissionsUrl } from "metabase/admin/permissions/utils/urls";-import { permissionApi } from "metabase/api";+import { databaseApi, permissionApi } from "metabase/api";import { type ErrorPayload, getErrorMessage } from "metabase/api/utils/errors";-import { Tables } from "metabase/entities/tables";+import { entityCompatibleQuery } from "metabase/entities/utils";import {PLUGIN_ADVANCED_PERMISSIONS,PLUGIN_DATA_PERMISSIONS,@@ -217,14 +217,20 @@ export const updateDataPermission = createThunkAction(}: UpdateDataPermissionParams) => {return (dispatch, getState): UpdateDataPermissionPayload | undefined => {if (isDatabaseEntityId(entityId)) {- dispatch(- Tables.actions.fetchList({- dbId: entityId.databaseId,+ // Fire-and-forget background refresh of the database's table metadata;+ // the reducer below reads the current snapshot synchronously. Swallow+ // rejections so a failed fetch doesn't surface as an unhandled+ // promise rejection.+ void entityCompatibleQuery(+ {+ id: entityId.databaseId,include_hidden: true,remove_inactive: true,skip_fields: true,- }),- );+ },+ dispatch,+ databaseApi.endpoints.getDatabaseMetadata,+ ).catch(() => undefined);}const metadata = getMetadataWithHiddenTables(getState());diff --git a/frontend/src/metabase/admin/permissions/selectors/data-permissions/permission-editor.tsx b/frontend/src/metabase/admin/permissions/selectors/data-permissions/permission-editor.tsxindex 4e47fe767a0..9332387825a 100644--- a/frontend/src/metabase/admin/permissions/selectors/data-permissions/permission-editor.tsx+++ b/frontend/src/metabase/admin/permissions/selectors/data-permissions/permission-editor.tsx@@ -7,9 +7,9 @@ import {getSpecialGroupType,isDefaultGroup,} from "metabase/admin/utils/groups";+import { databaseApi } from "metabase/api";import { getPlan } from "metabase/common/utils/plan";import { getIsHosted } from "metabase/databases/selectors";-import { Tables } from "metabase/entities/tables";import {PLUGIN_AUDIT,PLUGIN_FEATURE_LEVEL_PERMISSIONS,@@ -19,8 +19,14 @@ import type { State } from "metabase/redux/store";import { getMetadataWithHiddenTables } from "metabase/selectors/metadata";import { getSetting } from "metabase/selectors/settings";import { getTokenFeature } from "metabase/setup";+import { getResponseErrorMessage } from "metabase/utils/errors";import type Schema from "metabase-lib/v1/metadata/Schema";-import type { Database, Group, GroupsPermissions } from "metabase-types/api";+import type {+ Database,+ DatabaseId,+ Group,+ GroupsPermissions,+} from "metabase-types/api";import type {DataRouteParams,@@ -59,27 +65,36 @@ const getGroupHint = (groupType: SpecialGroupType): string | null => {}};+// The database's tables are loaded via getDatabaseMetadata (see DataPermissionsPage+// and updateDataPermission below); read that request's state to drive the+// editor/sidebar loading and error UI.+const selectDatabaseTablesMetadata = (state: State, databaseId: string) =>+ databaseApi.endpoints.getDatabaseMetadata.select({+ id: databaseId as unknown as DatabaseId,+ include_hidden: true,+ remove_inactive: true,+ skip_fields: true,+ })(state);+export const getIsLoadingDatabaseTables = (state: State,{ params }: { params: Pick<RawGroupRouteParams, "databaseId"> },-) =>- Tables.selectors.getLoading(state, {- entityQuery: {- dbId: params.databaseId,- include_hidden: true,- },- });+): boolean => {+ if (params.databaseId == null) {+ return false;+ }+ return selectDatabaseTablesMetadata(state, params.databaseId).isLoading;+};export const getLoadingDatabaseTablesError = (state: State,{ params }: { params: Pick<RawGroupRouteParams, "databaseId"> },-) => {- return Tables.selectors.getError(state, {- entityQuery: {- dbId: params.databaseId,- include_hidden: true,- },- });+): string | undefined => {+ if (params.databaseId == null) {+ return undefined;+ }+ const { error } = selectDatabaseTablesMetadata(state, params.databaseId);+ return error ? getResponseErrorMessage(error) : undefined;};type RouteParamsSelectorParameters = {diff --git a/frontend/src/metabase/browse/schemas/BrowseSchemas.tsx b/frontend/src/metabase/browse/schemas/BrowseSchemas.tsxindex d41e7b7ca75..c32bf11606d 100644--- a/frontend/src/metabase/browse/schemas/BrowseSchemas.tsx+++ b/frontend/src/metabase/browse/schemas/BrowseSchemas.tsx@@ -52,9 +52,7 @@ const BrowseSchemasContainer = ({<Flex maw="64rem" mx="auto" w="100%" direction="column">{schemas.length === 1 ? (<TableBrowser- schemas={schemas}params={params}- slug={slug}dbId={dbId}schemaName={schemas[0].name}// hide the schema since there's only onediff --git a/frontend/src/metabase/browse/tables/TableBrowser/TableBrowser.tsx b/frontend/src/metabase/browse/tables/TableBrowser/TableBrowser.tsxindex febb3346e6b..3138c9c1486 100644--- a/frontend/src/metabase/browse/tables/TableBrowser/TableBrowser.tsx+++ b/frontend/src/metabase/browse/tables/TableBrowser/TableBrowser.tsx@@ -1,8 +1,12 @@-import _ from "underscore";+import { useEffect, useState } from "react";-import { Tables } from "metabase/entities/tables";-import { connect } from "metabase/redux";-import type { State } from "metabase/redux/store";+import {+ skipToken,+ useGetDatabaseMetadataQuery,+ useListDatabaseSchemaTablesQuery,+} from "metabase/api";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { useSelector } from "metabase/redux";import { getMetadata } from "metabase/selectors/metadata";import { getSetting } from "metabase/selectors/settings";import * as Urls from "metabase/urls";@@ -25,8 +29,11 @@ type TableBrowserContainerProps = {dbId?: DatabaseId | string;schemaName?: string;params?: RouteParams;+ showSchemaInHeader?: boolean;};+const EMPTY_TABLES: Table[] = [];+const getDatabaseId = (props: TableBrowserContainerProps,{ includeVirtual = false }: { includeVirtual?: boolean } = {},@@ -49,31 +56,63 @@ const getDatabaseId = (const getSchemaName = (props: TableBrowserContainerProps): string | undefined =>props.schemaName || props.params?.schemaName || undefined;-const getReloadInterval = (- _state: State,- _props: TableBrowserContainerProps,- tables: Table[] = [],-): number => (tables.some((t) => isSyncInProgress(t)) ? RELOAD_INTERVAL : 0);-export const getTableUrl = (table: Table, metadata?: Metadata): string => {const metadataTable = metadata?.table(table.id);const question = metadataTable?.newQuestion();return question ? Urls.question(question) : "";};-export const TableBrowser = _.compose(- Tables.loadList({- query: (_state: State, props: TableBrowserContainerProps) => ({- dbId: getDatabaseId(props, { includeVirtual: true }),- schemaName: getSchemaName(props),- }),- reloadInterval: getReloadInterval,- }),- connect((state: State, props: TableBrowserContainerProps) => ({- dbId: getDatabaseId(props, { includeVirtual: true }),- schemaName: getSchemaName(props),- metadata: getMetadata(state),- xraysEnabled: getSetting(state, "enable-xrays"),- getTableUrl,- })),-)(TableBrowserInner);+export const TableBrowser = (props: TableBrowserContainerProps) => {+ const dbId = getDatabaseId(props, { includeVirtual: true });+ const schemaName = getSchemaName(props);+ const { showSchemaInHeader } = props;+ const metadata = useSelector(getMetadata);+ const xraysEnabled = useSelector((state) =>+ getSetting(state, "enable-xrays"),+ );++ // Poll while any table is still syncing so newly-added databases refresh.+ const [reloadInterval, setReloadInterval] = useState(0);+ const useSchemaTables = dbId != null && schemaName != null;++ const schemaTablesResult = useListDatabaseSchemaTablesQuery(+ useSchemaTables ? { id: dbId, schema: schemaName } : skipToken,+ { pollingInterval: reloadInterval || undefined },+ );+ const databaseResult = useGetDatabaseMetadataQuery(+ dbId != null && !useSchemaTables ? { id: dbId } : skipToken,+ { pollingInterval: reloadInterval || undefined },+ );++ const tables =+ (useSchemaTables ? schemaTablesResult.data : databaseResult.data?.tables) ??+ EMPTY_TABLES;+ const isLoading = useSchemaTables+ ? schemaTablesResult.isLoading+ : databaseResult.isLoading;+ const error = useSchemaTables+ ? schemaTablesResult.error+ : databaseResult.error;++ useEffect(() => {+ setReloadInterval(tables.some(isSyncInProgress) ? RELOAD_INTERVAL : 0);+ }, [tables]);++ if (dbId == null) {+ return null;+ }++ return (+ <LoadingAndErrorWrapper loading={isLoading} error={error} noWrapper>+ <TableBrowserInner+ tables={tables}+ getTableUrl={getTableUrl}+ metadata={metadata}+ dbId={dbId}+ schemaName={schemaName}+ xraysEnabled={xraysEnabled}+ showSchemaInHeader={showSchemaInHeader}+ />+ </LoadingAndErrorWrapper>+ );+};diff --git a/frontend/src/metabase/common/components/MetadataInfo/TableInfo/TableInfo.tsx b/frontend/src/metabase/common/components/MetadataInfo/TableInfo/TableInfo.tsxindex bf65162d18b..3ec831a9ffa 100644--- a/frontend/src/metabase/common/components/MetadataInfo/TableInfo/TableInfo.tsx+++ b/frontend/src/metabase/common/components/MetadataInfo/TableInfo/TableInfo.tsx@@ -2,8 +2,13 @@ import { useEffect, useState } from "react";import { useAsyncFn } from "react-use";import { t } from "ttag";-import { Tables } from "metabase/entities/tables";import { connect } from "metabase/redux";+import type { Dispatch, State } from "metabase/redux/store";+import {+ fetchTableForeignKeys,+ fetchTableMetadata,+} from "metabase/redux/tables";+import { getMetadata } from "metabase/selectors/metadata";import type Table from "metabase-lib/v1/metadata/Table";import { Description, EmptyDescription } from "../MetadataInfo";@@ -24,27 +29,24 @@ export type TableInfoProps = {};const mapStateToProps = (- state: any,+ state: State,props: TableInfoProps,): { table?: Table } => {return {- table: Tables.selectors.getObject(state, {- entityId: props.tableId,- }) as Table,+ table: getMetadata(state).table(props.tableId) ?? undefined,};};-const mapDispatchToProps: {- fetchForeignKeys: (args: { id: Table["id"] }) => Promise<any>;- fetchMetadata: (args: { id: Table["id"] }) => Promise<any>;-} = {- fetchForeignKeys: Tables.actions.fetchForeignKeys,- fetchMetadata: Tables.actions.fetchMetadata,-};+const mapDispatchToProps = (dispatch: Dispatch) => ({+ fetchForeignKeys: (args: { id: Table["id"] }) =>+ dispatch(fetchTableForeignKeys(args)),+ fetchMetadata: (args: { id: Table["id"] }) =>+ dispatch(fetchTableMetadata(args)),+});type AllProps = TableInfoProps &ReturnType<typeof mapStateToProps> &- typeof mapDispatchToProps;+ ReturnType<typeof mapDispatchToProps>;function useDependentTableMetadata({tableId,diff --git a/frontend/src/metabase/common/hooks/entity-framework/use-entity-list-query/use-entity-list-query.unit.spec.tsx b/frontend/src/metabase/common/hooks/entity-framework/use-entity-list-query/use-entity-list-query.unit.spec.tsxindex 8fccf254108..b419a9576f3 100644--- a/frontend/src/metabase/common/hooks/entity-framework/use-entity-list-query/use-entity-list-query.unit.spec.tsx+++ b/frontend/src/metabase/common/hooks/entity-framework/use-entity-list-query/use-entity-list-query.unit.spec.tsx@@ -1,10 +1,7 @@import userEvent from "@testing-library/user-event";import fetchMock from "fetch-mock";-import {- setupCardsEndpoints,- setupTablesEndpoints,-} from "__support__/server-mocks";+import { setupCardsEndpoints } from "__support__/server-mocks";import {renderWithProviders,screen,@@ -14,26 +11,28 @@ import {} from "__support__/ui";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import { Questions } from "metabase/entities/questions";-import { Tables } from "metabase/entities/tables";import { useDispatch } from "metabase/redux";import { delay } from "metabase/utils/promise";import type Question from "metabase-lib/v1/Question";-import type Table from "metabase-lib/v1/metadata/Table";-import type { TableListQuery } from "metabase-types/api";-import { createMockCard, createMockTable } from "metabase-types/api/mocks";+import { createMockCard } from "metabase-types/api/mocks";import { useEntityListQuery } from "./use-entity-list-query";const TEST_CARD = createMockCard();-const TEST_TABLE = createMockTable();-const TestComponent = ({ testId }: { testId?: string }) => {+const TestComponent = ({+ reload,+ testId,+}: {+ reload?: boolean;+ testId?: string;+}) => {const {data = [],isLoading,error,} = useEntityListQuery<Question>(- {},+ { reload },{fetchList: Questions.actions.fetchList,getList: Questions.selectors.getList,@@ -63,51 +62,13 @@ const TestComponent = ({ testId }: { testId?: string }) => {{data.map((question) => (<div key={question.id()}>{question.displayName()}</div>))}- <TestInnerComponent />- </div>- );-};--const TestInnerComponent = () => {- const {- data = [],- isLoading,- error,- } = useEntityListQuery<Table, TableListQuery>(- {- reload: true,- },- {- fetchList: Tables.actions.fetchList,- getList: Tables.selectors.getList,- getLoading: Tables.selectors.getLoading,- getLoaded: Tables.selectors.getLoaded,- getError: Tables.selectors.getError,- getListMetadata: Tables.selectors.getListMetadata,- },- );-- const dispatch = useDispatch();- const handleInvalidate = () => dispatch(Tables.actions.invalidateLists());-- if (isLoading || error) {- return <LoadingAndErrorWrapper loading={isLoading} error={error} />;- }-- return (- <div>- <button onClick={handleInvalidate}>Invalidate tables</button>- {data.map((table) => (- <div key={table.id}>{table.name}</div>- ))}</div>);};-const setup = () => {+const setup = ({ reload }: { reload?: boolean } = {}) => {setupCardsEndpoints([TEST_CARD]);- setupTablesEndpoints([TEST_TABLE]);- return renderWithProviders(<TestComponent />);+ return renderWithProviders(<TestComponent reload={reload} />);};describe("useEntityListQuery", () => {@@ -117,15 +78,13 @@ describe("useEntityListQuery", () => {expect(screen.getByTestId("loading-indicator")).toBeInTheDocument();});- it("should initially load data only once the reload flag in a nested component tree", async () => {+ it("should load data only once", async () => {setup();await waitForLoaderToBeRemoved();expect(screen.getByText(TEST_CARD.name)).toBeInTheDocument();- expect(screen.getByText(TEST_TABLE.name)).toBeInTheDocument();expect(fetchMock.callHistory.calls("path:/api/card")).toHaveLength(1);- expect(fetchMock.callHistory.calls("path:/api/table")).toHaveLength(1);});it("should not reload data when re-rendered", async () => {@@ -135,12 +94,10 @@ describe("useEntityListQuery", () => {rerender(<TestComponent />);expect(screen.getByText(TEST_CARD.name)).toBeInTheDocument();- expect(screen.getByText(TEST_TABLE.name)).toBeInTheDocument();expect(fetchMock.callHistory.calls("path:/api/card")).toHaveLength(1);- expect(fetchMock.callHistory.calls("path:/api/table")).toHaveLength(1);});- it("should reload data only for calls with the reload flag when re-mounted", async () => {+ it("should not reload data when re-mounted without the reload flag", async () => {const { rerender } = setup();await waitForLoaderToBeRemoved();@@ -149,35 +106,31 @@ describe("useEntityListQuery", () => {await waitForLoaderToBeRemoved();expect(screen.getByText(TEST_CARD.name)).toBeInTheDocument();- expect(screen.getByText(TEST_TABLE.name)).toBeInTheDocument();expect(fetchMock.callHistory.calls("path:/api/card")).toHaveLength(1);- expect(fetchMock.callHistory.calls("path:/api/table")).toHaveLength(2);});- it("should reload data when the reload flag is off and it is explicitly invalidated", async () => {- setup();+ it("should reload data when re-mounted with the reload flag", async () => {+ const { rerender } = setup({ reload: true });await waitForLoaderToBeRemoved();- await userEvent.click(screen.getByText("Invalidate questions"));+ rerender(<div />);+ rerender(<TestComponent reload />);+ await waitForLoaderToBeRemoved();- await waitFor(() => {- expect(fetchMock.callHistory.calls("path:/api/card")).toHaveLength(2);- });- expect(await screen.findByText(TEST_CARD.name)).toBeInTheDocument();+ expect(screen.getByText(TEST_CARD.name)).toBeInTheDocument();+ expect(fetchMock.callHistory.calls("path:/api/card")).toHaveLength(2);});- it("should reload data when the reload flag is on and it is explicitly invalidated", async () => {+ it("should reload data when explicitly invalidated", async () => {setup();await waitForLoaderToBeRemoved();- await userEvent.click(screen.getByText("Invalidate tables"));+ await userEvent.click(screen.getByText("Invalidate questions"));await waitFor(() => {- expect(fetchMock.callHistory.calls("path:/api/table")).toHaveLength(2);+ expect(fetchMock.callHistory.calls("path:/api/card")).toHaveLength(2);});- await waitForLoaderToBeRemoved();-- expect(screen.getByText(TEST_TABLE.name)).toBeInTheDocument();+ expect(await screen.findByText(TEST_CARD.name)).toBeInTheDocument();});it("should not remove loader in case second api call is cached", async () => {diff --git a/frontend/src/metabase/common/hooks/entity-framework/use-entity-query/use-entity-query.unit.spec.tsx b/frontend/src/metabase/common/hooks/entity-framework/use-entity-query/use-entity-query.unit.spec.tsxindex f51246c9f5e..3cb8063f67b 100644--- a/frontend/src/metabase/common/hooks/entity-framework/use-entity-query/use-entity-query.unit.spec.tsx+++ b/frontend/src/metabase/common/hooks/entity-framework/use-entity-query/use-entity-query.unit.spec.tsx@@ -1,9 +1,6 @@import fetchMock from "fetch-mock";-import {- setupCardEndpoints,- setupTableEndpoints,-} from "__support__/server-mocks";+import { setupCardEndpoints } from "__support__/server-mocks";import {renderWithProviders,screen,@@ -11,16 +8,14 @@ import {} from "__support__/ui";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import { Questions } from "metabase/entities/questions";-import { Tables } from "metabase/entities/tables";import type Question from "metabase-lib/v1/Question";-import type Table from "metabase-lib/v1/metadata/Table";-import type { CardId, TableId } from "metabase-types/api";-import { createMockCard, createMockTable } from "metabase-types/api/mocks";+import type { CardId } from "metabase-types/api";+import { createMockCard } from "metabase-types/api/mocks";import { useEntityQuery } from "./use-entity-query";-const TEST_CARD = createMockCard();-const TEST_TABLE = createMockTable();+const TEST_CARD = createMockCard({ id: 1, name: "Card One" });+const TEST_CARD_RELOAD = createMockCard({ id: 2, name: "Card Two" });const TestComponent = () => {const {@@ -53,32 +48,32 @@ const TestComponent = () => {const TestInnerComponent = () => {const {- data: table,+ data: question,isLoading,error,- } = useEntityQuery<TableId, Table>(+ } = useEntityQuery<CardId, Question>({- id: TEST_TABLE.id,+ id: TEST_CARD_RELOAD.id,reload: true,},{- fetch: Tables.actions.fetch,- getObject: Tables.selectors.getObject,- getLoading: Tables.selectors.getLoading,- getError: Tables.selectors.getError,+ fetch: Questions.actions.fetch,+ getObject: Questions.selectors.getObject,+ getLoading: Questions.selectors.getLoading,+ getError: Questions.selectors.getError,},);- if (isLoading || error || !table) {+ if (isLoading || error || !question) {return <LoadingAndErrorWrapper loading={isLoading} error={error} />;}- return <div>{table.name}</div>;+ return <div>{question.displayName()}</div>;};const setup = () => {setupCardEndpoints(TEST_CARD);- setupTableEndpoints(TEST_TABLE);+ setupCardEndpoints(TEST_CARD_RELOAD);return renderWithProviders(<TestComponent />);};@@ -95,12 +90,12 @@ describe("useEntityQuery", () => {await waitForLoaderToBeRemoved();expect(screen.getByText(TEST_CARD.name)).toBeInTheDocument();- expect(screen.getByText(TEST_TABLE.name)).toBeInTheDocument();+ expect(screen.getByText(TEST_CARD_RELOAD.name)).toBeInTheDocument();expect(fetchMock.callHistory.calls(`path:/api/card/${TEST_CARD.id}`),).toHaveLength(1);expect(- fetchMock.callHistory.calls(`path:/api/table/${TEST_TABLE.id}`),+ fetchMock.callHistory.calls(`path:/api/card/${TEST_CARD_RELOAD.id}`),).toHaveLength(1);});@@ -111,12 +106,12 @@ describe("useEntityQuery", () => {rerender(<TestComponent />);expect(screen.getByText(TEST_CARD.name)).toBeInTheDocument();- expect(screen.getByText(TEST_TABLE.name)).toBeInTheDocument();+ expect(screen.getByText(TEST_CARD_RELOAD.name)).toBeInTheDocument();expect(fetchMock.callHistory.calls(`path:/api/card/${TEST_CARD.id}`),).toHaveLength(1);expect(- fetchMock.callHistory.calls(`path:/api/table/${TEST_TABLE.id}`),+ fetchMock.callHistory.calls(`path:/api/card/${TEST_CARD_RELOAD.id}`),).toHaveLength(1);});@@ -129,12 +124,12 @@ describe("useEntityQuery", () => {await waitForLoaderToBeRemoved();expect(screen.getByText(TEST_CARD.name)).toBeInTheDocument();- expect(screen.getByText(TEST_TABLE.name)).toBeInTheDocument();+ expect(screen.getByText(TEST_CARD_RELOAD.name)).toBeInTheDocument();expect(fetchMock.callHistory.calls(`path:/api/card/${TEST_CARD.id}`),).toHaveLength(1);expect(- fetchMock.callHistory.calls(`path:/api/table/${TEST_TABLE.id}`),+ fetchMock.callHistory.calls(`path:/api/card/${TEST_CARD_RELOAD.id}`),).toHaveLength(2);});});diff --git a/frontend/src/metabase/common/hooks/entity-framework/use-table-query/use-table-query.ts b/frontend/src/metabase/common/hooks/entity-framework/use-table-query/use-table-query.tsindex 600f466563d..9739091c87f 100644--- a/frontend/src/metabase/common/hooks/entity-framework/use-table-query/use-table-query.ts+++ b/frontend/src/metabase/common/hooks/entity-framework/use-table-query/use-table-query.ts@@ -1,22 +1,36 @@+import { skipToken, useGetTableQuery } from "metabase/api";import type {UseEntityQueryProps,UseEntityQueryResult,} from "metabase/common/hooks/entity-framework/use-entity-query";-import { useEntityQuery } from "metabase/common/hooks/entity-framework/use-entity-query";-import { Tables } from "metabase/entities/tables";+import { useSelector } from "metabase/redux";+import { getMetadata } from "metabase/selectors/metadata";import type Table from "metabase-lib/v1/metadata/Table";import type { GetTableRequest, TableId } from "metabase-types/api";/*** @deprecated use "metabase/api" instead*/-export const useTableQuery = (- props: UseEntityQueryProps<TableId, GetTableRequest>,-): UseEntityQueryResult<Table> => {- return useEntityQuery(props, {- fetch: Tables.actions.fetch,- getObject: Tables.selectors.getObject,- getLoading: Tables.selectors.getLoading,- getError: Tables.selectors.getError,- });+export const useTableQuery = ({+ id,+ query,+ reload = false,+ enabled = true,+}: UseEntityQueryProps<+ TableId,+ GetTableRequest+>): UseEntityQueryResult<Table> => {+ const isActive = enabled && id != null;+ const { isFetching, error } = useGetTableQuery(+ isActive ? { id, ...query } : skipToken,+ { refetchOnMountOrArgChange: reload },+ );+ const data = useSelector((state) =>+ id != null ? (getMetadata(state).table(id) ?? undefined) : undefined,+ );+ return {+ data,+ isLoading: isFetching || (isActive && data == null),+ error,+ };};diff --git a/frontend/src/metabase/entities/index.ts b/frontend/src/metabase/entities/index.tsindex 5830ecb6bbb..9e0dfe2b71e 100644--- a/frontend/src/metabase/entities/index.ts+++ b/frontend/src/metabase/entities/index.ts@@ -69,5 +69,3 @@*/export { Questions as questions } from "./questions";--export { Tables as tables } from "./tables";diff --git a/frontend/src/metabase/entities/tables-reducer.ts b/frontend/src/metabase/entities/tables-reducer.tsnew file mode 100644index 00000000000..65f0ec91069--- /dev/null+++ b/frontend/src/metabase/entities/tables-reducer.ts@@ -0,0 +1,150 @@+import { updateIn } from "icepick";++import { Questions } from "metabase/entities/questions";+import {+ convertSavedQuestionToVirtualTable,+ getCollectionVirtualSchemaId,+ getCollectionVirtualSchemaName,+ getQuestionVirtualTableId,+} from "metabase-lib/v1/metadata/utils/saved-questions";++type TableState = Record<string, any>;+type ReducerAction = { type: string; payload?: any; error?: unknown };++/**+ * Reducer for the `state.entities.tables` slice.+ *+ * The `tables` entity has been removed from the entity framework (its CRUD now+ * lives in `metabase/api/table`), but the normalized slice still needs to:+ *+ * - keep virtual tables (the `card__<id>` representation of saved questions) in+ * sync as questions are created, updated, and archived, and+ * - keep `original_fields` in sync when a field is updated elsewhere.+ *+ * It is registered as the retired-entity reducer for `tables` in+ * `metabase/redux/entities`, where it runs after `handleEntities` has merged any+ * `payload.entities.tables`.+ */+export function tablesReducer(+ state: TableState = {},+ { type, payload, error }: ReducerAction,+): TableState {+ if (type === Questions.actionTypes.CREATE && !error) {+ const card = payload.question;+ const virtualQuestionTable = convertSavedQuestionToVirtualTable(card);++ if (state[virtualQuestionTable.id]) {+ return state;+ }++ return {+ ...state,+ [virtualQuestionTable.id]: virtualQuestionTable,+ };+ }++ if (type === Questions.actionTypes.UPDATE && !error) {+ const card = payload.question;+ const virtualTableId = getQuestionVirtualTableId(card.id);++ if (card.archived && state[virtualTableId]) {+ const nextState = { ...state };+ delete nextState[virtualTableId];+ return nextState;+ }++ if (state[virtualTableId]) {+ const virtualTable = state[virtualTableId];+ const virtualSchemaId = getCollectionVirtualSchemaId(card.collection);+ const virtualSchemaName = getCollectionVirtualSchemaName(card.collection);++ if (+ virtualTable.display_name !== card.name ||+ virtualTable.moderated_status !== card.moderated_status ||+ virtualTable.description !== card.description ||+ virtualTable.schema !== virtualSchemaId ||+ virtualTable.schema_name !== virtualSchemaName+ ) {+ state = updateIn(state, [virtualTableId], (table) => ({+ ...table,+ display_name: card.name,+ moderated_status: card.moderated_status,+ description: card.description,+ schema: virtualSchemaId,+ schema_name: virtualSchemaName,+ }));+ }++ return state;+ }++ return {+ ...state,+ [virtualTableId]: convertSavedQuestionToVirtualTable(card),+ };+ }++ // Keep `original_fields` in sync when something dispatches+ // `updateMetadata(field, FieldSchema)` (e.g. RTK Query's getField+ // onQueryStarted, or the deprecated redux/metadata wrappers). Without this,+ // edits land in state.entities.fields but hydrateTableFields keeps reading+ // stale data from original_fields.+ //+ // Virtual card tables can have multiple `original_fields` entries with the+ // same `id` (a model with two columns both mapped to the same source+ // field). Normalization collapses those into one entry in+ // `payload.entities.fields`, so we can't tell which `original_fields` entry+ // the update belongs to — skip the sync for ambiguous matches.+ if (+ type === "metabase/entities/UPDATE" &&+ !error &&+ payload?.entities?.fields+ ) {+ let nextState = state;+ for (const updated of Object.values<any>(payload.entities.fields)) {+ const tableId = updated.table_id;+ const table = nextState[tableId];+ if (!table?.original_fields) {+ continue;+ }+ const matchingIndex = findUniqueIndex(+ table.original_fields,+ (field: any) => field.id === updated.id,+ );+ if (matchingIndex < 0) {+ continue;+ }+ const nextOriginalFields = [...table.original_fields];+ nextOriginalFields[matchingIndex] = {+ ...nextOriginalFields[matchingIndex],+ ...updated,+ };+ nextState = {+ ...nextState,+ [tableId]: { ...table, original_fields: nextOriginalFields },+ };+ }+ return nextState;+ }++ return state;+}++// Returns the index of the only element matching the predicate, or -1 if there+// are zero or more than one matches.+function findUniqueIndex<T>(+ array: T[],+ predicate: (value: T) => boolean,+): number {+ let found = -1;+ for (let index = 0; index < array.length; index++) {+ if (!predicate(array[index])) {+ continue;+ }+ if (found !== -1) {+ return -1;+ }+ found = index;+ }+ return found;+}diff --git a/frontend/src/metabase/entities/tables.unit.spec.js b/frontend/src/metabase/entities/tables-reducer.unit.spec.tssimilarity index 59%rename from frontend/src/metabase/entities/tables.unit.spec.jsrename to frontend/src/metabase/entities/tables-reducer.unit.spec.tsindex 81ae7c8f91a..7ec0fa3d980 100644--- a/frontend/src/metabase/entities/tables.unit.spec.js+++ b/frontend/src/metabase/entities/tables-reducer.unit.spec.ts@@ -1,9 +1,9 @@import { Questions } from "metabase/entities/questions";-import { Tables } from "metabase/entities/tables";+import { tablesReducer } from "metabase/entities/tables-reducer";import { convertSavedQuestionToVirtualTable } from "metabase-lib/v1/metadata/utils/saved-questions";-describe("table entity", () => {- describe("saved questions | reducer", () => {+describe("tablesReducer", () => {+ describe("saved questions virtual table sync", () => {function getQuestion({id = 5,name = "Q1",@@ -24,7 +24,7 @@ describe("table entity", () => {};}- function getCreateAction(question) {+ function getCreateAction(question: unknown) {return {type: Questions.actionTypes.CREATE,payload: {@@ -34,7 +34,7 @@ describe("table entity", () => {};}- function getUpdateAction(question) {+ function getUpdateAction(question: unknown) {return {type: Questions.actionTypes.UPDATE,payload: {@@ -44,20 +44,40 @@ describe("table entity", () => {};}- it("should add saved question to tables state", () => {+ it("should add saved question to tables state on CREATE", () => {const { question, virtualTable } = getQuestion();- const nextState = Tables.reducer({}, getCreateAction(question));+ const nextState = tablesReducer({}, getCreateAction(question));expect(nextState).toEqual({[virtualTable.id]: virtualTable,});});+ it("should leave state untouched on CREATE when the virtual table already exists", () => {+ const { question, virtualTable } = getQuestion();+ const state = { [virtualTable.id]: virtualTable };++ const nextState = tablesReducer(state, getCreateAction(question));++ expect(nextState).toBe(state);+ });++ it("should ignore CREATE actions flagged with error", () => {+ const { question } = getQuestion();++ const nextState = tablesReducer(+ {},+ { ...getCreateAction(question), error: true },+ );++ expect(nextState).toEqual({});+ });+it("should remove saved question from state when archived", () => {const { question, virtualTable } = getQuestion({ archived: true });- const nextState = Tables.reducer(+ const nextState = tablesReducer({card__123: { foo: "bar" },[virtualTable.id]: virtualTable,@@ -68,19 +88,66 @@ describe("table entity", () => {expect(nextState).toEqual({ card__123: { foo: "bar" } });});+ it("should not mutate the previous state when removing an archived question", () => {+ const { question, virtualTable } = getQuestion({ archived: true });+ const state = {+ card__123: { foo: "bar" },+ [virtualTable.id]: virtualTable,+ };++ const nextState = tablesReducer(state, getUpdateAction(question));++ expect(nextState).not.toBe(state);+ expect(state[virtualTable.id]).toBeDefined();+ });+it("should add saved question to tables state when unarchived", () => {const { question, virtualTable } = getQuestion();- const nextState = Tables.reducer({}, getUpdateAction(question));+ const nextState = tablesReducer({}, getUpdateAction(question));expect(nextState).toEqual({[virtualTable.id]: virtualTable,});});++ it("should sync display_name and description into an existing virtual table on UPDATE", () => {+ const { question, virtualTable } = getQuestion();+ const state = { [virtualTable.id]: virtualTable };++ const renamed = { ...question, name: "Renamed", description: "Now here" };+ const nextState = tablesReducer(state, getUpdateAction(renamed));++ expect(nextState[virtualTable.id]).toMatchObject({+ display_name: "Renamed",+ description: "Now here",+ });+ });++ it("should leave state untouched on UPDATE when nothing relevant changed", () => {+ const { question, virtualTable } = getQuestion();+ const state = { [virtualTable.id]: virtualTable };++ const nextState = tablesReducer(state, getUpdateAction(question));++ expect(nextState).toBe(state);+ });++ it("should ignore UPDATE actions flagged with error", () => {+ const { question, virtualTable } = getQuestion({ archived: true });+ const state = { [virtualTable.id]: virtualTable };++ const nextState = tablesReducer(state, {+ ...getUpdateAction(question),+ error: true,+ });++ expect(nextState).toBe(state);+ });});describe("metabase/entities/UPDATE original_fields sync", () => {- function getEntitiesUpdateAction(fields) {+ function getEntitiesUpdateAction(fields: Record<string, unknown>) {return {type: "metabase/entities/UPDATE",payload: {@@ -101,7 +168,7 @@ describe("table entity", () => {},};- const nextState = Tables.reducer(+ const nextState = tablesReducer(state,getEntitiesUpdateAction({10: { id: 10, table_id: 1, display_name: "New" },@@ -117,7 +184,7 @@ describe("table entity", () => {it("leaves state untouched when the table has no original_fields", () => {const state = { 1: { id: 1, name: "Orders" } };- const nextState = Tables.reducer(+ const nextState = tablesReducer(state,getEntitiesUpdateAction({10: { id: 10, table_id: 1, display_name: "New" },@@ -135,7 +202,7 @@ describe("table entity", () => {},};- const nextState = Tables.reducer(+ const nextState = tablesReducer(state,getEntitiesUpdateAction({10: { id: 10, table_id: 1, display_name: "New" },@@ -159,7 +226,7 @@ describe("table entity", () => {},};- const nextState = Tables.reducer(+ const nextState = tablesReducer(state,getEntitiesUpdateAction({"card__1:10": { id: 10, table_id: "card__1", display_name: "Both" },@@ -177,7 +244,7 @@ describe("table entity", () => {},};- const nextState = Tables.reducer(state, {+ const nextState = tablesReducer(state, {type: "metabase/entities/UPDATE",error: true,payload: {diff --git a/frontend/src/metabase/entities/tables.js b/frontend/src/metabase/entities/tables.jsdeleted file mode 100644index b30e10c861e..00000000000--- a/frontend/src/metabase/entities/tables.js+++ /dev/null@@ -1,490 +0,0 @@-import { createSelector } from "@reduxjs/toolkit";-import { updateIn } from "icepick";-import { useEffect, useMemo } from "react";-import { match } from "ts-pattern";-import { t } from "ttag";-import _ from "underscore";--import {- databaseApi,- fieldApi,- skipToken,- tableApi,- useGetDatabaseMetadataQuery,- useGetTableQuery,- useGetTableQueryMetadataQuery,- useListDatabaseSchemaTablesQuery,- useListTablesQuery,-} from "metabase/api";-import { Questions } from "metabase/entities/questions";-import {- compose,- createThunkAction,- useDispatch,- useSelector,- withAction,-} from "metabase/redux";-import { TableSchema } from "metabase/schema";-import {- getMetadata,- getMetadataUnfiltered,-} from "metabase/selectors/metadata";-import {- convertSavedQuestionToVirtualTable,- getCollectionVirtualSchemaId,- getCollectionVirtualSchemaName,- getQuestionVirtualTableId,-} from "metabase-lib/v1/metadata/utils/saved-questions";--import {- createEntity,- entityCompatibleQuery,- notify,- withCachedDataAndRequestState,- withNormalize,-} from "./utils";--// OBJECT ACTIONS-export const TABLES_BULK_UPDATE = "metabase/entities/TABLES_BULK_UPDATE";-export const FETCH_METADATA = "metabase/entities/FETCH_METADATA";-export const FETCH_TABLE_METADATA = "metabase/entities/FETCH_TABLE_METADATA";-export const FETCH_TABLE_FOREIGN_KEYS =- "metabase/entities/FETCH_TABLE_FOREIGN_KEYS";-export const UPDATE_TABLE_FIELD_ORDER =- "metabase/entities/UPDATE_TABLE_FIELD_ORDER";--/**- * @deprecated use "metabase/api" instead- */-export const Tables = createEntity({- name: "tables",- nameOne: "table",- path: "/api/table",- schema: TableSchema,-- rtk: () => ({- getUseGetQuery: (fetchType) => {- if (fetchType === "fetchMetadata") {- return {- useGetQuery: useGetTableQueryMetadataQuery,- };- }-- if (fetchType === "fetchMetadataDeprecated") {- return {- useGetQuery: useGetTableQueryMetadataQuery,- };- }-- if (fetchType === "fetchMetadataAndForeignTables") {- return {- useGetQuery: useGetMetadataAndForeignTables,- };- }-- return {- useGetQuery: useGetTableQuery,- };- },- useListQuery,- }),-- api: {- list: async ({ dbId, schemaName, ...params } = {}, dispatch) => {- if (dbId != null && schemaName != null) {- return entityCompatibleQuery(- { id: dbId, schema: schemaName, ...params },- dispatch,- databaseApi.endpoints.listDatabaseSchemaTables,- );- } else if (dbId != null) {- const database = await entityCompatibleQuery(- { id: dbId, ...params },- dispatch,- databaseApi.endpoints.getDatabaseMetadata,- );- return database.tables;- } else {- return entityCompatibleQuery(- params,- dispatch,- tableApi.endpoints.listTables,- );- }- },- get: (entityQuery, options, dispatch) =>- entityCompatibleQuery(entityQuery, dispatch, tableApi.endpoints.getTable),- },-- actions: {- // updates all tables in the `ids` key- bulkUpdate: compose(- withAction(TABLES_BULK_UPDATE),- withNormalize([TableSchema]),- )(- (updates) => async (dispatch) =>- entityCompatibleQuery(- updates,- dispatch,- tableApi.endpoints.updateTableList,- ),- ),- },-- // ACTION CREATORS- objectActions: {- updateProperty(entityObject, name, value, opts) {- return Tables.actions.update(- entityObject,- { [name]: value },- notify(opts, `Table ${name}`, t`updated`),- );- },- // loads `query_metadata` for a single table- fetchMetadata: compose(- withAction(FETCH_METADATA),- withNormalize(TableSchema),- )(- ({ id, ...params }, options = {}) =>- (dispatch) =>- entityCompatibleQuery(- { id, ...params, ...options.params },- dispatch,- tableApi.endpoints.getTableQueryMetadata,- { forceRefetch: false },- ),- ),-- // fetches table metadata with the request state & caching managed by the entity framework- // data is not properly cached & invalidated this way, prefer fetchMetadata instead- // used only to support legacy entity framework loader HoCs- fetchMetadataDeprecated: compose(- withAction(FETCH_METADATA),- withCachedDataAndRequestState(- ({ id }) => [...Tables.getObjectStatePath(id)],- ({ id }) => [- ...Tables.getObjectStatePath(id),- "fetchMetadataDeprecated",- ],- (entityQuery) => Tables.getQueryKey(entityQuery),- ),- withNormalize(TableSchema),- )(- ({ id, ...params }, options = {}) =>- (dispatch) =>- entityCompatibleQuery(- { id, ...params, ...options.params },- dispatch,- tableApi.endpoints.getTableQueryMetadata,- ),- ),-- // like fetchMetadata but also loads tables linked by foreign key- fetchMetadataAndForeignTables: createThunkAction(- FETCH_TABLE_METADATA,- ({ id }, options = {}) =>- async (dispatch, getState) => {- await dispatch(- Tables.actions.fetchMetadataDeprecated({ id }, options),- );- // fetch foreign key linked table's metadata as well- const table = Tables.selectors[- options.selectorName || "getObjectUnfiltered"- ](getState(), { entityId: id });- await Promise.all([- ...getTableForeignKeyTableIds(table).map((id) =>- dispatch(Tables.actions.fetchMetadataDeprecated({ id }, options)),- ),- ...getTableForeignKeyFieldIds(table).map((id) =>- entityCompatibleQuery(- { id },- dispatch,- fieldApi.endpoints.getField,- { forceRefetch: options.reload ?? false },- ),- ),- ]);- },- ),-- fetchForeignKeys: compose(- withAction(FETCH_TABLE_FOREIGN_KEYS),- withCachedDataAndRequestState(- ({ id }) => [...Tables.getObjectStatePath(id)],- ({ id }) => [...Tables.getObjectStatePath(id), "fetchForeignKeys"],- (entityQuery) => Tables.getQueryKey(entityQuery),- ),- withNormalize(TableSchema),- )(({ id }) => async (dispatch, getState) => {- const fks = await entityCompatibleQuery(- id,- dispatch,- tableApi.endpoints.listTableForeignKeys,- );- return { id, fks: fks };- }),-- setFieldOrder:- ({ id }, fieldOrder) =>- (dispatch) => {- dispatch({- type: UPDATE_TABLE_FIELD_ORDER,- payload: { id, fieldOrder },- });- entityCompatibleQuery(- { id, field_order: fieldOrder },- dispatch,- tableApi.endpoints.updateTableFieldsOrder,- );- },- },-- reducer: (state = {}, { type, payload, error }) => {- if (type === Questions.actionTypes.CREATE && !error) {- const card = payload.question;- const virtualQuestionTable = convertSavedQuestionToVirtualTable(card);-- if (state[virtualQuestionTable.id]) {- return state;- }-- return {- ...state,- [virtualQuestionTable.id]: virtualQuestionTable,- };- }-- if (type === Questions.actionTypes.UPDATE && !error) {- const card = payload.question;- const virtualTableId = getQuestionVirtualTableId(card.id);-- if (card.archived && state[virtualTableId]) {- delete state[virtualTableId];- return state;- }-- if (state[virtualTableId]) {- const virtualTable = state[virtualTableId];- const virtualSchemaId = getCollectionVirtualSchemaId(card.collection);- const virtualSchemaName = getCollectionVirtualSchemaName(- card.collection,- );-- if (- virtualTable.display_name !== card.name ||- virtualTable.moderated_status !== card.moderated_status ||- virtualTable.description !== card.description ||- virtualTable.schema !== virtualSchemaId ||- virtualTable.schema_name !== virtualSchemaName- ) {- state = updateIn(state, [virtualTableId], (table) => ({- ...table,- display_name: card.name,- moderated_status: card.moderated_status,- description: card.description,- schema: virtualSchemaId,- schema_name: virtualSchemaName,- }));- }-- return state;- }-- return {- ...state,- [virtualTableId]: convertSavedQuestionToVirtualTable(card),- };- }-- if (type === UPDATE_TABLE_FIELD_ORDER) {- const table = state[payload.id];- if (table) {- return {- ...state,- [table.id]: { ...table, field_order: "custom" },- };- }- }-- // Keep `original_fields` in sync when something dispatches- // `updateMetadata(field, FieldSchema)` (e.g. RTK Query's getField- // onQueryStarted, or the deprecated redux/metadata wrappers). Without this,- // edits land in state.entities.fields but hydrateTableFields keeps reading- // stale data from original_fields.- //- // Virtual card tables can have multiple `original_fields` entries with the- // same `id` (a model with two columns both mapped to the same source- // field). Normalization collapses those into one entry in- // `payload.entities.fields`, so we can't tell which `original_fields` entry- // the update belongs to — skip the sync for ambiguous matches.- if (- type === "metabase/entities/UPDATE" &&- !error &&- payload?.entities?.fields- ) {- let nextState = state;- for (const updated of Object.values(payload.entities.fields)) {- const tableId = updated.table_id;- const table = nextState[tableId];- if (!table?.original_fields) {- continue;- }- const matchingIndex = findUniqueIndex(- table.original_fields,- (field) => field.id === updated.id,- );- if (matchingIndex < 0) {- continue;- }- const nextOriginalFields = [...table.original_fields];- nextOriginalFields[matchingIndex] = {- ...nextOriginalFields[matchingIndex],- ...updated,- };- nextState = {- ...nextState,- [tableId]: { ...table, original_fields: nextOriginalFields },- };- }- return nextState;- }-- return state;- },-- selectors: {- getObject: (state, { entityId }) => getMetadata(state).table(entityId),- // these unfiltered selectors include hidden tables/fields for display in the admin panel- getObjectUnfiltered: (state, { entityId }) =>- getMetadataUnfiltered(state).table(entityId),- getListUnfiltered: (state, { entityQuery }) => {- const entityIds =- Tables.selectors.getEntityIds(state, { entityQuery }) ?? [];- return entityIds.map((entityId) =>- Tables.selectors.getObjectUnfiltered(state, { entityId }),- );- },- getTable: createSelector(- // we wrap getMetadata to handle a circular dep issue- [(state) => getMetadata(state), (state, props) => props.entityId],- (metadata, id) => metadata.table(id),- ),- },-});--const useGetMetadataAndForeignTables = (entityQuery, options) => {- const dispatch = useDispatch();- const table = useSelector((state) =>- Tables.selectors[options.selectorName || "getObjectUnfiltered"](state, {- entityId: entityQuery.id,- }),- );-- const result = useGetTableQueryMetadataQuery(entityQuery, options);-- const tableForeignKeyTableIds = useMemo(- () => (table ? getTableForeignKeyTableIds(table) : []),- [table],- );- const tableForeignKeyFieldIds = useMemo(- () => (table ? getTableForeignKeyFieldIds(table) : []),- [table],- );-- // fetch foreign key linked tables metadata as well- useEffect(() => {- for (const id of tableForeignKeyTableIds) {- dispatch(Tables.actions.fetchMetadataDeprecated({ id }, options));- }- }, [dispatch, options, tableForeignKeyTableIds]);-- useEffect(() => {- for (const id of tableForeignKeyFieldIds) {- entityCompatibleQuery({ id }, dispatch, fieldApi.endpoints.getField, {- forceRefetch: options.reload ?? false,- });- }- }, [dispatch, options, tableForeignKeyFieldIds]);-- return result;-};--// Returns the index of the only element matching the predicate, or -1 if there-// are zero or more than one matches.-function findUniqueIndex(array, predicate) {- let found = -1;- for (let index = 0; index < array.length; index++) {- if (!predicate(array[index])) {- continue;- }- if (found !== -1) {- return -1;- }- found = index;- }- return found;-}--function getTableForeignKeyTableIds(table) {- return _.chain(table.fields)- .filter((field) => field.target != null)- .map((field) => field.target.table_id)- .uniq()- .value();-}--// overridden model FK columns have fk_target_field_id but don't have a target-// in this case we load the field instead of the table-function getTableForeignKeyFieldIds(table) {- return _.chain(table.fields)- .filter((field) => field.target == null && field.fk_target_field_id != null)- .map((field) => field.fk_target_field_id)- .uniq()- .value();-}--function useListQuery({ dbId, schemaName, ...params } = {}, options) {- const endpoint = getUseListQueryEndpoint(dbId, schemaName);-- const databaseSchemaTables = useListDatabaseSchemaTablesQuery(- endpoint === "listDatabaseSchemaTables"- ? { id: dbId, schema: schemaName, ...params }- : skipToken,- options,- );-- const databaseMetadataQuery = useGetDatabaseMetadataQuery(- endpoint === "getDatabaseMetadata" ? { id: dbId, ...params } : skipToken,- options,- );- const databaseMetadata = useMemo(- () => ({- ...databaseMetadataQuery,- data: databaseMetadataQuery.data?.tables,- }),- [databaseMetadataQuery],- );-- const tables = useListTablesQuery(- endpoint === "listTables" ? params : skipToken,- options,- );-- return match(endpoint)- .with("listDatabaseSchemaTables", () => databaseSchemaTables)- .with("getDatabaseMetadata", () => databaseMetadata)- .with("listTables", () => tables)- .exhaustive();-}--function getUseListQueryEndpoint(dbId, schemaName) {- if (dbId != null && schemaName) {- return "listDatabaseSchemaTables";- }-- if (dbId != null) {- return "getDatabaseMetadata";- }-- return "listTables";-}diff --git a/frontend/src/metabase/entities/utils.ts b/frontend/src/metabase/entities/utils.tsindex 901d75194e8..04e3afd9a82 100644--- a/frontend/src/metabase/entities/utils.ts+++ b/frontend/src/metabase/entities/utils.ts@@ -982,9 +982,19 @@ const RETIRED_ENTITY_NAMES = ["schemas","segments","snippets",+ "tables",];-export function combineEntities(entities: Entity[]): CombinedEntities {+/**+ * Custom slice reducers for retired entities whose normalized slice needs more+ * than the default `handleEntities` merge — passed in by the caller (see+ * `metabase/redux/entities`) to keep custom reducers out of this module and+ * avoid circular imports.+ */+export function combineEntities(+ entities: Entity[],+ retiredReducers: Record<string, EntitiesReducer> = {},+): CombinedEntities {const entitiesMap: Record<string, Entity> = {};const reducersMap: EntitiesReducersMap = {};@@ -1000,7 +1010,11 @@ export function combineEntities(entities: Entity[]): CombinedEntities {for (const name of RETIRED_ENTITY_NAMES) {if (!(name in reducersMap)) {- reducersMap[name] = handleEntities(/^metabase\/entities\//, name);+ reducersMap[name] = handleEntities(+ /^metabase\/entities\//,+ name,+ retiredReducers[name],+ );}}diff --git a/frontend/src/metabase/models/containers/ModelActions/ModelActions.tsx b/frontend/src/metabase/models/containers/ModelActions/ModelActions.tsxindex 605303e232d..bf8e5703e75 100644--- a/frontend/src/metabase/models/containers/ModelActions/ModelActions.tsx+++ b/frontend/src/metabase/models/containers/ModelActions/ModelActions.tsx@@ -7,12 +7,12 @@ import _ from "underscore";import { useListActionsQuery, useListDatabasesQuery } from "metabase/api";import { NotFound } from "metabase/common/components/ErrorPages";import { Questions } from "metabase/entities/questions";-import { Tables } from "metabase/entities/tables";import { usePageTitle } from "metabase/hooks/use-page-title";import ModelActionsView from "metabase/models/components/ModelActions";import { loadMetadataForCard } from "metabase/questions/actions";import { connect } from "metabase/redux";import type { State } from "metabase/redux/store";+import { fetchTableForeignKeys } from "metabase/redux/tables";import * as Urls from "metabase/urls";import * as Lib from "metabase-lib";import type Question from "metabase-lib/v1/Question";@@ -40,7 +40,7 @@ type Props = OwnProps & EntityLoadersProps & DispatchProps;const mapDispatchToProps = {loadMetadataForCard,- fetchTableForeignKeys: Tables.actions.fetchForeignKeys,+ fetchTableForeignKeys,onChangeLocation: replace,};diff --git a/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceTypeModal.tsx b/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceTypeModal.tsxindex b48abe7cacb..29cdaa0a9a6 100644--- a/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceTypeModal.tsx+++ b/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceTypeModal.tsx@@ -4,6 +4,7 @@ import { useAsyncFn } from "react-use";import { jt, t } from "ttag";import _ from "underscore";+import { skipToken, useGetTableQueryMetadataQuery } from "metabase/api";import { Button } from "metabase/common/components/Button";import { ExternalLink } from "metabase/common/components/ExternalLink";import { ModalContent } from "metabase/common/components/ModalContent";@@ -13,7 +14,6 @@ import type { SelectChangeEvent } from "metabase/common/components/Select";import { Option, Select } from "metabase/common/components/Select";import { SelectButton } from "metabase/common/components/SelectButton";import { Questions } from "metabase/entities/questions";-import { Tables } from "metabase/entities/tables";import { connect, useSelector } from "metabase/redux";import type { State } from "metabase/redux/store";import { getLearnUrl } from "metabase/selectors/settings";@@ -666,18 +666,31 @@ const mapDispatchToProps = {onFetchParameterValues: fetchParameterValues,};-// eslint-disable-next-line import/no-default-export -- deprecated usage-export default _.compose(- Tables.load({- id: (state: State, { sourceConfig: { card_id } }: ModalOwnProps) =>- card_id ? getQuestionVirtualTableId(card_id) : undefined,- fetchType: "fetchMetadataDeprecated",- requestType: "fetchMetadataDeprecated",- LoadingAndErrorWrapper: ModalLoadingAndErrorWrapper,- }),+const ValuesSourceTypeModalConnected = _.compose(Questions.load({id: (state: State, { sourceConfig: { card_id } }: ModalOwnProps) => card_id,LoadingAndErrorWrapper: ModalLoadingAndErrorWrapper,}),connect(null, mapDispatchToProps),)(ValuesSourceTypeModal);++// Loads the source card's virtual-table query metadata into the store (so the+// connected fields are available) before rendering, replacing the former+// Tables.load HOC.+function ValuesSourceTypeModalLoader(props: ModalOwnProps) {+ const { card_id } = props.sourceConfig;+ const virtualTableId =+ card_id != null ? getQuestionVirtualTableId(card_id) : undefined;+ const { isLoading, error } = useGetTableQueryMetadataQuery(+ virtualTableId != null ? { id: virtualTableId } : skipToken,+ );++ return (+ <ModalLoadingAndErrorWrapper loading={isLoading} error={error} noWrapper>+ <ValuesSourceTypeModalConnected {...props} />+ </ModalLoadingAndErrorWrapper>+ );+}++// eslint-disable-next-line import/no-default-export -- deprecated usage+export default ValuesSourceTypeModalLoader;diff --git a/frontend/src/metabase/querying/common/components/DataSelector/DataSelector.jsx b/frontend/src/metabase/querying/common/components/DataSelector/DataSelector.jsxindex 5cc4f25b95d..b5b4726cb28 100644--- a/frontend/src/metabase/querying/common/components/DataSelector/DataSelector.jsx+++ b/frontend/src/metabase/querying/common/components/DataSelector/DataSelector.jsx@@ -16,9 +16,9 @@ import { EmptyState } from "metabase/common/components/EmptyState";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import CS from "metabase/css/core/index.css";import { Questions } from "metabase/entities/questions";-import { Tables } from "metabase/entities/tables";import { entityCompatibleQuery } from "metabase/entities/utils";import { connect } from "metabase/redux";+import { fetchTableMetadata } from "metabase/redux/tables";import { getMetadata } from "metabase/selectors/metadata";import { getSetting } from "metabase/selectors/settings";import { canUserCreateQueries } from "metabase/selectors/user";@@ -1185,8 +1185,7 @@ const DataSelector = _.compose(databaseApi.endpoints.listDatabases,{ forceRefetch: false },),- fetchFields: (tableId) =>- dispatch(Tables.actions.fetchMetadata({ id: tableId })),+ fetchFields: (tableId) => dispatch(fetchTableMetadata({ id: tableId })),fetchQuestion: (id) =>dispatch(Questions.actions.fetch({diff --git a/frontend/src/metabase/querying/components/DataReference/TableInfoLoader.tsx b/frontend/src/metabase/querying/components/DataReference/TableInfoLoader.tsxindex 05ddbd381f5..1962df8b5a6 100644--- a/frontend/src/metabase/querying/components/DataReference/TableInfoLoader.tsx+++ b/frontend/src/metabase/querying/components/DataReference/TableInfoLoader.tsx@@ -1,8 +1,12 @@import { useEffect, useState } from "react";import { useAsyncFn } from "react-use";-import { Tables } from "metabase/entities/tables";import { connect } from "metabase/redux";+import type { Dispatch } from "metabase/redux/store";+import {+ fetchTableForeignKeys,+ fetchTableMetadata,+} from "metabase/redux/tables";import type Table from "metabase-lib/v1/metadata/Table";type OwnProps = {@@ -10,15 +14,14 @@ type OwnProps = {children: JSX.Element[];};-const mapDispatchToProps: {- fetchForeignKeys: (args: { id: Table["id"] }) => Promise<any>;- fetchMetadata: (args: { id: Table["id"] }) => Promise<any>;-} = {- fetchForeignKeys: Tables.actions.fetchForeignKeys,- fetchMetadata: Tables.actions.fetchMetadata,-};+const mapDispatchToProps = (dispatch: Dispatch) => ({+ fetchForeignKeys: (args: { id: Table["id"] }) =>+ dispatch(fetchTableForeignKeys(args)),+ fetchMetadata: (args: { id: Table["id"] }) =>+ dispatch(fetchTableMetadata(args)),+});-type AllProps = OwnProps & typeof mapDispatchToProps;+type AllProps = OwnProps & ReturnType<typeof mapDispatchToProps>;function useDependentTableMetadata({table,diff --git a/frontend/src/metabase/querying/segments/components/SegmentEditor/DataStep/DataStep.tsx b/frontend/src/metabase/querying/segments/components/SegmentEditor/DataStep/DataStep.tsxindex 04a106795cf..1b13b7d1a1d 100644--- a/frontend/src/metabase/querying/segments/components/SegmentEditor/DataStep/DataStep.tsx+++ b/frontend/src/metabase/querying/segments/components/SegmentEditor/DataStep/DataStep.tsx@@ -5,9 +5,9 @@ import {DataPickerModal,getDataPickerValue,} from "metabase/common/components/Pickers/DataPicker";-import { Tables } from "metabase/entities/tables";import { TableBreadcrumbs } from "metabase/metadata/components";import { useDispatch, useStore } from "metabase/redux";+import { fetchTableMetadataAndForeignKeys } from "metabase/redux/tables";import { getMetadata } from "metabase/selectors/metadata";import { Box, Button, Flex, Icon, Text } from "metabase/ui";import { checkNotNull } from "metabase/utils/types";@@ -41,9 +41,7 @@ export function DataStep({const dispatch = useDispatch();const handleChange = async (tableId: TableId) => {- await dispatch(- Tables.actions.fetchMetadataAndForeignTables({ id: tableId }),- );+ await dispatch(fetchTableMetadataAndForeignKeys({ id: tableId }));const metadata = getMetadata(store.getState());const databaseId = checkNotNull(metadata.table(tableId)).db_id;const metadataProvider = Lib.metadataProvider(databaseId, metadata);diff --git a/frontend/src/metabase/questions/actions.ts b/frontend/src/metabase/questions/actions.tsindex dd9ec50c055..b86e490da20 100644--- a/frontend/src/metabase/questions/actions.ts+++ b/frontend/src/metabase/questions/actions.ts@@ -1,7 +1,7 @@import { cardApi, datasetApi } from "metabase/api";-import { Tables } from "metabase/entities/tables";import { entityCompatibleQuery } from "metabase/entities/utils";import type { Dispatch } from "metabase/redux/store";+import { fetchTableMetadata } from "metabase/redux/tables";import type { Card, TableId, UnsavedCard } from "metabase-types/api";import type { EntityToken } from "metabase-types/api/entity";import { isSavedCard } from "metabase-types/guards";@@ -9,7 +9,7 @@ import { isSavedCard } from "metabase-types/guards";export const loadMetadataForTable =(tableId: TableId) => async (dispatch: Dispatch) => {try {- await dispatch(Tables.actions.fetchMetadata({ id: tableId }));+ await dispatch(fetchTableMetadata({ id: tableId }));} catch (error) {console.error("Error in loadMetadataForTable", error);}diff --git a/frontend/src/metabase/redux/entities.js b/frontend/src/metabase/redux/entities.jsindex 1d51679f067..77c3d311dd6 100644--- a/frontend/src/metabase/redux/entities.js+++ b/frontend/src/metabase/redux/entities.js@@ -1,4 +1,5 @@import * as entitiesMap from "metabase/entities";+import { tablesReducer } from "metabase/entities/tables-reducer";import { combineEntities } from "metabase/entities/utils";import { PLUGIN_ENTITIES } from "metabase/plugins";@@ -7,8 +8,10 @@ const entitiesArray = Object.values({...PLUGIN_ENTITIES.entities,});-export const { entities, reducer, requestsReducer } =- combineEntities(entitiesArray);+export const { entities, reducer, requestsReducer } = combineEntities(+ entitiesArray,+ { tables: tablesReducer },+);// eslint-disable-next-line import/no-default-export -- deprecated usageexport default reducer;diff --git a/frontend/src/metabase/redux/metadata.js b/frontend/src/metabase/redux/metadata.jsindex 42a5845119b..ccee4285e44 100644--- a/frontend/src/metabase/redux/metadata.js+++ b/frontend/src/metabase/redux/metadata.js@@ -8,12 +8,13 @@ import {datasetApi,fieldApi,segmentApi,+ tableApi,} from "metabase/api";-import { Tables } from "metabase/entities/tables";import { entityCompatibleQuery } from "metabase/entities/utils";import { isProduction } from "metabase/env";import { createThunkAction } from "metabase/redux";-import { DatabaseSchema, FieldSchema } from "metabase/schema";+import { fetchTableMetadataAndForeignKeys } from "metabase/redux/tables";+import { DatabaseSchema, FieldSchema, TableSchema } from "metabase/schema";import { RevisionsApi } from "metabase/services";import { hasRemappedParameterValues } from "metabase-lib/v1/parameters/utils/parameter-source";import { normalizeParameter } from "metabase-lib/v1/parameters/utils/parameter-values";@@ -84,7 +85,7 @@ export const updateDatabase = (database) => async (dispatch) => {return result;};-export const updateTable = (table) => {+export const updateTable = (table) => async (dispatch) => {deprecated("metabase/redux/metadata updateTable");const slimTable = _.omit(table,@@ -93,13 +94,18 @@ export const updateTable = (table) => {"aggregation_operators","segments",);- return Tables.actions.update(slimTable);+ const result = await entityCompatibleQuery(+ slimTable,+ dispatch,+ tableApi.endpoints.updateTable,+ );+ dispatch(updateMetadata(result, TableSchema));+ return result;};-export { FETCH_TABLE_METADATA } from "metabase/entities/tables";export const fetchTableMetadata = (id, reload = false) => {deprecated("metabase/redux/metadata fetchTableMetadata");- return Tables.actions.fetchMetadataAndForeignTables({ id }, { reload });+ return fetchTableMetadataAndForeignKeys({ id }, { reload });};export const updateFieldValues = (fieldId, fieldValuePairs) => (dispatch) => {diff --git a/frontend/src/metabase/redux/tables.ts b/frontend/src/metabase/redux/tables.tsnew file mode 100644index 00000000000..4b2802af1c9--- /dev/null+++ b/frontend/src/metabase/redux/tables.ts@@ -0,0 +1,118 @@+import { fieldApi, tableApi } from "metabase/api";+import { entityCompatibleQuery } from "metabase/entities/utils";+import { updateMetadata } from "metabase/redux/metadata-typed";+import type { Dispatch, GetState } from "metabase/redux/store";+import { TableSchema } from "metabase/schema";+import { getMetadataUnfiltered } from "metabase/selectors/metadata";+import type { FieldId, TableId } from "metabase-types/api";++type FetchOptions = {+ reload?: boolean;+ params?: Record<string, unknown>;+};++// Minimal structural view of a table's foreign-key-bearing fields. Avoids+// pulling the heavy `Table` class type into this module's inference, which keeps+// the project under TypeScript's instantiation-depth limit.+type ForeignKeyField = {+ target?: { table_id?: TableId } | null;+ fk_target_field_id?: FieldId | null;+};+type ForeignKeyHost =+ | { fields?: ForeignKeyField[]; fks?: unknown[] }+ | null+ | undefined;++/**+ * Loads `query_metadata` for a single table, so `getMetadata` can read it.+ * Replaces the `Tables.actions.fetchMetadata` entity action.+ *+ * Normalization into `state.entities` happens in the endpoint's own+ * `onQueryStarted` (it dispatches `updateMetadata(data, TableSchema)`), so this+ * thunk just initiates the request and returns the unwrapped result.+ */+export const fetchTableMetadata =+ (+ { id, ...params }: { id: TableId; [key: string]: unknown },+ options: FetchOptions = {},+ ) =>+ async (dispatch: Dispatch) =>+ entityCompatibleQuery(+ { id, ...params, ...options.params },+ dispatch,+ tableApi.endpoints.getTableQueryMetadata,+ { forceRefetch: options.reload ?? false },+ );++/**+ * Loads a table's foreign keys and normalizes them onto the table in+ * `state.entities`. Replaces the `Tables.actions.fetchForeignKeys` entity+ * action.+ */+export const fetchTableForeignKeys =+ ({ id }: { id: TableId }) =>+ async (dispatch: Dispatch, getState: GetState) => {+ // Already loaded — skip, so callers that fire this from an effect don't+ // churn the store on every re-render (mirrors the cached entity action).+ const table = getMetadataUnfiltered(getState()).table(id) as ForeignKeyHost;+ if (table?.fks != null) {+ return { id, fks: table.fks };+ }+ const fks = await entityCompatibleQuery(+ id,+ dispatch,+ tableApi.endpoints.listTableForeignKeys,+ { forceRefetch: false },+ );+ dispatch(updateMetadata({ id, fks }, TableSchema));+ return { id, fks };+ };++/**+ * Loads a table's metadata along with the metadata of any tables/fields it+ * links to via foreign key. Replaces the+ * `Tables.actions.fetchMetadataAndForeignTables` entity action.+ */+export const fetchTableMetadataAndForeignKeys =+ ({ id }: { id: TableId }, options: FetchOptions = {}) =>+ async (dispatch: Dispatch, getState: GetState) => {+ await dispatch(fetchTableMetadata({ id }, options));++ const table = getMetadataUnfiltered(getState()).table(id) as ForeignKeyHost;+ await Promise.all([+ ...getTableForeignKeyTableIds(table).map((tableId) =>+ dispatch(fetchTableMetadata({ id: tableId }, options)),+ ),+ // overridden model FK columns have fk_target_field_id but don't have a+ // target — in this case we load the field instead of the table+ ...getTableForeignKeyFieldIds(table).map((fieldId) =>+ entityCompatibleQuery(+ { id: fieldId },+ dispatch,+ fieldApi.endpoints.getField,+ { forceRefetch: options.reload ?? false },+ ),+ ),+ ]);+ };++function getTableForeignKeyTableIds(table: ForeignKeyHost): TableId[] {+ const tableIds: TableId[] = [];+ for (const field of table?.fields ?? []) {+ const tableId = field.target?.table_id;+ if (tableId != null) {+ tableIds.push(tableId);+ }+ }+ return Array.from(new Set(tableIds));+}++function getTableForeignKeyFieldIds(table: ForeignKeyHost): FieldId[] {+ const fieldIds: FieldId[] = [];+ for (const field of table?.fields ?? []) {+ if (field.target == null && field.fk_target_field_id != null) {+ fieldIds.push(field.fk_target_field_id);+ }+ }+ return Array.from(new Set(fieldIds));+}diff --git a/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetail.tsx b/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetail.tsxindex 742da224142..fd4da299bf3 100644--- a/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetail.tsx+++ b/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetail.tsx@@ -1,4 +1,3 @@-import { Tables } from "metabase/entities/tables";import {closeObjectDetail,followForeignKey,@@ -19,6 +18,7 @@ import {} from "metabase/query_builder/selectors";import { connect } from "metabase/redux";import type { State } from "metabase/redux/store";+import { fetchTableForeignKeys } from "metabase/redux/tables";import { getUser } from "metabase/selectors/user";import type ForeignKey from "metabase-lib/v1/metadata/ForeignKey";@@ -61,8 +61,7 @@ type MapStateProps = ReturnType<typeof mapStateToProps>;// ugh, using function form of mapDispatchToProps here due to circlular dependency with actionsconst mapDispatchToProps = (dispatch: any) => ({- fetchTableFks: (id: number) =>- dispatch(Tables.objectActions.fetchForeignKeys({ id })),+ fetchTableFks: (id: number) => dispatch(fetchTableForeignKeys({ id })),loadObjectDetailFKReferences: (args: any) =>dispatch(loadObjectDetailFKReferences(args)),followForeignKey: ({