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
Move the entities store into the metadata module and hide normalizr (#81290)
Romeo Van Snick577f242c41a6
diff --git a/frontend/lint/module-boundaries.mjs b/frontend/lint/module-boundaries.mjsindex 3a366a1f498..66cd3c75d2c 100644--- a/frontend/lint/module-boundaries.mjs+++ b/frontend/lint/module-boundaries.mjs@@ -240,13 +240,6 @@ const elements = [createElement({ type: "shared", name: "redux", enforceSharedTiers: false }),createElement({ type: "shared", name: "rich_text_editing" }),createElement({ type: "shared", name: "route-guards" }),- createElement({- type: "shared",- name: "schema",- pattern: "frontend/src/metabase/schema.ts",- mode: "full",- enforceSharedTiers: false,- }),createElement({ type: "shared", name: "selectors" }),createElement({ type: "shared", name: "settings", enforcePublicApi: true }),createElement({ type: "feature", name: "setup" }),diff --git a/frontend/lint/shared-tiers.mjs b/frontend/lint/shared-tiers.mjsindex 41a8c77e036..ee626e0889d 100644--- a/frontend/lint/shared-tiers.mjs+++ b/frontend/lint/shared-tiers.mjs@@ -11,12 +11,7 @@const SHARED_UTILS_LEVELS = [// U0 — foundation: leaf plumbing.- [- "shared/schema",- "shared/urls",- "shared/styled-components",- "shared/cljs-dev-tools",- ],+ ["shared/urls", "shared/styled-components", "shared/cljs-dev-tools"],// U1 — the api client.["shared/api"],// U2 — the store slices and hooks.diff --git a/frontend/lint/side-effect-files.json b/frontend/lint/side-effect-files.jsonindex 378f54e317d..f430f96dcc6 100644--- a/frontend/lint/side-effect-files.json+++ b/frontend/lint/side-effect-files.json@@ -144,6 +144,7 @@"frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPromptWidget.tsx": "self","frontend/src/metabase/metabot/components/editor-extensions/MetabotEmbed/MetabotEmbed.tsx": "self","frontend/src/metabase/metabot/components/editor-extensions/MetabotMention/MetabotMentionExtension.tsx": "self",+ "frontend/src/metabase/metadata-store/schema.ts": "self","frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/errorHighlight.ts": "self","frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/metricTokenHighlight.ts": "self","frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/operatorHighlight.ts": "self",@@ -179,7 +180,6 @@"frontend/src/metabase/rich_text_editing/tiptap/extensions/SupportingText/SupportingText.tsx": "self","frontend/src/metabase/routes-public.tsx": "self","frontend/src/metabase/routes.tsx": "entry",- "frontend/src/metabase/schema.ts": "self","frontend/src/metabase/setup/components/InviteUserForm/InviteUserForm.tsx": "self","frontend/src/metabase/setup/components/LicenseTokenStep/constants.tsx": "self","frontend/src/metabase/setup/components/UserForm/UserForm.tsx": "self",diff --git a/frontend/src/embedding-sdk-bundle/lib/sdk-question/load-question.ts b/frontend/src/embedding-sdk-bundle/lib/sdk-question/load-question.tsindex dc9896ea60a..a82f9b68c86 100644--- a/frontend/src/embedding-sdk-bundle/lib/sdk-question/load-question.ts+++ b/frontend/src/embedding-sdk-bundle/lib/sdk-question/load-question.ts@@ -7,14 +7,12 @@ import type {LoadSdkQuestionParams,SdkQuestionState,} from "embedding-sdk-bundle/types/question";-import { getMetadata } from "metabase/metadata-store";+import { getMetadata, paramFieldsFetched } from "metabase/metadata-store";import {getParameterValuesForQuestion,resolveCards,} from "metabase/query_builder";import { loadMetadataForCard } from "metabase/questions/actions";-import { updateMetadata } from "metabase/redux/metadata";-import { FieldSchema } from "metabase/schema";import Question from "metabase-lib/v1/Question";import type { SeriesCard } from "metabase-types/api";import type { EntityToken } from "metabase-types/api/entity";@@ -95,9 +93,7 @@ export const loadQuestionSdk =if ("param_fields" in card && card.param_fields) {// This is needed to make some parameter widget populate the dropdown list// otherwise they will use a normal text input- dispatch(- updateMetadata(Object.values(card.param_fields).flat(), [FieldSchema]),- );+ dispatch(paramFieldsFetched(card.param_fields));}return { question, originalQuestion, parameterValues };diff --git a/frontend/src/metabase-lib/v1/metadata/utils/saved-questions.ts b/frontend/src/metabase-lib/v1/metadata/utils/saved-questions.tsindex b2125b1fd14..645fffaeecd 100644--- a/frontend/src/metabase-lib/v1/metadata/utils/saved-questions.ts+++ b/frontend/src/metabase-lib/v1/metadata/utils/saved-questions.ts@@ -79,7 +79,7 @@ export function convertSavedQuestionToVirtualTable(card: ConvertibleCard) {moderated_status: card.moderated_status,// we may not have permissionsdb_id: card.dataset_query?.database,- type: "question",+ type: "question" as const,schema: getCollectionVirtualSchemaId(card.collection),schema_name: getCollectionVirtualSchemaName(card.collection),};diff --git a/frontend/src/metabase/admin/databases/database.ts b/frontend/src/metabase/admin/databases/database.tsindex c5f38216694..46d2bd7e972 100644--- a/frontend/src/metabase/admin/databases/database.ts+++ b/frontend/src/metabase/admin/databases/database.ts@@ -2,12 +2,11 @@ import { createAction, createReducer } from "@reduxjs/toolkit";import { databaseApi } from "metabase/api";import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";+import { databaseFetched } from "metabase/metadata-store";import { combineReducers } from "metabase/redux";import { createDatabase } from "metabase/redux/databases";-import { updateMetadata } from "metabase/redux/metadata";import type { Dispatch } from "metabase/redux/store";import { navigate } from "metabase/router";-import { DatabaseSchema } from "metabase/schema";import type { DatabaseData, DatabaseId } from "metabase-types/api";const DELETE_DATABASE = createAction<{ databaseId: DatabaseId }>(@@ -28,7 +27,7 @@ export const updateDatabase = function (database: DatabaseData) {dispatch,databaseApi.endpoints.updateDatabase,);- dispatch(updateMetadata(result, DatabaseSchema));+ dispatch(databaseFetched(result));return result;};};diff --git a/frontend/src/metabase/collections/components/CollectionCopyEntityModal.tsx b/frontend/src/metabase/collections/components/CollectionCopyEntityModal.tsxindex ef7ea18f9cf..27b998cacd5 100644--- a/frontend/src/metabase/collections/components/CollectionCopyEntityModal.tsx+++ b/frontend/src/metabase/collections/components/CollectionCopyEntityModal.tsx@@ -8,7 +8,7 @@ import {} from "metabase/api";import { useInitialCollectionId } from "metabase/common/collections/hooks";import { CopyModal } from "metabase/common/components/CopyModal";-import { entityTypeForObject } from "metabase/redux/store/entities";+import { entityTypeForObject } from "metabase/metadata-store";const getTitle = (entityObject: any, isShallowCopy: boolean) => {if (entityObject.model !== "dashboard") {diff --git a/frontend/src/metabase/dashboard/actions/data-fetching.ts b/frontend/src/metabase/dashboard/actions/data-fetching.tsindex 27d55e90696..f5aa027dbaa 100644--- a/frontend/src/metabase/dashboard/actions/data-fetching.ts+++ b/frontend/src/metabase/dashboard/actions/data-fetching.ts@@ -33,19 +33,17 @@ import {getAllDashboardCards,getCurrentTabDashboardCards,} from "metabase/dashboard/utils";-import { getMetadata } from "metabase/metadata-store";+import { getMetadata, paramFieldsFetched } from "metabase/metadata-store";import { getSavedDashboardUiParameters } from "metabase/parameters/utils/dashboards";import { getParameterValuesByIdFromQueryParams } from "metabase/parameters/utils/parameter-parsing";import { makePivotAwareQueryRunner } from "metabase/querying/api/query-endpoints";import { runAdhocDatasetQuery } from "metabase/querying/run-query";-import { updateMetadata } from "metabase/redux/metadata";import type {DashboardLinkTargets,Dispatch,GetState,} from "metabase/redux/store";import { createAsyncThunk, createThunkAction } from "metabase/redux/utils";-import { FieldSchema } from "metabase/schema";import {getDashboardType,isQuestionDashCard,@@ -893,11 +891,7 @@ export const fetchDashboard = createAsyncThunk(}if (result.param_fields) {- await dispatch(- updateMetadata(Object.values(result.param_fields).flat(), [- FieldSchema,- ]),- );+ await dispatch(paramFieldsFetched(result.param_fields));}const lastUsedParametersValues = result["last_used_param_values"] ?? {};diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-available-parameters.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-available-parameters.tsindex 181fbc9f3e9..c7cde68e3ec 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-available-parameters.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-available-parameters.ts@@ -2,11 +2,9 @@ import { useEffect, useMemo, useRef } from "react";import { useLatest, usePrevious } from "react-use";import type { SdkIframeEmbedSetupExperience } from "metabase/embedding/embedding-iframe-sdk-setup/types";-import { getMetadata } from "metabase/metadata-store";+import { getMetadata, paramFieldsFetched } from "metabase/metadata-store";import { getSavedDashboardUiParameters } from "metabase/parameters/utils/dashboards";import { useDispatch, useSelector } from "metabase/redux";-import { updateMetadata } from "metabase/redux/metadata";-import { FieldSchema } from "metabase/schema";import { getCardUiParameters } from "metabase-lib/v1/parameters/utils/cards";import type { Card, Dashboard, Parameter } from "metabase-types/api";@@ -69,11 +67,7 @@ export const useAvailableParameters = ({if (resource && "param_fields" in resource && resource.param_fields) {// This is needed to make some parameter widget populate the dropdown list// otherwise they will use a normal text input- dispatch(- updateMetadata(Object.values(resource.param_fields).flat(), [- FieldSchema,- ]),- );+ dispatch(paramFieldsFetched(resource.param_fields));}}, [resource, dispatch]);diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-available-parameters.unit.spec.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-available-parameters.unit.spec.tsindex 9912999c42f..8a84af32abc 100644--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-available-parameters.unit.spec.ts+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-available-parameters.unit.spec.ts@@ -23,19 +23,12 @@ jest.mock("metabase-lib/v1/parameters/utils/cards", () => ({getCardUiParameters: jest.fn(),}));-jest.mock("metabase/redux/metadata", () => ({- updateMetadata: jest.fn((data) => ({- type: "metabase/entities/UPDATE",- payload: data,- })),-}));--jest.mock("metabase/schema", () => ({- FieldSchema: {},-}));-jest.mock("metabase/metadata-store", () => ({getMetadata: jest.fn(),+ paramFieldsFetched: jest.fn((paramFields) => ({+ type: "metabase/entities/UPDATE",+ payload: paramFields,+ })),}));const mockUseSelector = jest.requireMock("metabase/redux").useSelector;@@ -321,7 +314,7 @@ describe("useAvailableParameters", () => {});describe("param_fields handling", () => {- it("should dispatch updateMetadata when resource has param_fields", () => {+ it("should mirror the param_fields the resource carries", () => {const dashboardWithParamFields = {...mockDashboard,param_fields: {diff --git a/frontend/src/metabase/hoc/Remapped.tsx b/frontend/src/metabase/hoc/Remapped.tsxindex 861bea8dc79..a5fdd92a965 100644--- a/frontend/src/metabase/hoc/Remapped.tsx+++ b/frontend/src/metabase/hoc/Remapped.tsx@@ -1,8 +1,7 @@import { Component, type ComponentType } from "react";-import { getMetadata } from "metabase/metadata-store";+import { fetchRemapping, getMetadata } from "metabase/metadata-store";import { connect } from "metabase/redux";-import { fetchRemapping } from "metabase/redux/remappings";import type { State } from "metabase/redux/store";import type Field from "metabase-lib/v1/metadata/Field";import type Metadata from "metabase-lib/v1/metadata/Metadata";diff --git a/frontend/src/metabase/metadata-store/README.md b/frontend/src/metabase/metadata-store/README.mdnew file mode 100644index 00000000000..dc47e731b15--- /dev/null+++ b/frontend/src/metabase/metadata-store/README.md@@ -0,0 +1,44 @@+# The metadata store++`state.entities` holds one normalized record per database, table, field, and so+on. `getMetadata` builds the metabase-lib v1 `Metadata` object from those+records.++## This store is not a deletable mirror slice++The store doctrine says to delete mirror slices and to read the RTK Query cache+instead. That rule fits a slice which copies one endpoint. The `user` slice is+the example: one endpoint fills it, so a cache read serves it.++This store is different. It folds 34 endpoints into one record per entity, so it+needs a reducer. It is one write path over many sources, not a copy of one+response.++## The slices are the CLJS provider's input format++`parse-metadata` in `src/metabase/lib/js/metadata.cljc` reads eight keys off the+`Metadata` object by string: `databases`, `tables`, `fields`, `snippets`,+`cards`, `measures`, `metrics`, and `segments`.++Two rules follow:++- No slice can be deleted on its own while `getMetadata` feeds+ `Lib.metadataProvider`.+- A slice with no JS readers is still live. Search for its key in+ `metadata.cljc` before you call it dead.++## The RTK Query cache is not a drop-in for an accumulator++RTK Query removes a cache entry 60 seconds after its last subscriber unmounts.+`runRtkEndpoint` unsubscribes as soon as the request resolves.++A reader whose data must outlive its own fetch needs owned state, not a cache+read. The `dashboards` slice is the worked example. Both of its readers depended+on the accumulator, so neither could move to a cache read.++## One write door++`hydration.ts` holds the only writer. Every hydrating endpoint flows through it.++That single door is the seam for a later swap to a CLJS-backed store. Keep it+single.diff --git a/frontend/src/metabase/metadata-store/actions.ts b/frontend/src/metabase/metadata-store/actions.tsnew file mode 100644index 00000000000..f6075ca7ddb--- /dev/null+++ b/frontend/src/metabase/metadata-store/actions.ts@@ -0,0 +1,60 @@+import { type Schema, normalize } from "normalizr";++import type {+ Database,+ Field,+ FieldId,+ FieldValue,+ ForeignKey,+ Table,+ TableId,+} from "metabase-types/api";++import { DatabaseSchema, FieldSchema, TableSchema } from "./schema";++const UPDATE = "metabase/entities/UPDATE";++/**+ * Normalizes an entity, or a list of them, into `state.entities`.+ *+ * Module-private: the barrel does not re-export it. normalizr is how this+ * module stores records, not something its callers should have to know, so the+ * writes below name what they carry and pick their own schema. The hydration+ * listener is the other caller, and it lives in here.+ */+export function updateMetadata(data: unknown, schema: Schema) {+ const payload = normalize(data, schema);+ return { type: UPDATE, payload };+}++/**+ * The fields a card or dashboard names in its parameters, keyed by parameter.+ *+ * Widgets read these to decide whether a parameter gets a value picker or a+ * plain text input, and the endpoints that return them do not hydrate.+ */+export const paramFieldsFetched = (paramFields: Record<string, Field[]>) =>+ updateMetadata(Object.values(paramFields).flat(), [FieldSchema]);++export const databaseFetched = (database: Database) =>+ updateMetadata(database, DatabaseSchema);++export const tableFetched = (table: Table) =>+ updateMetadata(table, TableSchema);++export const fieldFetched = (field: Field) =>+ updateMetadata(field, FieldSchema);++/**+ * `listTableForeignKeys` returns the keys alone, so they are attached to the+ * table the caller asked about.+ */+export const tableForeignKeysFetched = (id: TableId, fks: ForeignKey[]) =>+ updateMetadata({ id, fks }, TableSchema);++/**+ * A field's remappings accumulate on the client. No endpoint returns them, and+ * one component's fetch labels values for another.+ */+export const fieldRemappingsUpdated = (id: FieldId, remappings: FieldValue[]) =>+ updateMetadata({ id, remappings }, FieldSchema);diff --git a/frontend/src/metabase/redux/entities/entities.unit.spec.ts b/frontend/src/metabase/metadata-store/entities.unit.spec.tssimilarity index 97%rename from frontend/src/metabase/redux/entities/entities.unit.spec.tsrename to frontend/src/metabase/metadata-store/entities.unit.spec.tsindex a5812f8bcee..d138621f905 100644--- a/frontend/src/metabase/redux/entities/entities.unit.spec.ts+++ b/frontend/src/metabase/metadata-store/entities.unit.spec.ts@@ -1,4 +1,4 @@-import { reducer } from "./index";+import { entitiesReducer as reducer } from "./index";const update = (fields: Record<string, unknown>) => ({type: "metabase/entities/UPDATE",diff --git a/frontend/src/metabase/metadata-store/entity-types.ts b/frontend/src/metabase/metadata-store/entity-types.tsnew file mode 100644index 00000000000..24d3b1cecc9--- /dev/null+++ b/frontend/src/metabase/metadata-store/entity-types.ts@@ -0,0 +1,15 @@+/**+ * The slice a model's records live in. The backend says "card" where the mirror+ * keys them under "questions".+ */+export const entityTypeForModel = (model: string): string => {+ if (model === "card" || model === "dataset" || model === "metric") {+ return "questions";+ }+ return `${model}s`;+};++export const entityTypeForObject = (+ object?: { model: string } | null,+): string | undefined =>+ object ? entityTypeForModel(object.model) : undefined;diff --git a/frontend/src/metabase/redux/store/entities.unit.spec.ts b/frontend/src/metabase/metadata-store/entity-types.unit.spec.tssimilarity index 99%rename from frontend/src/metabase/redux/store/entities.unit.spec.tsrename to frontend/src/metabase/metadata-store/entity-types.unit.spec.tsindex 3c08b0d2fb2..41c2f41484a 100644--- a/frontend/src/metabase/redux/store/entities.unit.spec.ts+++ b/frontend/src/metabase/metadata-store/entity-types.unit.spec.ts@@ -1,4 +1,4 @@-import { entityTypeForModel, entityTypeForObject } from "./entities";+import { entityTypeForModel, entityTypeForObject } from "./entity-types";const MODEL_ENTITY_TYPE = [{ model: "card", entityType: "questions" },diff --git a/frontend/src/metabase/redux/entities/hydration.ts b/frontend/src/metabase/metadata-store/hydration.tssimilarity index 98%rename from frontend/src/metabase/redux/entities/hydration.tsrename to frontend/src/metabase/metadata-store/hydration.tsindex d74527cbf48..53f584f2882 100644--- a/frontend/src/metabase/redux/entities/hydration.ts+++ b/frontend/src/metabase/metadata-store/hydration.ts@@ -15,7 +15,10 @@ import {snippetApi,tableApi,} from "metabase/api";-import { updateMetadata } from "metabase/redux/metadata";+import { generateSchemaId } from "metabase-lib/v1/metadata/utils/schema";+import type { DatabaseId, SchemaName } from "metabase-types/api";++import { updateMetadata } from "./actions";import {DatabaseSchema,FieldSchema,@@ -29,9 +32,7 @@ import {SegmentSchema,SnippetSchema,TableSchema,-} from "metabase/schema";-import { generateSchemaId } from "metabase-lib/v1/metadata/utils/schema";-import type { DatabaseId, SchemaName } from "metabase-types/api";+} from "./schema";/*** The part of an RTK Query endpoint a rule needs. Structural, so a real@@ -107,6 +108,7 @@ const HYDRATION_RULES: HydrationRule[] = [hydrates(databaseApi.endpoints.listDatabaseSchemaTables, [TableSchema]),hydrates(databaseApi.endpoints.listVirtualDatabaseTables, [TableSchema]),hydrates(databaseApi.endpoints.listDatabaseIdFields, [FieldSchema]),+ hydrates(databaseApi.endpoints.createDatabase, DatabaseSchema),hydrates(tableApi.endpoints.listTables, [TableSchema]),hydrates(tableApi.endpoints.getTable, TableSchema),diff --git a/frontend/src/metabase/redux/entities/hydration.unit.spec.ts b/frontend/src/metabase/metadata-store/hydration.unit.spec.tssimilarity index 99%rename from frontend/src/metabase/redux/entities/hydration.unit.spec.tsrename to frontend/src/metabase/metadata-store/hydration.unit.spec.tsindex 4de855e27e0..d5f262ea600 100644--- a/frontend/src/metabase/redux/entities/hydration.unit.spec.ts+++ b/frontend/src/metabase/metadata-store/hydration.unit.spec.ts@@ -17,6 +17,7 @@ import {*/const HYDRATING_ENDPOINTS = ["createCard",+ "createDatabase","createSnippet","getAdhocQueryMetadata","getCard",diff --git a/frontend/src/metabase/metadata-store/index.ts b/frontend/src/metabase/metadata-store/index.tsindex a6802ff8674..c8100c7592e 100644--- a/frontend/src/metabase/metadata-store/index.ts+++ b/frontend/src/metabase/metadata-store/index.ts@@ -1,16 +1,5 @@-/**- * The public face of the metadata mirror.- *- * `state.entities` holds one normalized record per database, table, field and- * so on, merged from many endpoints. Everything outside this folder reads it- * through the selectors below, and `metabase/enforce-module-public-api` rejects- * a deeper import.- *- * `getMetadata` builds the metabase-lib v1 `Metadata` object. It is the input- * format the CLJS provider parses, so it stays until that provider does.- */-export type { MetadataSelectorOpts } from "./selectors";export {+ getFieldRemappings,getMetadata,getMetadataUnfiltered,getMetadataWithHiddenTables,@@ -19,3 +8,24 @@ export {getShallowSegments,getShallowTables,} from "./selectors";+export type { MetadataSelectorOpts } from "./selectors";++export { entitiesReducer } from "./reducer";++export { metadataHydrationMiddleware } from "./hydration";++export { addRemappings, fetchRemapping } from "./remappings";++export {+ databaseFetched,+ fieldFetched,+ fieldRemappingsUpdated,+ paramFieldsFetched,+ tableFetched,+ tableForeignKeysFetched,+} from "./actions";++export { entityTypeForModel, entityTypeForObject } from "./entity-types";++export { createMockEntitiesState } from "./mocks";+export type { EntitiesStateOpts } from "./mocks";diff --git a/frontend/src/metabase/metadata-store/mocks.ts b/frontend/src/metabase/metadata-store/mocks.tsnew file mode 100644index 00000000000..c59d2f5e553--- /dev/null+++ b/frontend/src/metabase/metadata-store/mocks.ts@@ -0,0 +1,77 @@+import { type Schema as NormalizrSchema, normalize } from "normalizr";++import type { EntitiesState } from "metabase/redux/store";+import type {+ Card,+ Database,+ Field,+ Measure,+ NativeQuerySnippet,+ SavedQuestionDatabase,+ Schema,+ Segment,+ Table,+ User,+} from "metabase-types/api";++import {+ DatabaseSchema,+ FieldSchema,+ MeasureSchema,+ MetricSchema,+ QuestionSchema,+ SchemaSchema,+ SegmentSchema,+ SnippetSchema,+ TableSchema,+} from "./schema";++export interface EntitiesStateOpts {+ databases?: (Database | SavedQuestionDatabase)[];+ schemas?: Schema[];+ tables?: Table[];+ fields?: Field[];+ segments?: Segment[];+ measures?: Measure[];+ snippets?: NativeQuerySnippet[];+ users?: User[];+ questions?: Card[];+}++const EntitiesSchema: Record<keyof EntitiesState, NormalizrSchema<any>> = {+ databases: [DatabaseSchema],+ schemas: [SchemaSchema],+ tables: [TableSchema],+ fields: [FieldSchema],+ segments: [SegmentSchema],+ measures: [MeasureSchema],+ metrics: [MetricSchema],+ snippets: [SnippetSchema],+ questions: [QuestionSchema],+};++const emptyEntitiesState = (): EntitiesState => ({+ databases: {},+ schemas: {},+ tables: {},+ fields: {},+ segments: {},+ measures: {},+ metrics: {},+ snippets: {},+ questions: {},+});++/**+ * A fixture of the mirror's normalized shape, built from plain API entities.+ *+ * It lives in the module because normalizing is what the schemas do, and they+ * are private. `__support__/store` re-exports it, which is where specs take it+ * from.+ */+export const createMockEntitiesState = (+ opts: EntitiesStateOpts,+): EntitiesState => ({+ ...emptyEntitiesState(),+ ...normalize(opts, EntitiesSchema).entities,+});diff --git a/frontend/src/metabase/redux/entities/index.ts b/frontend/src/metabase/metadata-store/reducer.tssimilarity index 85%rename from frontend/src/metabase/redux/entities/index.tsrename to frontend/src/metabase/metadata-store/reducer.tsindex c492fc9f8fc..8a4771703c7 100644--- a/frontend/src/metabase/redux/entities/index.ts+++ b/frontend/src/metabase/metadata-store/reducer.ts@@ -10,11 +10,10 @@ type SliceAction = { type: string; payload?: any };type SliceReducer = Reducer<SliceState>;/**- * Slices held under `state.entities.<name>`. These used to be wired up by the- * (now-removed) entity framework via `createEntity`; the slices themselves- * still exist because `getMetadata` in `metabase/metadata-store.ts` reads- * directly from them. `metadataHydrationMiddleware` in `./hydration` is the- * only writer, and populates them by dispatching `metabase/entities/UPDATE`.+ * Slices held under `state.entities.<name>`. `getMetadata` reads them directly.+ *+ * `metadataHydrationMiddleware` in `./hydration` is the only writer, and fills+ * them by dispatching `metabase/entities/UPDATE`.*/const ENTITY_SLICE_NAMES = ["databases",@@ -117,7 +116,4 @@ const sliceReducers = Object.fromEntries(]),) as Record<(typeof ENTITY_SLICE_NAMES)[number], SliceReducer>;-export const reducer = combineReducers(sliceReducers);--// eslint-disable-next-line import/no-default-export -- deprecated usage-export default reducer;+export const entitiesReducer = combineReducers(sliceReducers);diff --git a/frontend/src/metabase/redux/entities/index.unit.spec.ts b/frontend/src/metabase/metadata-store/reducer.unit.spec.tssimilarity index 98%rename from frontend/src/metabase/redux/entities/index.unit.spec.tsrename to frontend/src/metabase/metadata-store/reducer.unit.spec.tsindex be857dded0f..18a89ce1ea2 100644--- a/frontend/src/metabase/redux/entities/index.unit.spec.ts+++ b/frontend/src/metabase/metadata-store/reducer.unit.spec.ts@@ -1,4 +1,4 @@-import { reducer } from "./index";+import { entitiesReducer as reducer } from "./index";const UPDATE = "metabase/entities/UPDATE";diff --git a/frontend/src/metabase/redux/remappings.ts b/frontend/src/metabase/metadata-store/remappings.tssimilarity index 94%rename from frontend/src/metabase/redux/remappings.tsrename to frontend/src/metabase/metadata-store/remappings.tsindex dc2f25be250..a9a046a41bb 100644--- a/frontend/src/metabase/redux/remappings.ts+++ b/frontend/src/metabase/metadata-store/remappings.ts@@ -2,7 +2,6 @@ import { cardApi, dashboardApi, datasetApi } from "metabase/api";import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { createThunkAction } from "metabase/redux";import type { Dispatch, GetState } from "metabase/redux/store";-import { FieldSchema } from "metabase/schema";import type Field from "metabase-lib/v1/metadata/Field";import { hasRemappedParameterValues } from "metabase-lib/v1/parameters/utils/parameter-source";import { normalizeParameter } from "metabase-lib/v1/parameters/utils/parameter-values";@@ -15,7 +14,8 @@ import type {RowValue,} from "metabase-types/api";-import { getFieldRemappings, updateMetadata } from "./metadata";+import { fieldRemappingsUpdated } from "./actions";+import { getFieldRemappings } from "./selectors";export const addRemappings =(fieldId: FieldId, remappings: FieldValue[]) =>@@ -31,9 +31,7 @@ export const addRemappings =]),).values(),);- return dispatch(- updateMetadata({ id: fieldId, remappings: merged }, FieldSchema),- );+ return dispatch(fieldRemappingsUpdated(fieldId, merged));};type FetchRemappingOptions = {diff --git a/frontend/src/metabase/schema.ts b/frontend/src/metabase/metadata-store/schema.tssimilarity index 98%rename from frontend/src/metabase/schema.tsrename to frontend/src/metabase/metadata-store/schema.tsindex a3c505b20f7..2682c84ffe5 100644--- a/frontend/src/metabase/schema.ts+++ b/frontend/src/metabase/metadata-store/schema.ts@@ -2,7 +2,6 @@import { schema } from "normalizr";-import { entityTypeForObject } from "metabase/redux/store/entities";import { checkNotNull } from "metabase/utils/types";import { getUniqueFieldId } from "metabase-lib/v1/metadata/utils/fields";import { SAVED_QUESTIONS_VIRTUAL_DB_ID } from "metabase-lib/v1/metadata/utils/saved-questions";@@ -23,6 +22,8 @@ import type {Table,} from "metabase-types/api";+import { entityTypeForObject } from "./entity-types";+export const QuestionSchema = new schema.Entity<Card>("questions");export const CollectionSchema = new schema.Entity<Collection>("collections");diff --git a/frontend/src/metabase/metadata-store/selectors.ts b/frontend/src/metabase/metadata-store/selectors.tsindex 34217e05622..7bac505dd61 100644--- a/frontend/src/metabase/metadata-store/selectors.ts+++ b/frontend/src/metabase/metadata-store/selectors.ts@@ -2,7 +2,6 @@ import { createSelector } from "@reduxjs/toolkit";import { normalize } from "normalizr";import type { State } from "metabase/redux/store";-import { type FieldEntity, FieldSchema } from "metabase/schema";import { getSettings } from "metabase/settings";import Question from "metabase-lib/v1/Question";import Database from "metabase-lib/v1/metadata/Database";@@ -19,6 +18,8 @@ import {import type {Table as ApiTable,Card,+ FieldId,+ FieldValue,Measure,Metric,NormalizedDatabase,@@ -32,6 +33,8 @@ import type {Segment,} from "metabase-types/api";+import { type FieldEntity, FieldSchema } from "./schema";+type TableSelectorOpts = {includeHiddenTables?: boolean;};@@ -439,3 +442,15 @@ function hydrateMeasureTable(} = normalized;return { ...rest, schema: schema_name ?? "" };}++/**+ * A field's client-accumulated remappings. No endpoint returns these: they are+ * merged in as values are fetched, and one component's fetch labels values for+ * another, so a component cannot answer this from its own result.+ */+export function getFieldRemappings(+ state: State,+ fieldId: FieldId,+): FieldValue[] {+ return state.entities.fields[fieldId]?.remappings ?? [];+}diff --git a/frontend/src/metabase/redux/entities/tables-reducer.ts b/frontend/src/metabase/metadata-store/tables-reducer.tssimilarity index 94%rename from frontend/src/metabase/redux/entities/tables-reducer.tsrename to frontend/src/metabase/metadata-store/tables-reducer.tsindex 64cfeda73c3..a936c22982a 100644--- a/frontend/src/metabase/redux/entities/tables-reducer.ts+++ b/frontend/src/metabase/metadata-store/tables-reducer.ts@@ -14,15 +14,13 @@ type ReducerAction = { type: string; payload?: any; error?: unknown };/*** Reducer for the `state.entities.tables` slice.*- * Tables no longer go through the entity framework — CRUD lives in- * `metabase/api/table`. The slice itself is still consumed by `getMetadata` in- * `metabase/metadata-store.ts`, so we keep it in sync when:+ * `getMetadata` reads this slice, so it is kept in sync when:** - questions are created/updated/archived (the saved-question virtual table* `card__<id>` representation needs to track them), and* - a field is updated elsewhere (so `original_fields` doesn't go stale).*- * It runs after the generic slice reducer in `./index` has merged any+ * It runs after the generic slice reducer in `./reducer` has merged any* `payload.entities.tables` from `metabase/entities/*` actions.*/export function tablesReducer(diff --git a/frontend/src/metabase/redux/entities/tables-reducer.unit.spec.ts b/frontend/src/metabase/metadata-store/tables-reducer.unit.spec.tssimilarity index 100%rename from frontend/src/metabase/redux/entities/tables-reducer.unit.spec.tsrename to frontend/src/metabase/metadata-store/tables-reducer.unit.spec.tsdiff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsx b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsxindex 1429e464d6d..34b70a875a1 100644--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsx+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsx@@ -23,14 +23,13 @@ import { useTranslateContent } from "metabase/content-translation/hooks";import type { ContentTranslationFunction } from "metabase/content-translation/types";import CS from "metabase/css/core/index.css";import { useEmbeddingEntityContext } from "metabase/embedding/context";-import { getMetadata } from "metabase/metadata-store";+import { addRemappings, getMetadata } from "metabase/metadata-store";import {fetchCardParameterValues,fetchDashboardParameterValues,fetchParameterValues,} from "metabase/parameters/actions";import { connect, useDispatch } from "metabase/redux";-import { addRemappings } from "metabase/redux/remappings";import type { State } from "metabase/redux/store";import {Autocomplete,diff --git a/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion.tsx b/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion.tsxindex 677c727fca4..141729727b5 100644--- a/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion.tsx+++ b/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion.tsx@@ -7,7 +7,7 @@ import { applyParameters } from "metabase/common/utils/card";import { fetchDataOrError } from "metabase/dashboard/utils";import { LocaleProvider } from "metabase/embedding/LocaleProvider";import { EmbeddingEntityContextProvider } from "metabase/embedding/context";-import { getMetadata } from "metabase/metadata-store";+import { getMetadata, paramFieldsFetched } from "metabase/metadata-store";import { getParameterValuesByIdFromQueryParams } from "metabase/parameters/utils/parameter-parsing";import { useEmbedFrameOptions } from "metabase/public/hooks";import { usePublicEndpoints } from "metabase/public/hooks/use-public-endpoints";@@ -15,9 +15,7 @@ import { useSetEmbedFont } from "metabase/public/hooks/use-set-embed-font";import { makePivotAwareQueryRunner } from "metabase/querying/api/query-endpoints";import { useDispatch, useSelector } from "metabase/redux";import { setErrorPage } from "metabase/redux/app";-import { updateMetadata } from "metabase/redux/metadata";import { useLocation, useParams } from "metabase/router";-import { FieldSchema } from "metabase/schema";import { getCanWhitelabel } from "metabase/selectors/whitelabel";import { parseSearchQuery } from "metabase/utils/browser";import { getCardUiParameters } from "metabase-lib/v1/parameters/utils/cards";@@ -79,11 +77,7 @@ export const PublicOrEmbeddedQuestion = () => {}if (card.param_fields) {- await dispatch(- updateMetadata(Object.values(card.param_fields).flat(), [- FieldSchema,- ]),- );+ await dispatch(paramFieldsFetched(card.param_fields));}const parameters = getCardUiParameters(diff --git a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts b/frontend/src/metabase/query_builder/actions/core/initializeQB.tsindex 07552663165..321babd797a 100644--- a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts+++ b/frontend/src/metabase/query_builder/actions/core/initializeQB.ts@@ -6,11 +6,10 @@ import {parseHash,} from "metabase/common/utils/card";import { canUserCreateQueries, getUser } from "metabase/current-user";-import { getMetadata } from "metabase/metadata-store";+import { getMetadata, paramFieldsFetched } from "metabase/metadata-store";import { loadMetadataForCard } from "metabase/questions/actions";import { setErrorPage } from "metabase/redux/app";import type { DispatchFn } from "metabase/redux/hooks";-import { updateMetadata } from "metabase/redux/metadata";import { INITIALIZE_QB } from "metabase/redux/query-builder";import type {Dispatch,@@ -20,7 +19,6 @@ import type {import { fetchTableMetadataAndForeignKeys } from "metabase/redux/tables";import type { Location } from "metabase/router";import { navigate } from "metabase/router";-import { FieldSchema } from "metabase/schema";import * as Urls from "metabase/urls";import { parseSearchQuery } from "metabase/utils/browser";import { isNotNull } from "metabase/utils/types";@@ -404,9 +402,7 @@ async function handleQBInit(// This ensures field filter widgets have has_field_values even when the user// lacks create-queries permission on the underlying table (GHY-1605).if (card.param_fields) {- await dispatch(- updateMetadata(Object.values(card.param_fields).flat(), [FieldSchema]),- );+ await dispatch(paramFieldsFetched(card.param_fields));}const metadata = getMetadata(getState());diff --git a/frontend/src/metabase/query_builder/components/view/sidebars/QuestionInfoSidebar/components/QuestionSources.unit.spec.tsx b/frontend/src/metabase/query_builder/components/view/sidebars/QuestionInfoSidebar/components/QuestionSources.unit.spec.tsxindex 84cff58044f..0dc650fb047 100644--- a/frontend/src/metabase/query_builder/components/view/sidebars/QuestionInfoSidebar/components/QuestionSources.unit.spec.tsx+++ b/frontend/src/metabase/query_builder/components/view/sidebars/QuestionInfoSidebar/components/QuestionSources.unit.spec.tsx@@ -11,8 +11,12 @@ import {} from "metabase/redux/store/mocks";import { Route } from "metabase/router";import { convertSavedQuestionToVirtualTable } from "metabase-lib/v1/metadata/utils/saved-questions";-import type { Card, NormalizedTable } from "metabase-types/api";-import { createMockCard, createMockSettings } from "metabase-types/api/mocks";+import type { Card } from "metabase-types/api";+import {+ createMockCard,+ createMockSettings,+ createMockTable,+} from "metabase-types/api/mocks";import {SAMPLE_DB_ID,createSampleDatabase,@@ -29,38 +33,31 @@ const setup = async ({card = createMockCard(),sourceCard,}: SetupOpts = {}) => {+ const sampleDatabase = createSampleDatabase();++ // A card used as a source appears as a virtual table on its own database.+ const database = sourceCard+ ? {+ ...sampleDatabase,+ tables: [+ ...(sampleDatabase.tables ?? []),+ createMockTable({+ ...convertSavedQuestionToVirtualTable(sourceCard),+ db_id: SAMPLE_DB_ID,+ }),+ ],+ }+ : sampleDatabase;+const state = createMockState({qb: createMockQueryBuilderState({ card }),settings: mockSettings(createMockSettings()),entities: createMockEntitiesState({- databases: [createSampleDatabase()],+ databases: [database],questions: _.compact([card, sourceCard]),}),});- // 😫 all this is necessary to test a card as a question source- if (sourceCard) {- const virtualTable = convertSavedQuestionToVirtualTable(sourceCard);-- state.entities = {- ...state.entities,- tables: {- // Unjustified type cast. FIXME- ...(state.entities.tables as Record<number, NormalizedTable>),- [virtualTable.id]: virtualTable,- },- databases: {- [state.entities.databases[1].id]: {- ...state.entities.databases[1],- tables: [- ...(state.entities.databases[1].tables ?? []),- virtualTable.id,- ],- },- },- };- }-setupListDatabaseSchemasEndpoint(SAMPLE_DB_ID, ["PUBLIC"]);return renderWithProviders(<Route path="/" element={<QuestionSources />} />, {diff --git a/frontend/src/metabase/reducers-common.ts b/frontend/src/metabase/reducers-common.tsindex 41f7227c7af..190b83b246e 100644--- a/frontend/src/metabase/reducers-common.ts+++ b/frontend/src/metabase/reducers-common.ts@@ -6,6 +6,7 @@ import { Api } from "metabase/api";import { dashboardReducers as dashboard } from "metabase/dashboard/reducers";import { documentsReducer as documents } from "metabase/documents/documents.slice";import { explorationsReducer as explorations } from "metabase/explorations/explorations.slice";+import { entitiesReducer } from "metabase/metadata-store";import * as parameters from "metabase/parameters/reducers";import { reducer as analyticsExport } from "metabase/redux/analytics-export";import app from "metabase/redux/app";@@ -13,7 +14,6 @@ import { reducer as auth } from "metabase/redux/auth";import { reducer as downloads } from "metabase/redux/downloads";import { embed } from "metabase/redux/embed";import { reducer as embeddingDataPicker } from "metabase/redux/embedding-data-picker";-import entities from "metabase/redux/entities";import { modal } from "metabase/redux/ui";import { undoReducer as undo } from "metabase/redux/undo";import upload from "metabase/redux/uploads";@@ -26,7 +26,7 @@ export const commonReducers = {embed,embeddingDataPicker,undo,- entities,+ entities: entitiesReducer,documents,upload,analyticsExport,diff --git a/frontend/src/metabase/redux/databases.ts b/frontend/src/metabase/redux/databases.tsindex 1014183f68d..e2f0c9c49af 100644--- a/frontend/src/metabase/redux/databases.ts+++ b/frontend/src/metabase/redux/databases.ts@@ -2,9 +2,7 @@ import _ from "underscore";import { databaseApi } from "metabase/api";import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";-import { updateMetadata } from "metabase/redux/metadata";import type { Dispatch } from "metabase/redux/store";-import { DatabaseSchema } from "metabase/schema";import type { DatabaseData } from "metabase-types/api";export const editParamsForUserControlledScheduling = _.compose(@@ -50,7 +48,6 @@ export const createDatabase = function (inputDatabase: DatabaseData) {dispatch,databaseApi.endpoints.createDatabase,);- dispatch(updateMetadata(savedDatabase, DatabaseSchema));return savedDatabase;} catch (error) {console.error("error creating a database", error);diff --git a/frontend/src/metabase/redux/metadata.ts b/frontend/src/metabase/redux/metadata.tsdeleted file mode 100644index 2dfeed8f387..00000000000--- a/frontend/src/metabase/redux/metadata.ts+++ /dev/null@@ -1,89 +0,0 @@-import { type Schema, normalize } from "normalizr";-import _ from "underscore";--import { databaseApi, fieldApi, segmentApi, tableApi } from "metabase/api";-import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";-import type { Dispatch, State } from "metabase/redux/store";-import { DatabaseSchema, FieldSchema, TableSchema } from "metabase/schema";-import type {- Database,- Field,- FieldId,- FieldValue,- Segment,- Table,-} from "metabase-types/api";--const UPDATE = "metabase/entities/UPDATE";--// Normalizes an entity (or list) and dispatches it into `state.entities`.-// Handled by the per-slice reducers in `metabase/redux/entities` — see-// `makeSliceReducer` there, which merges `payload.entities.<name>` into the-// matching `state.entities.<name>` slice so `getMetadata` picks up the change.-export function updateMetadata(data: unknown, schema: Schema) {- const payload = normalize(data, schema);- return { type: UPDATE, payload };-}--/**- * A field's client-accumulated remappings. No endpoint returns these: they are- * merged in by `addRemappings` as values are fetched, and one component's fetch- * labels values for another, so a component cannot answer this from its own- * result.- */-export function getFieldRemappings(- state: State,- fieldId: FieldId,-): FieldValue[] {- return state.entities.fields[fieldId]?.remappings ?? [];-}--export const updateSegment =- (segment: Segment) =>- (dispatch: Dispatch): Promise<unknown> =>- runRtkEndpoint(segment, dispatch, segmentApi.endpoints.updateSegment);--export const updateDatabase =- (database: Database) =>- async (dispatch: Dispatch): Promise<unknown> => {- const slimDatabase = _.omit(database, "tables", "tables_lookup");- const result: unknown = await runRtkEndpoint(- slimDatabase,- dispatch,- databaseApi.endpoints.updateDatabase,- );- dispatch(updateMetadata(result, DatabaseSchema));- return result;- };--export const updateTable =- (table: Table) =>- async (dispatch: Dispatch): Promise<unknown> => {- const slimTable = _.omit(- table,- "fields",- "fields_lookup",- "aggregation_operators",- "segments",- );- const result: unknown = await runRtkEndpoint(- slimTable,- dispatch,- tableApi.endpoints.updateTable,- );- dispatch(updateMetadata(result, TableSchema));- return result;- };--export const updateField =- (field: Field) =>- async (dispatch: Dispatch): Promise<unknown> => {- const slimField = _.omit(field, "filter_operators_lookup");- const result: unknown = await runRtkEndpoint(- slimField,- dispatch,- fieldApi.endpoints.updateField,- );- dispatch(updateMetadata(result, FieldSchema));- return result;- };diff --git a/frontend/src/metabase/redux/store/entities.ts b/frontend/src/metabase/redux/store/entities.tsindex f0a43a5aeae..0a70a22c6cd 100644--- a/frontend/src/metabase/redux/store/entities.ts+++ b/frontend/src/metabase/redux/store/entities.ts@@ -10,19 +10,6 @@ import type {NormalizedTable,} from "metabase-types/api";-// backend returns model = "card" instead of "question"-export const entityTypeForModel = (model: string): string => {- if (model === "card" || model === "dataset" || model === "metric") {- return "questions";- }- return `${model}s`;-};--export const entityTypeForObject = (- object?: { model: string } | null,-): string | undefined =>- object ? entityTypeForModel(object.model) : undefined;-export interface EntitiesState {databases: Record<string, NormalizedDatabase>;schemas: Record<string, NormalizedSchema>;diff --git a/frontend/src/metabase/redux/tables.ts b/frontend/src/metabase/redux/tables.tsindex ed7f1c9f2e9..1697f49c10f 100644--- a/frontend/src/metabase/redux/tables.ts+++ b/frontend/src/metabase/redux/tables.ts@@ -1,9 +1,10 @@import { fieldApi, tableApi } from "metabase/api";import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";-import { getMetadataUnfiltered } from "metabase/metadata-store";-import { updateMetadata } from "metabase/redux/metadata";+import {+ getMetadataUnfiltered,+ tableForeignKeysFetched,+} from "metabase/metadata-store";import type { Dispatch, GetState } from "metabase/redux/store";-import { TableSchema } from "metabase/schema";import type { FieldId, TableId } from "metabase-types/api";type FetchOptions = {@@ -25,11 +26,9 @@ type ForeignKeyHost =/*** 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.+ * `metadataHydrationMiddleware` mirrors the response into `state.entities`, so+ * this thunk only starts the request and returns the unwrapped result.*/export const fetchTableMetadata =(@@ -46,14 +45,13 @@ export const fetchTableMetadata =/*** Loads a table's foreign keys and normalizes them onto the table in- * `state.entities`. Replaces the `Tables.actions.fetchForeignKeys` entity- * action.+ * `state.entities`.*/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).+ // Already loaded, so callers that fire this from an effect do not churn+ // the store on every re-render.const table = getMetadataUnfiltered(getState()).table(id) as ForeignKeyHost;if (table?.fks != null) {return { id, fks: table.fks };@@ -64,14 +62,13 @@ export const fetchTableForeignKeys =tableApi.endpoints.listTableForeignKeys,{ forceRefetch: false },);- dispatch(updateMetadata({ id, fks }, TableSchema));+ dispatch(tableForeignKeysFetched(id, fks));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.+ * Loads a table's metadata along with the metadata of any tables or fields it+ * links to via foreign key.*/export const fetchTableMetadataAndForeignKeys =({ id }: { id: TableId }, options: FetchOptions = {}) =>diff --git a/frontend/src/metabase/reference/databases/DatabaseDetail.tsx b/frontend/src/metabase/reference/databases/DatabaseDetail.tsxindex 1f61f177234..d8fedcb1c45 100644--- a/frontend/src/metabase/reference/databases/DatabaseDetail.tsx+++ b/frontend/src/metabase/reference/databases/DatabaseDetail.tsx@@ -7,11 +7,11 @@ import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrimport CS from "metabase/css/core/index.css";import { getShallowFields as getFields } from "metabase/metadata-store";import { connect } from "metabase/redux";-import { updateDatabase } from "metabase/redux/metadata";import Detail from "metabase/reference/components/Detail";import { EditHeader } from "metabase/reference/components/EditHeader";import EditableReferenceHeader from "metabase/reference/components/EditableReferenceHeader";import * as actions from "metabase/reference/reference";+import { updateDatabase } from "metabase/reference/update-actions";import type { User } from "metabase-types/api";import type { ReferenceRouteProps, StateWithReference } from "../selectors";diff --git a/frontend/src/metabase/reference/databases/FieldDetail.tsx b/frontend/src/metabase/reference/databases/FieldDetail.tsxindex 856b4ff21ed..e68dbbcd7cd 100644--- a/frontend/src/metabase/reference/databases/FieldDetail.tsx+++ b/frontend/src/metabase/reference/databases/FieldDetail.tsx@@ -6,7 +6,6 @@ import { t } from "ttag";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import CS from "metabase/css/core/index.css";import { connect } from "metabase/redux";-import { updateField } from "metabase/redux/metadata";import S from "metabase/reference/Reference.module.css";import Detail from "metabase/reference/components/Detail";import { EditHeader } from "metabase/reference/components/EditHeader";@@ -14,6 +13,7 @@ import EditableReferenceHeader from "metabase/reference/components/EditableReferimport FieldTypeDetail from "metabase/reference/components/FieldTypeDetail";import UsefulQuestions from "metabase/reference/components/UsefulQuestions";import * as actions from "metabase/reference/reference";+import { updateField } from "metabase/reference/update-actions";import type Metadata from "metabase-lib/v1/metadata/Metadata";import type { FieldId, User } from "metabase-types/api";diff --git a/frontend/src/metabase/reference/databases/FieldList.tsx b/frontend/src/metabase/reference/databases/FieldList.tsxindex 4c67b0fd56f..45c92c0983c 100644--- a/frontend/src/metabase/reference/databases/FieldList.tsx+++ b/frontend/src/metabase/reference/databases/FieldList.tsx@@ -7,7 +7,6 @@ import { EmptyState } from "metabase/common/components/EmptyState";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import CS from "metabase/css/core/index.css";import { connect } from "metabase/redux";-import { updateField } from "metabase/redux/metadata";import R from "metabase/reference/Reference.module.css";import { EditHeader } from "metabase/reference/components/EditHeader";import EditableReferenceHeader from "metabase/reference/components/EditableReferenceHeader";@@ -15,6 +14,7 @@ import Field from "metabase/reference/components/Field";import F from "metabase/reference/components/Field.module.css";import S from "metabase/reference/components/List/List.module.css";import * as actions from "metabase/reference/reference";+import { updateField } from "metabase/reference/update-actions";import { getIconForField } from "metabase-lib/v1/metadata/utils/fields";import type {FieldId,diff --git a/frontend/src/metabase/reference/databases/TableDetail.tsx b/frontend/src/metabase/reference/databases/TableDetail.tsxindex 58b93fa82b9..5e047d7ee33 100644--- a/frontend/src/metabase/reference/databases/TableDetail.tsx+++ b/frontend/src/metabase/reference/databases/TableDetail.tsx@@ -10,13 +10,13 @@ import {getMetadata,} from "metabase/metadata-store";import { connect } from "metabase/redux";-import { updateTable } from "metabase/redux/metadata";import S from "metabase/reference/Reference.module.css";import Detail from "metabase/reference/components/Detail";import { EditHeader } from "metabase/reference/components/EditHeader";import EditableReferenceHeader from "metabase/reference/components/EditableReferenceHeader";import UsefulQuestions from "metabase/reference/components/UsefulQuestions";import * as actions from "metabase/reference/reference";+import { updateTable } from "metabase/reference/update-actions";import type Metadata from "metabase-lib/v1/metadata/Metadata";import type { User } from "metabase-types/api";diff --git a/frontend/src/metabase/reference/segments/SegmentDetail.tsx b/frontend/src/metabase/reference/segments/SegmentDetail.tsxindex 9b08d29bcf1..cf2c85adedf 100644--- a/frontend/src/metabase/reference/segments/SegmentDetail.tsx+++ b/frontend/src/metabase/reference/segments/SegmentDetail.tsx@@ -12,7 +12,6 @@ import {getMetadata,} from "metabase/metadata-store";import { connect } from "metabase/redux";-import { updateSegment } from "metabase/redux/metadata";import Detail from "metabase/reference/components/Detail";import { EditHeader } from "metabase/reference/components/EditHeader";import EditableReferenceHeader from "metabase/reference/components/EditableReferenceHeader";@@ -20,6 +19,7 @@ import { Formula } from "metabase/reference/components/Formula";import { List } from "metabase/reference/components/List";import UsefulQuestions from "metabase/reference/components/UsefulQuestions";import * as actions from "metabase/reference/reference";+import { updateSegment } from "metabase/reference/update-actions";import type Metadata from "metabase-lib/v1/metadata/Metadata";import type { User } from "metabase-types/api";diff --git a/frontend/src/metabase/reference/segments/SegmentFieldDetail.tsx b/frontend/src/metabase/reference/segments/SegmentFieldDetail.tsxindex 1f3480a1650..a36094c1318 100644--- a/frontend/src/metabase/reference/segments/SegmentFieldDetail.tsx+++ b/frontend/src/metabase/reference/segments/SegmentFieldDetail.tsx@@ -7,7 +7,6 @@ import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrimport CS from "metabase/css/core/index.css";import { getMetadata } from "metabase/metadata-store";import { connect } from "metabase/redux";-import { updateField } from "metabase/redux/metadata";import S from "metabase/reference/Reference.module.css";import Detail from "metabase/reference/components/Detail";import { EditHeader } from "metabase/reference/components/EditHeader";@@ -16,6 +15,7 @@ import FieldTypeDetail from "metabase/reference/components/FieldTypeDetail";import { List } from "metabase/reference/components/List";import UsefulQuestions from "metabase/reference/components/UsefulQuestions";import * as actions from "metabase/reference/reference";+import { updateField } from "metabase/reference/update-actions";import type Metadata from "metabase-lib/v1/metadata/Metadata";import type { FieldId, User } from "metabase-types/api";diff --git a/frontend/src/metabase/reference/segments/SegmentFieldList.tsx b/frontend/src/metabase/reference/segments/SegmentFieldList.tsxindex 12545922d07..26192ba6aca 100644--- a/frontend/src/metabase/reference/segments/SegmentFieldList.tsx+++ b/frontend/src/metabase/reference/segments/SegmentFieldList.tsx@@ -8,7 +8,6 @@ import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrimport { modelIconMap } from "metabase/common/utils/icon";import CS from "metabase/css/core/index.css";import { connect } from "metabase/redux";-import { updateField } from "metabase/redux/metadata";import R from "metabase/reference/Reference.module.css";import { EditHeader } from "metabase/reference/components/EditHeader";import EditableReferenceHeader from "metabase/reference/components/EditableReferenceHeader";@@ -17,6 +16,7 @@ import F from "metabase/reference/components/Field.module.css";import { List } from "metabase/reference/components/List";import S from "metabase/reference/components/List/List.module.css";import * as actions from "metabase/reference/reference";+import { updateField } from "metabase/reference/update-actions";import { getIconForField } from "metabase-lib/v1/metadata/utils/fields";import type {FieldId,diff --git a/frontend/src/metabase/reference/update-actions.ts b/frontend/src/metabase/reference/update-actions.tsnew file mode 100644index 00000000000..4b7669af4b9--- /dev/null+++ b/frontend/src/metabase/reference/update-actions.ts@@ -0,0 +1,64 @@+import _ from "underscore";++import { databaseApi, fieldApi, segmentApi, tableApi } from "metabase/api";+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";+import {+ databaseFetched,+ fieldFetched,+ tableFetched,+} from "metabase/metadata-store";+import type { Dispatch } from "metabase/redux/store";+import type { Database, Field, Segment, Table } from "metabase-types/api";++/**+ * The edit forms in this module submit the entity they rendered, which came+ * from `state.entities` and carries the nested records the mirror stitched onto+ * it. The API rejects those, so each one is dropped before the request.+ */++export const updateDatabase =+ (database: Database) =>+ async (dispatch: Dispatch): Promise<unknown> => {+ const updated: Database = await runRtkEndpoint(+ _.omit(database, "tables", "tables_lookup"),+ dispatch,+ databaseApi.endpoints.updateDatabase,+ );+ dispatch(databaseFetched(updated));+ return updated;+ };++export const updateTable =+ (table: Table) =>+ async (dispatch: Dispatch): Promise<unknown> => {+ const updated: Table = await runRtkEndpoint(+ _.omit(+ table,+ "fields",+ "fields_lookup",+ "aggregation_operators",+ "segments",+ ),+ dispatch,+ tableApi.endpoints.updateTable,+ );+ dispatch(tableFetched(updated));+ return updated;+ };++export const updateField =+ (field: Field) =>+ async (dispatch: Dispatch): Promise<unknown> => {+ const updated: Field = await runRtkEndpoint(+ _.omit(field, "filter_operators_lookup"),+ dispatch,+ fieldApi.endpoints.updateField,+ );+ dispatch(fieldFetched(updated));+ return updated;+ };++export const updateSegment =+ (segment: Segment) =>+ (dispatch: Dispatch): Promise<unknown> =>+ runRtkEndpoint(segment, dispatch, segmentApi.endpoints.updateSegment);diff --git a/frontend/src/metabase/store.ts b/frontend/src/metabase/store.tsindex 0a30f0459e0..61de6510ad4 100644--- a/frontend/src/metabase/store.ts+++ b/frontend/src/metabase/store.ts@@ -7,8 +7,8 @@ import {} from "@reduxjs/toolkit";import { Api } from "metabase/api";+import { metadataHydrationMiddleware } from "metabase/metadata-store";import { PLUGIN_REDUX_MIDDLEWARES } from "metabase/plugins";-import { metadataHydrationMiddleware } from "metabase/redux/entities/hydration";import type { State } from "metabase/redux/store";// Each app passes its own reducer map, so per-slice types can't be known here.diff --git a/frontend/test/__support__/entities-store.ts b/frontend/test/__support__/entities-store.tsindex 45f98479014..e0d81e6c36a 100644--- a/frontend/test/__support__/entities-store.ts+++ b/frontend/test/__support__/entities-store.ts@@ -3,11 +3,13 @@ import { combineReducers, configureStore } from "@reduxjs/toolkit";import _ from "underscore";import { Api } from "metabase/api";+import {+ entitiesReducer,+ metadataHydrationMiddleware,+} from "metabase/metadata-store";import { commonReducers } from "metabase/reducers-common";import { mainReducers } from "metabase/reducers-main";import { publicReducers } from "metabase/reducers-public";-import { reducer as entitiesReducer } from "metabase/redux/entities";-import { metadataHydrationMiddleware } from "metabase/redux/entities/hydration";import type { State } from "metabase/redux/store";import {type StoreSeedState,diff --git a/frontend/test/__support__/store.ts b/frontend/test/__support__/store.tsindex 43860e547c9..da5e3e26cfd 100644--- a/frontend/test/__support__/store.ts+++ b/frontend/test/__support__/store.ts@@ -1,62 +1,4 @@-import type { Schema as NormalizrSchema } from "normalizr";-import { normalize } from "normalizr";--import type { EntitiesState } from "metabase/redux/store";-import { createMockNormalizedEntitiesState } from "metabase/redux/store/mocks";-import {- DatabaseSchema,- FieldSchema,- MeasureSchema,- MetricSchema,- QuestionSchema,- SchemaSchema,- SegmentSchema,- SnippetSchema,- TableSchema,-} from "metabase/schema";-import type {- Card,- Database,- Field,- Measure,- NativeQuerySnippet,- SavedQuestionDatabase,- Schema,- Segment,- Table,- User,-} from "metabase-types/api";--export interface EntitiesStateOpts {- databases?: (Database | SavedQuestionDatabase)[];- schemas?: Schema[];- tables?: Table[];- fields?: Field[];- segments?: Segment[];- measures?: Measure[];- snippets?: NativeQuerySnippet[];- users?: User[];- questions?: Card[];-}--const EntitiesSchema: Record<keyof EntitiesState, NormalizrSchema<any>> = {- databases: [DatabaseSchema],- schemas: [SchemaSchema],- tables: [TableSchema],- fields: [FieldSchema],- segments: [SegmentSchema],- measures: [MeasureSchema],- metrics: [MetricSchema],- snippets: [SnippetSchema],- questions: [QuestionSchema],-};--export const createMockEntitiesState = (- opts: EntitiesStateOpts,-): EntitiesState => {- const schema = normalize(opts, EntitiesSchema);- return {- ...createMockNormalizedEntitiesState(),- ...schema.entities,- };-};+export {+ createMockEntitiesState,+ type EntitiesStateOpts,+} from "metabase/metadata-store";