Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Read the reference database pages from their own requests (#82481)

Romeo Van Snick6636c786e2dc
diff --git a/frontend/src/metabase/reference/databases/DatabaseDetail.tsx b/frontend/src/metabase/reference/databases/DatabaseDetail.tsx
index e1b0ee7b04c..ef69781a743 100644
--- a/frontend/src/metabase/reference/databases/DatabaseDetail.tsx
+++ b/frontend/src/metabase/reference/databases/DatabaseDetail.tsx
@@ -11,29 +11,18 @@ 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 { Database, User } from "metabase-types/api";
-import type { ReferenceRouteProps, StateWithReference } from "../selectors";
-import {
- getDatabase,
- getIsEditing,
- getIsFormulaExpanded,
- getUser,
-} from "../selectors";
-import type { BaseDetailFormFields, StubbedDatabase } from "../types";
+import type { StateWithReference } from "../selectors";
+import { getIsEditing, getIsFormulaExpanded, getUser } from "../selectors";
+import type { BaseDetailFormFields } from "../types";
interface DatabaseDetailFormFields extends BaseDetailFormFields {
revision_message?: string;
}
-const mapStateToProps = (
- state: StateWithReference,
- props: ReferenceRouteProps,
-) => {
- const entity = getDatabase(state, props) || {};
-
+const mapStateToProps = (state: StateWithReference) => {
return {
- entity,
user: getUser(state),
isEditing: getIsEditing(state),
isFormulaExpanded: getIsFormulaExpanded(state),
@@ -48,7 +37,7 @@ const mapDispatchToProps = {
interface DatabaseDetailProps {
style?: React.CSSProperties;
- entity: StubbedDatabase;
+ database: Database | undefined;
user: User | null;
isEditing?: boolean;
startEditing: () => void;
@@ -62,7 +51,7 @@ interface DatabaseDetailProps {
const DatabaseDetail = (props: DatabaseDetailProps) => {
const {
style,
- entity,
+ database: entity,
loadingError,
loading,
user,
@@ -85,7 +74,13 @@ const DatabaseDetail = (props: DatabaseDetailProps) => {
onSubmit: async (fields): Promise<void> => {
setSaveError(null);
try {
- await onSubmit(fields, { ...props, resetForm: handleReset });
+ await onSubmit(fields, {
+ ...props,
+ // `props` carries the entity under its own name. The update actions
+ // read `entity`, so name it that here.
+ entity: entity ?? {},
+ resetForm: handleReset,
+ });
} catch (error) {
console.error(error);
setSaveError(error);
@@ -111,7 +106,7 @@ const DatabaseDetail = (props: DatabaseDetailProps) => {
/>
)}
<EditableReferenceHeader
- entity={entity}
+ entity={entity ?? {}}
type="database"
name="Details"
headerIcon="database"
@@ -145,7 +140,7 @@ const DatabaseDetail = (props: DatabaseDetailProps) => {
<li className={CS.relative}>
<Detail
name={t`Description`}
- description={entity.description}
+ description={entity?.description}
placeholder={t`No description yet`}
isEditing={isEditing}
field={getFormField("description")}
@@ -154,7 +149,7 @@ const DatabaseDetail = (props: DatabaseDetailProps) => {
<li className={CS.relative}>
<Detail
name={t`Why this database is interesting`}
- description={entity.points_of_interest}
+ description={entity?.points_of_interest}
placeholder={t`Nothing interesting yet`}
isEditing={isEditing}
field={getFormField("points_of_interest")}
@@ -163,7 +158,7 @@ const DatabaseDetail = (props: DatabaseDetailProps) => {
<li className={CS.relative}>
<Detail
name={t`Things to be aware of about this database`}
- description={entity.caveats}
+ description={entity?.caveats}
placeholder={t`Nothing to be aware of yet`}
isEditing={isEditing}
field={getFormField("caveats")}
diff --git a/frontend/src/metabase/reference/databases/DatabaseDetail.unit.spec.tsx b/frontend/src/metabase/reference/databases/DatabaseDetail.unit.spec.tsx
new file mode 100644
index 00000000000..1b8e815af22
--- /dev/null
+++ b/frontend/src/metabase/reference/databases/DatabaseDetail.unit.spec.tsx
@@ -0,0 +1,59 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import { setupDatabaseEndpoints } from "__support__/server-mocks";
+import { createMockState } from "__support__/state";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { Route } from "metabase/router";
+import { createMockDatabase, createMockUser } from "metabase-types/api/mocks";
+
+import DatabaseDetail from "./DatabaseDetail";
+
+const database = createMockDatabase({ id: 1, name: "Sample Database" });
+
+function setup() {
+ setupDatabaseEndpoints(database);
+ fetchMock.put(`path:/api/database/${database.id}`, {
+ ...database,
+ description: "A pretty ok store",
+ });
+
+ renderWithProviders(
+ <Route path="/" element={<DatabaseDetail database={database} />} />,
+ {
+ withRouter: true,
+ storeInitialState: createMockState({
+ currentUser: createMockUser({ is_superuser: true }),
+ }),
+ },
+ );
+}
+
+describe("DatabaseDetail", () => {
+ it("sends the edited description to the api", async () => {
+ setup();
+
+ await userEvent.click(screen.getByRole("button", { name: /Edit/ }));
+ await userEvent.type(
+ screen.getByPlaceholderText("No description yet"),
+ "A pretty ok store",
+ );
+ await userEvent.click(screen.getByRole("button", { name: "Save" }));
+
+ await waitFor(() => {
+ expect(
+ fetchMock.callHistory.calls(`path:/api/database/${database.id}`, {
+ method: "PUT",
+ }),
+ ).toHaveLength(1);
+ });
+
+ const [call] = fetchMock.callHistory.calls(
+ `path:/api/database/${database.id}`,
+ { method: "PUT" },
+ );
+ expect(JSON.parse(String(call.options.body))).toEqual({
+ description: "A pretty ok store",
+ });
+ });
+});
diff --git a/frontend/src/metabase/reference/databases/DatabaseDetailContainer.tsx b/frontend/src/metabase/reference/databases/DatabaseDetailContainer.tsx
index 88fa349c30d..bd2408a5bae 100644
--- a/frontend/src/metabase/reference/databases/DatabaseDetailContainer.tsx
+++ b/frontend/src/metabase/reference/databases/DatabaseDetailContainer.tsx
@@ -2,7 +2,6 @@ import cx from "classnames";
import { useEffect } from "react";
import { usePrevious } from "react-use";
-import { useGetDatabaseMetadataQuery } from "metabase/api";
import CS from "metabase/css/core/index.css";
import { connect, useSelector } from "metabase/redux";
import { SidebarLayout } from "metabase/reference/components/SidebarLayout";
@@ -13,12 +12,12 @@ import { useLocation, useParams } from "metabase/router";
import type { ClearStateProps } from "../reference";
import {
type ReferenceRouteParams,
- getDatabase,
getDatabaseId,
getIsEditing,
} from "../selectors";
import DatabaseSidebar from "./DatabaseSidebar";
+import { useReferenceDatabase } from "./use-reference-database";
const mapDispatchToProps = {
...actions,
@@ -31,14 +30,9 @@ function DatabaseDetailContainer(props: DatabaseDetailContainerProps) {
const previousPathname = usePrevious(pathname);
const params = useParams<ReferenceRouteParams>();
- const database = useSelector((state) => getDatabase(state, { params }));
const databaseId = useSelector((state) => getDatabaseId(state, { params }));
const isEditing = useSelector(getIsEditing);
-
- const { isFetching, error } = useGetDatabaseMetadataQuery({
- id: databaseId,
- skip_fields: true,
- });
+ const { database, isLoading, error } = useReferenceDatabase(databaseId);
useEffect(() => {
const pathnameChanged =
@@ -52,11 +46,16 @@ function DatabaseDetailContainer(props: DatabaseDetailContainerProps) {
<SidebarLayout
className={cx(CS.flexFull, CS.relative)}
style={isEditing ? { paddingTop: "43px" } : {}}
- sidebar={<DatabaseSidebar database={database} />}
+ sidebar={
+ <DatabaseSidebar
+ databaseId={databaseId}
+ databaseName={database?.name}
+ />
+ }
>
<DatabaseDetail
- params={params}
- loading={isFetching}
+ database={database}
+ loading={isLoading}
loadingError={error}
/>
</SidebarLayout>
diff --git a/frontend/src/metabase/reference/databases/DatabaseSidebar.tsx b/frontend/src/metabase/reference/databases/DatabaseSidebar.tsx
index bfe1d0db1be..deafcb76b65 100644
--- a/frontend/src/metabase/reference/databases/DatabaseSidebar.tsx
+++ b/frontend/src/metabase/reference/databases/DatabaseSidebar.tsx
@@ -6,36 +6,39 @@ import { Breadcrumbs } from "metabase/common/components/Breadcrumbs";
import CS from "metabase/css/core/index.css";
import S from "metabase/reference/components/Sidebar.module.css";
import { SidebarItem } from "metabase/reference/components/SidebarItem";
-
-import type { StubbedDatabase } from "../types";
+import type { DatabaseId } from "metabase-types/api";
interface DatabaseSidebarProps {
- database: StubbedDatabase;
+ databaseId: DatabaseId;
+ databaseName?: string;
}
-const DatabaseSidebar = ({ database }: DatabaseSidebarProps) => (
+const DatabaseSidebar = ({
+ databaseId,
+ databaseName,
+}: DatabaseSidebarProps) => (
<div className={S.sidebar}>
<ul>
<div>
<Breadcrumbs
className={cx(CS.py4, CS.ml3)}
- crumbs={[[t`Databases`, "/reference/databases"], [database.name]]}
+ crumbs={[[t`Databases`, "/reference/databases"], [databaseName]]}
inSidebar={true}
placeholder={t`Data Reference`}
/>
</div>
<ol className={CS.mx3}>
<SidebarItem
- key={`/reference/databases/${database.id}`}
- href={`/reference/databases/${database.id}`}
+ key={`/reference/databases/${databaseId}`}
+ href={`/reference/databases/${databaseId}`}
icon="document"
name={t`Details`}
/>
<SidebarItem
- key={`/reference/databases/${database.id}/tables`}
- href={`/reference/databases/${database.id}/tables`}
+ key={`/reference/databases/${databaseId}/tables`}
+ href={`/reference/databases/${databaseId}/tables`}
icon="table2"
- name={t`Tables in ${database.name}`}
+ name={t`Tables in ${databaseName}`}
/>
</ol>
</ul>
diff --git a/frontend/src/metabase/reference/databases/FieldDetail.tsx b/frontend/src/metabase/reference/databases/FieldDetail.tsx
index a31d2a12f84..85ac8b20859 100644
--- a/frontend/src/metabase/reference/databases/FieldDetail.tsx
+++ b/frontend/src/metabase/reference/databases/FieldDetail.tsx
@@ -5,10 +5,7 @@ import { t } from "ttag";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import CS from "metabase/css/core/index.css";
-import {
- getShallowFields,
- selectMetadataProvider,
-} from "metabase/metadata-store";
+import { selectMetadataProvider } from "metabase/metadata-store";
import { connect } from "metabase/redux";
import S from "metabase/reference/Reference.module.css";
import Detail from "metabase/reference/components/Detail";
@@ -19,25 +16,14 @@ import UsefulQuestions from "metabase/reference/components/UsefulQuestions";
import * as actions from "metabase/reference/reference";
import { updateField } from "metabase/reference/update-actions";
import type * as Lib from "metabase-lib";
-import type { NormalizedField, User } from "metabase-types/api";
+import type { DatabaseId, Field, Table, User } from "metabase-types/api";
-import type { ReferenceRouteProps, StateWithReference } from "../selectors";
-import {
- getDatabase,
- getField,
- getFieldId,
- getIsEditing,
- getIsFormulaExpanded,
- getTable,
- getUser,
-} from "../selectors";
+import type { StateWithReference } from "../selectors";
+import { getIsEditing, getIsFormulaExpanded, getUser } from "../selectors";
import type {
BaseDetailFormFields,
FieldFormFieldsValues,
ReferenceLoadingProps,
- StubbedDatabase,
- StubbedField,
- StubbedTable,
} from "../types";
import { getQuestionUrl } from "../utils";
@@ -47,11 +33,9 @@ interface FieldDetailFormFields
}
const interestingQuestions = (
- database: StubbedDatabase,
- table: StubbedTable,
- field: StubbedField,
+ table: Table,
+ field: Field,
metadataProvider: Lib.MetadataProvider,
- breakoutField: NormalizedField | undefined,
) => {
return [
{
@@ -59,7 +43,7 @@ const interestingQuestions = (
icon: "bar" as const,
link: getQuestionUrl({
tableId: table.id,
- breakoutField,
+ breakoutField: field,
getCount: true,
visualization: "bar",
metadataProvider: metadataProvider,
@@ -70,7 +54,7 @@ const interestingQuestions = (
icon: "pie" as const,
link: getQuestionUrl({
tableId: table.id,
- breakoutField,
+ breakoutField: field,
getCount: true,
visualization: "pie",
metadataProvider: metadataProvider,
@@ -81,7 +65,7 @@ const interestingQuestions = (
icon: "table2" as const,
link: getQuestionUrl({
tableId: table.id,
- breakoutField,
+ breakoutField: field,
metadataProvider: metadataProvider,
}),
},
@@ -90,22 +74,10 @@ const interestingQuestions = (
const mapStateToProps = (
state: StateWithReference,
- props: ReferenceRouteProps,
+ props: Pick<FieldDetailProps, "databaseId">,
) => {
- const entity = getField(state, props) || {};
-
return {
- metadataProvider: selectMetadataProvider(
- state,
- getDatabase(state, props)?.id ?? null,
- ),
- // `getField` falls back to a stub with only an id, which cannot describe a
- // column, so the breakout takes the loaded field or nothing
- breakoutField: getShallowFields(state)?.[getFieldId(state, props)],
- entity,
- field: entity,
- table: getTable(state, props),
- database: getDatabase(state, props),
+ metadataProvider: selectMetadataProvider(state, props.databaseId ?? null),
user: getUser(state),
isEditing: getIsEditing(state),
isFormulaExpanded: getIsFormulaExpanded(state),
@@ -120,18 +92,16 @@ const mapDispatchToProps = {
interface FieldDetailProps {
style: React.CSSProperties;
- entity: StubbedField;
- field: StubbedField;
- table: StubbedTable;
+ field: Field | undefined;
+ table: Table | undefined;
+ databaseId: DatabaseId;
user: User;
- database: StubbedDatabase;
isEditing?: boolean;
startEditing: () => void;
endEditing: () => void;
loading?: boolean;
loadingError?: unknown;
metadataProvider: Lib.MetadataProvider;
- breakoutField: NormalizedField | undefined;
onSubmit: (fields: FieldDetailFormFields, props: any) => Promise<void>;
}
@@ -139,7 +109,7 @@ interface FieldDetailProps {
const FieldDetail = (props: FieldDetailProps) => {
const {
style,
- entity,
+ field: entity,
table,
loadingError,
loading,
@@ -148,7 +118,6 @@ const FieldDetail = (props: FieldDetailProps) => {
startEditing,
endEditing,
metadataProvider,
- breakoutField,
onSubmit,
} = props;
@@ -165,7 +134,13 @@ const FieldDetail = (props: FieldDetailProps) => {
onSubmit: async (fields): Promise<void> => {
setSaveError(null);
try {
- await onSubmit(fields, { ...props, resetForm: handleReset });
+ await onSubmit(fields, {
+ ...props,
+ // `props` carries the entity under its own name. The update actions
+ // read `entity`, so name it that here.
+ entity: entity ?? {},
+ resetForm: handleReset,
+ });
} catch (error) {
console.error(error);
setSaveError(error);
@@ -207,103 +182,102 @@ const FieldDetail = (props: FieldDetailProps) => {
loading={!loadingError && !saveError && (loading || isSubmitting)}
error={saveError ?? loadingError}
>
- {() => (
- <div className={CS.wrapper}>
- <div
- className={cx(
- CS.pl4,
- CS.pr3,
- CS.pt4,
- CS.mb4,
- CS.mb1,
- CS.bgWhite,
- CS.rounded,
- CS.bordered,
- )}
- >
- <ul>
- <li>
- <Detail
- name={t`Description`}
- description={entity.description}
- placeholder={t`No description yet`}
- isEditing={isEditing}
- field={getFormField("description")}
- />
- </li>
- {!isEditing && (
+ {() =>
+ entity == null || table == null ? null : (
+ <div className={CS.wrapper}>
+ <div
+ className={cx(
+ CS.pl4,
+ CS.pr3,
+ CS.pt4,
+ CS.mb4,
+ CS.mb1,
+ CS.bgWhite,
+ CS.rounded,
+ CS.bordered,
+ )}
+ >
+ <ul>
<li>
<Detail
- name={t`Actual name in database`}
- description={entity.name}
- subtitleClass={S.tableActualName}
+ name={t`Description`}
+ description={entity.description}
+ placeholder={t`No description yet`}
+ isEditing={isEditing}
+ field={getFormField("description")}
/>
</li>
- )}
- <li>
- <Detail
- name={t`Why this field is interesting`}
- description={entity.points_of_interest}
- placeholder={t`Nothing interesting yet`}
- isEditing={isEditing}
- field={getFormField("points_of_interest")}
- />
- </li>
- <li>
- <Detail
- name={t`Things to be aware of about this field`}
- description={entity.caveats}
- placeholder={t`Nothing to be aware of yet`}
- isEditing={isEditing}
- field={getFormField("caveats")}
- />
- </li>
-
- {!isEditing && (
+ {!isEditing && (
+ <li>
+ <Detail
+ name={t`Actual name in database`}
+ description={entity.name}
+ subtitleClass={S.tableActualName}
+ />
+ </li>
+ )}
<li>
<Detail
- name={t`Data type`}
- description={entity.database_type}
+ name={t`Why this field is interesting`}
+ description={entity.points_of_interest}
+ placeholder={t`Nothing interesting yet`}
+ isEditing={isEditing}
+ field={getFormField("points_of_interest")}
/>
</li>
- )}
- <li>
- <FieldTypeDetail
- databaseId={table.db_id!}
- field={entity}
- fieldTypeFormField={getFormField("semantic_type")}
- foreignKeyFormField={getFormField("fk_target_field_id")}
- fieldSettingsFormField={getFormField("settings")}
- isEditing={Boolean(isEditing)}
- />
- </li>
- {!isEditing && (
<li>
- <UsefulQuestions
- questions={interestingQuestions(
- props.database,
- props.table,
- props.field,
- metadataProvider,
- breakoutField,
- )}
+ <Detail
+ name={t`Things to be aware of about this field`}
+ description={entity.caveats}
+ placeholder={t`Nothing to be aware of yet`}
+ isEditing={isEditing}
+ field={getFormField("caveats")}
/>
</li>
- )}
- </ul>
+
+ {!isEditing && (
+ <li>
+ <Detail
+ name={t`Data type`}
+ description={entity.database_type}
+ />
+ </li>
+ )}
+ <li>
+ <FieldTypeDetail
+ databaseId={table.db_id}
+ field={entity}
+ fieldTypeFormField={getFormField("semantic_type")}
+ foreignKeyFormField={getFormField("fk_target_field_id")}
+ fieldSettingsFormField={getFormField("settings")}
+ isEditing={Boolean(isEditing)}
+ />
+ </li>
+ {!isEditing && (
+ <li>
+ <UsefulQuestions
+ questions={interestingQuestions(
+ table,
+ entity,
+ metadataProvider,
+ )}
+ />
+ </li>
+ )}
+ </ul>
+ </div>
</div>
- </div>
- )}
+ )
+ }
</LoadingAndErrorWrapper>
</form>
);
};
-// What the container has to supply: `params` feeds `mapStateToProps`, and
-// `metadata` is read here but selected by the container. Naming it keeps that
-// contract type-checked.
-type FieldDetailOwnProps = ReferenceRouteProps &
- Pick<FieldDetailProps, "metadataProvider" | "breakoutField"> &
+type FieldDetailOwnProps = Pick<
+ FieldDetailProps,
+ "databaseId" | "table" | "field"
+> &
ReferenceLoadingProps;
// eslint-disable-next-line import/no-default-export -- deprecated usage
diff --git a/frontend/src/metabase/reference/databases/FieldDetailContainer.tsx b/frontend/src/metabase/reference/databases/FieldDetailContainer.tsx
index 1a1dd2bda72..be20d6702cc 100644
--- a/frontend/src/metabase/reference/databases/FieldDetailContainer.tsx
+++ b/frontend/src/metabase/reference/databases/FieldDetailContainer.tsx
@@ -14,14 +14,14 @@ import { useLocation, useParams } from "metabase/router";
import type { ClearStateProps } from "../reference";
import {
type ReferenceRouteParams,
- getDatabase,
- getField,
+ getDatabaseId,
+ getFieldId,
getIsEditing,
- getTable,
getTableId,
} from "../selectors";
import FieldSidebar from "./FieldSidebar";
+import { useReferenceTableFields } from "./use-reference-database";
const mapDispatchToProps = {
...actions,
@@ -35,11 +35,15 @@ function FieldDetailContainer(props: FieldDetailContainerProps) {
const dispatch = useDispatch();
const params = useParams<ReferenceRouteParams>();
- const database = useSelector((state) => getDatabase(state, { params }));
- const table = useSelector((state) => getTable(state, { params }));
- const field = useSelector((state) => getField(state, { params }));
+ const databaseId = useSelector((state) => getDatabaseId(state, { params }));
const tableId = useSelector((state) => getTableId(state, { params }));
+ const fieldId = useSelector((state) => getFieldId(state, { params }));
const isEditing = useSelector(getIsEditing);
+ const { database, table, fields } = useReferenceTableFields(
+ databaseId,
+ tableId,
+ );
+ const field = fields.find(({ id }) => id === fieldId);
const { loading, loadingError } = useReferenceFetch(() =>
fetchTableData(dispatch, tableId),
);
@@ -56,10 +60,21 @@ function FieldDetailContainer(props: FieldDetailContainerProps) {
<SidebarLayout
className={cx(CS.flexFull, CS.relative)}
style={isEditing ? { paddingTop: "43px" } : {}}
- sidebar={<FieldSidebar database={database} table={table} field={field} />}
+ sidebar={
+ <FieldSidebar
+ databaseId={databaseId}
+ databaseName={database?.name}
+ tableId={tableId}
+ tableName={table?.name}
+ fieldId={fieldId}
+ fieldName={field?.name}
+ />
+ }
>
<FieldDetail
- params={params}
+ databaseId={databaseId}
+ table={table}
+ field={field}
loading={loading}
loadingError={loadingError}
/>
diff --git a/frontend/src/metabase/reference/databases/FieldList.tsx b/frontend/src/metabase/reference/databases/FieldList.tsx
index 45c92c0983c..fb8d37d581f 100644
--- a/frontend/src/metabase/reference/databases/FieldList.tsx
+++ b/frontend/src/metabase/reference/databases/FieldList.tsx
@@ -1,6 +1,6 @@
import cx from "classnames";
import { useFormik } from "formik";
-import { useState } from "react";
+import { useMemo, useState } from "react";
import { t } from "ttag";
import { EmptyState } from "metabase/common/components/EmptyState";
@@ -17,24 +17,16 @@ 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 {
+ Field as ApiField,
FieldId,
IconName,
- NormalizedField,
+ Table,
User,
} from "metabase-types/api";
-import type { ReferenceRouteProps, StateWithReference } from "../selectors";
-import {
- getFieldsByTable,
- getIsEditing,
- getTable,
- getUser,
-} from "../selectors";
-import type {
- FieldFormFieldsValues,
- ReferenceLoadingProps,
- StubbedTable,
-} from "../types";
+import type { StateWithReference } from "../selectors";
+import { getIsEditing, getUser } from "../selectors";
+import type { FieldFormFieldsValues, ReferenceLoadingProps } from "../types";
type FieldListFormFields = Record<string, FieldFormFieldsValues>;
@@ -45,14 +37,8 @@ const emptyStateData = {
icon: "fields" as const,
};
-const mapStateToProps = (
- state: StateWithReference,
- props: ReferenceRouteProps,
-) => {
- const data = getFieldsByTable(state, props);
+const mapStateToProps = (state: StateWithReference) => {
return {
- table: getTable(state, props),
- entities: data,
user: getUser(state),
isEditing: getIsEditing(state),
};
@@ -67,17 +53,17 @@ const mapDispatchToProps = {
interface FieldListProps {
style: React.CSSProperties;
- entities: Record<string, NormalizedField>;
+ fields: ApiField[];
isEditing?: boolean;
startEditing: () => void;
endEditing: () => void;
user: User | null;
- table: StubbedTable;
+ table: Table | undefined;
loading?: boolean;
loadingError?: unknown;
// The action handler in reference.ts types its own props parameter.
onSubmit: (
- entities: Record<string, NormalizedField>,
+ entities: Record<string, ApiField>,
fields: FieldListFormFields,
props: any,
) => void;
@@ -87,7 +73,7 @@ interface FieldListProps {
const FieldList = (props: FieldListProps) => {
const {
style,
- entities,
+ fields,
table,
loadingError,
loading,
@@ -100,6 +86,12 @@ const FieldList = (props: FieldListProps) => {
const [saveError, setSaveError] = useState<unknown>(null);
+ // `rUpdateFields` looks each edited field up by id.
+ const entitiesById = useMemo(
+ () => Object.fromEntries(fields.map((field) => [String(field.id), field])),
+ [fields],
+ );
+
const {
isSubmitting,
getFieldProps,
@@ -111,7 +103,10 @@ const FieldList = (props: FieldListProps) => {
onSubmit: async (fields): Promise<void> => {
setSaveError(null);
try {
- await onSubmit(entities, fields, { ...props, resetForm: handleReset });
+ await onSubmit(entitiesById, fields, {
+ ...props,
+ resetForm: handleReset,
+ });
} catch (error) {
console.error(error);
setSaveError(error);
@@ -150,7 +145,7 @@ const FieldList = (props: FieldListProps) => {
)}
<EditableReferenceHeader
headerIcon="table2"
- name={t`Fields in ${table.display_name}`}
+ name={t`Fields in ${table?.display_name}`}
user={user}
isEditing={isEditing}
startEditing={startEditing}
@@ -160,7 +155,7 @@ const FieldList = (props: FieldListProps) => {
error={saveError ?? loadingError}
>
{() =>
- Object.keys(entities).length > 0 ? (
+ table != null && fields.length > 0 ? (
<div className={CS.wrapper}>
<div
className={cx(
@@ -186,17 +181,15 @@ const FieldList = (props: FieldListProps) => {
</div>
</div>
<ul>
- {Object.values(entities)
+ {fields
// respect the column sort order
- .sort((a, b) => a.position - b.position)
+ .toSorted((a, b) => a.position - b.position)
.map(
(entity) =>
- entity &&
- entity.id &&
- entity.name && (
+ entity.id != null && (
<li key={String(entity.id)}>
<Field
- databaseId={table.db_id!}
+ databaseId={table.db_id}
field={entity}
url={`/reference/databases/${table.db_id}/tables/${table.id}/fields/${entity.id}`}
// Unjustified type cast. FIXME
@@ -234,6 +227,6 @@ export default connect(
// props, because the `actions` spread in `mapDispatchToProps` is untyped.
// The cast restores the props a caller actually passes.
FieldList as unknown as React.ComponentType<
- ReferenceRouteProps & ReferenceLoadingProps
+ ReferenceLoadingProps & Pick<FieldListProps, "table" | "fields">
>,
);
diff --git a/frontend/src/metabase/reference/databases/FieldListContainer.tsx b/frontend/src/metabase/reference/databases/FieldListContainer.tsx
index 1ecf096fbc2..aeaad6e9166 100644
--- a/frontend/src/metabase/reference/databases/FieldListContainer.tsx
+++ b/frontend/src/metabase/reference/databases/FieldListContainer.tsx
@@ -14,13 +14,13 @@ import { useLocation, useParams } from "metabase/router";
import type { ClearStateProps } from "../reference";
import {
type ReferenceRouteParams,
- getDatabase,
+ getDatabaseId,
getIsEditing,
- getTable,
getTableId,
} from "../selectors";
import TableSidebar from "./TableSidebar";
+import { useReferenceTableFields } from "./use-reference-database";
const mapDispatchToProps = {
...actions,
@@ -34,10 +34,13 @@ function FieldListContainer(props: FieldListContainerProps) {
const dispatch = useDispatch();
const params = useParams<ReferenceRouteParams>();
- const database = useSelector((state) => getDatabase(state, { params }));
- const table = useSelector((state) => getTable(state, { params }));
+ const databaseId = useSelector((state) => getDatabaseId(state, { params }));
const tableId = useSelector((state) => getTableId(state, { params }));
const isEditing = useSelector(getIsEditing);
+ const { database, table, fields } = useReferenceTableFields(
+ databaseId,
+ tableId,
+ );
const { loading, loadingError } = useReferenceFetch(() =>
fetchTableData(dispatch, tableId),
@@ -55,10 +58,18 @@ function FieldListContainer(props: FieldListContainerProps) {
<SidebarLayout
className={cx(CS.flexFull, CS.relative)}
style={isEditing ? { paddingTop: "43px" } : {}}
- sidebar={<TableSidebar database={database} table={table} />}
+ sidebar={
+ <TableSidebar
+ databaseId={databaseId}
+ databaseName={database?.name}
+ tableId={tableId}
+ tableName={table?.name}
+ />
+ }
>
<FieldList
- params={params}
+ table={table}
+ fields={fields}
loading={loading}
loadingError={loadingError}
/>
diff --git a/frontend/src/metabase/reference/databases/FieldSidebar.tsx b/frontend/src/metabase/reference/databases/FieldSidebar.tsx
index d5dba3b096e..cd9dee9cccc 100644
--- a/frontend/src/metabase/reference/databases/FieldSidebar.tsx
+++ b/frontend/src/metabase/reference/databases/FieldSidebar.tsx
@@ -7,29 +7,36 @@ import CS from "metabase/css/core/index.css";
import S from "metabase/reference/components/Sidebar.module.css";
import { SidebarItem } from "metabase/reference/components/SidebarItem";
import MetabaseSettings from "metabase/utils/settings";
+import type { DatabaseId, FieldId, TableId } from "metabase-types/api";
import { trackReferenceXRayClicked } from "../analytics";
-import type { StubbedDatabase, StubbedField, StubbedTable } from "../types";
interface FieldSidebarProps {
- database: StubbedDatabase;
- table: StubbedTable;
- field: StubbedField;
+ databaseId: DatabaseId;
+ databaseName?: string;
+ tableId: TableId;
+ tableName?: string;
+ fieldId: FieldId;
+ fieldName?: string;
}
-const FieldSidebar = ({ database, table, field }: FieldSidebarProps) => (
+const FieldSidebar = ({
+ databaseId,
+ databaseName,
+ tableId,
+ tableName,
+ fieldId,
+ fieldName,
+}: FieldSidebarProps) => (
<div className={S.sidebar}>
<ul>
<div>
<Breadcrumbs
className={cx(CS.py4, CS.ml3)}
crumbs={[
- [database.name, `/reference/databases/${database.id}`],
- [
- table.name,
- `/reference/databases/${database.id}/tables/${table.id}`,
- ],
- [field.name],
+ [databaseName, `/reference/databases/${databaseId}`],
+ [tableName, `/reference/databases/${databaseId}/tables/${tableId}`],
+ [fieldName],
]}
inSidebar={true}
placeholder={t`Data Reference`}
@@ -37,16 +44,16 @@ const FieldSidebar = ({ database, table, field }: FieldSidebarProps) => (
</div>
<ol className={CS.mx3}>
<SidebarItem
- key={`/reference/databases/${database.id}/tables/${table.id}/fields/${field.id}`}
- href={`/reference/databases/${database.id}/tables/${table.id}/fields/${field.id}`}
+ key={`/reference/databases/${databaseId}/tables/${tableId}/fields/${fieldId}`}
+ href={`/reference/databases/${databaseId}/tables/${tableId}/fields/${fieldId}`}
icon="document"
name={t`Details`}
/>
{MetabaseSettings.get("enable-xrays") && (
<SidebarItem
- key={`/auto/dashboard/field/${field.id}`}
- href={`/auto/dashboard/field/${field.id}`}
+ key={`/auto/dashboard/field/${fieldId}`}
+ href={`/auto/dashboard/field/${fieldId}`}
icon="bolt"
name={t`X-ray this field`}
onClick={() => trackReferenceXRayClicked("field")}
diff --git a/frontend/src/metabase/reference/databases/TableDetail.tsx b/frontend/src/metabase/reference/databases/TableDetail.tsx
index b8c2bbac861..799d5a68e9a 100644
--- a/frontend/src/metabase/reference/databases/TableDetail.tsx
+++ b/frontend/src/metabase/reference/databases/TableDetail.tsx
@@ -15,21 +15,11 @@ import UsefulQuestions from "metabase/reference/components/UsefulQuestions";
import * as actions from "metabase/reference/reference";
import { updateTable } from "metabase/reference/update-actions";
import type * as Lib from "metabase-lib";
-import type { User } from "metabase-types/api";
+import type { Table, User } from "metabase-types/api";
-import type { ReferenceRouteProps, StateWithReference } from "../selectors";
-import {
- getHasSingleSchema,
- getIsEditing,
- getIsFormulaExpanded,
- getTable,
- getUser,
-} from "../selectors";
-import type {
- BaseDetailFormFields,
- ReferenceLoadingProps,
- StubbedTable,
-} from "../types";
+import type { StateWithReference } from "../selectors";
+import { getIsEditing, getIsFormulaExpanded, getUser } from "../selectors";
+import type { BaseDetailFormFields, ReferenceLoadingProps } from "../types";
import { getQuestionUrl } from "../utils";
interface TableDetailFormFields extends BaseDetailFormFields {
@@ -37,7 +27,7 @@ interface TableDetailFormFields extends BaseDetailFormFields {
}
const interestingQuestions = (
- table: StubbedTable,
+ table: Table,
metadataProvider: Lib.MetadataProvider,
) => {
return [
@@ -63,20 +53,12 @@ const interestingQuestions = (
const mapStateToProps = (
state: StateWithReference,
- props: ReferenceRouteProps,
+ props: Pick<TableDetailProps, "table">,
) => {
- const entity = getTable(state, props) || {};
-
return {
- entity,
- table: getTable(state, props),
- metadataProvider: selectMetadataProvider(
- state,
- getTable(state, props)?.db_id ?? null,
- ),
+ metadataProvider: selectMetadataProvider(state, props.table?.db_id ?? null),
user: getUser(state),
isEditing: getIsEditing(state),
- hasSingleSchema: getHasSingleSchema(state, props),
isFormulaExpanded: getIsFormulaExpanded(state),
};
};
@@ -89,13 +71,12 @@ const mapDispatchToProps = {
interface TableDetailProps {
style: React.CSSProperties;
- entity: StubbedTable;
- table: StubbedTable;
+ table: Table | undefined;
+ tables: Table[];
user: User;
isEditing?: boolean;
startEditing: () => void;
endEditing: () => void;
- hasSingleSchema?: boolean;
loading?: boolean;
loadingError?: unknown;
metadataProvider: Lib.MetadataProvider;
@@ -106,15 +87,14 @@ interface TableDetailProps {
const TableDetail = (props: TableDetailProps) => {
const {
style,
- entity,
- table,
+ table: entity,
+ tables,
loadingError,
loading,
user,
isEditing,
startEditing,
endEditing,
- hasSingleSchema,
metadataProvider,
onSubmit,
} = props;
@@ -132,7 +112,13 @@ const TableDetail = (props: TableDetailProps) => {
onSubmit: async (fields): Promise<void> => {
setSaveError(null);
try {
- await onSubmit(fields, { ...props, resetForm: handleReset });
+ await onSubmit(fields, {
+ ...props,
+ // `props` carries the entity under its own name. The update actions
+ // read `entity`, so name it that here.
+ entity: entity ?? {},
+ resetForm: handleReset,
+ });
} catch (error) {
console.error(error);
setSaveError(error);
@@ -145,6 +131,10 @@ const TableDetail = (props: TableDetailProps) => {
...getFieldMeta(name),
});
+ const hasSingleSchema =
+ tables.length === 0 ||
+ tables.every(({ schema }) => schema === tables[0].schema);
+
return (
<form style={style} className={CS.full} onSubmit={handleSubmit}>
{isEditing && (
@@ -158,13 +148,17 @@ const TableDetail = (props: TableDetailProps) => {
/>
)}
<EditableReferenceHeader
- entity={entity}
+ entity={entity ?? {}}
type="table"
headerIcon="table2"
- headerLink={getQuestionUrl({
- tableId: entity.id,
- metadataProvider: metadataProvider,
- })}
+ headerLink={
+ entity
+ ? getQuestionUrl({
+ tableId: entity.id,
+ metadataProvider,
+ })
+ : undefined
+ }
name={t`Details`}
user={user}
isEditing={isEditing}
@@ -196,7 +190,7 @@ const TableDetail = (props: TableDetailProps) => {
<li>
<Detail
name={t`Description`}
- description={entity.description}
+ description={entity?.description}
placeholder={t`No description yet`}
isEditing={isEditing}
field={getFormField("description")}
@@ -206,7 +200,7 @@ const TableDetail = (props: TableDetailProps) => {
<li>
<Detail
name={t`Actual name in database`}
- description={entity.name}
+ description={entity?.name}
subtitleClass={S.tableActualName}
/>
</li>
@@ -214,7 +208,7 @@ const TableDetail = (props: TableDetailProps) => {
<li>
<Detail
name={t`Why this table is interesting`}
- description={entity.points_of_interest}
+ description={entity?.points_of_interest}
placeholder={t`Nothing interesting yet`}
isEditing={isEditing}
field={getFormField("points_of_interest")}
@@ -223,16 +217,16 @@ const TableDetail = (props: TableDetailProps) => {
<li>
<Detail
name={t`Things to be aware of about this table`}
- description={entity.caveats}
+ description={entity?.caveats}
placeholder={t`Nothing to be aware of yet`}
isEditing={isEditing}
field={getFormField("caveats")}
/>
</li>
- {!isEditing && (
+ {!isEditing && entity && (
<li>
<UsefulQuestions
- questions={interestingQuestions(table, metadataProvider)}
+ questions={interestingQuestions(entity, metadataProvider)}
/>
</li>
)}
@@ -255,6 +249,6 @@ export default connect(
// props, because the `actions` spread in `mapDispatchToProps` is untyped.
// The cast restores the props a caller actually passes.
TableDetail as unknown as React.ComponentType<
- ReferenceRouteProps & ReferenceLoadingProps
+ ReferenceLoadingProps & Pick<TableDetailProps, "table" | "tables">
>,
);
diff --git a/frontend/src/metabase/reference/databases/TableDetailContainer.tsx b/frontend/src/metabase/reference/databases/TableDetailContainer.tsx
index 955cda89a20..e78740aa368 100644
--- a/frontend/src/metabase/reference/databases/TableDetailContainer.tsx
+++ b/frontend/src/metabase/reference/databases/TableDetailContainer.tsx
@@ -2,7 +2,6 @@ import cx from "classnames";
import { useEffect } from "react";
import { usePrevious } from "react-use";
-import { useGetDatabaseMetadataQuery } from "metabase/api";
import CS from "metabase/css/core/index.css";
import { connect, useSelector } from "metabase/redux";
import { SidebarLayout } from "metabase/reference/components/SidebarLayout";
@@ -13,13 +12,13 @@ import { useLocation, useParams } from "metabase/router";
import type { ClearStateProps } from "../reference";
import {
type ReferenceRouteParams,
- getDatabase,
getDatabaseId,
getIsEditing,
- getTable,
+ getTableId,
} from "../selectors";
import TableSidebar from "./TableSidebar";
+import { useReferenceTable } from "./use-reference-database";
const mapDispatchToProps = {
...actions,
@@ -32,15 +31,13 @@ function TableDetailContainer(props: TableDetailContainerProps) {
const previousPathname = usePrevious(pathname);
const params = useParams<ReferenceRouteParams>();
- const database = useSelector((state) => getDatabase(state, { params }));
- const table = useSelector((state) => getTable(state, { params }));
const databaseId = useSelector((state) => getDatabaseId(state, { params }));
+ const tableId = useSelector((state) => getTableId(state, { params }));
const isEditing = useSelector(getIsEditing);
-
- const { isFetching, error } = useGetDatabaseMetadataQuery({
- id: databaseId,
- skip_fields: true,
- });
+ const { database, tables, table, isLoading, error } = useReferenceTable(
+ databaseId,
+ tableId,
+ );
useEffect(() => {
const pathnameChanged =
@@ -54,9 +51,21 @@ function TableDetailContainer(props: TableDetailContainerProps) {
<SidebarLayout
className={cx(CS.flexFull, CS.relative)}
style={isEditing ? { paddingTop: "43px" } : {}}
- sidebar={<TableSidebar database={database} table={table} />}
+ sidebar={
+ <TableSidebar
+ databaseId={databaseId}
+ databaseName={database?.name}
+ tableId={tableId}
+ tableName={table?.name}
+ />
+ }
>
- <TableDetail params={params} loading={isFetching} loadingError={error} />
+ <TableDetail
+ table={table}
+ tables={tables}
+ loading={isLoading}
+ loadingError={error}
+ />
</SidebarLayout>
);
}
diff --git a/frontend/src/metabase/reference/databases/TableList.tsx b/frontend/src/metabase/reference/databases/TableList.tsx
index efdbdefc45d..36875fedcb6 100644
--- a/frontend/src/metabase/reference/databases/TableList.tsx
+++ b/frontend/src/metabase/reference/databases/TableList.tsx
@@ -6,20 +6,13 @@ import _ from "underscore";
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 R from "metabase/reference/Reference.module.css";
import { List } from "metabase/reference/components/List";
import S from "metabase/reference/components/List/List.module.css";
import { ListItem } from "metabase/reference/components/ListItem";
+import type { Database, Table, TableId } from "metabase-types/api";
import ReferenceHeader from "../components/ReferenceHeader";
-import type { ReferenceRouteProps, StateWithReference } from "../selectors";
-import {
- getDatabase,
- getHasSingleSchema,
- getTablesByDatabase,
-} from "../selectors";
-import type { ReferenceLoadingProps } from "../types";
const emptyStateData = {
get message() {
@@ -28,39 +21,27 @@ const emptyStateData = {
icon: "table2" as const,
};
-const mapStateToProps = (
- state: StateWithReference,
- props: ReferenceRouteProps,
-) => ({
- database: getDatabase(state, props),
- entities: getTablesByDatabase(state, props),
- hasSingleSchema: getHasSingleSchema(state, props),
-});
-
+// Only what the grouping reads, so the spec can drive it with plain objects.
interface TableLike {
- id?: number | string;
+ id?: TableId;
name?: string;
- display_name?: string;
- description?: string;
- initial_sync_status?: string;
- db_id?: number;
- schema_name?: string;
+ schema?: string | null;
}
-const createListItem = (table: TableLike) => (
+const createListItem = (table: Table) => (
<ListItem
data-testid="table-list-item"
key={table.id}
name={table.display_name || table.name || ""}
- description={table.description}
+ description={table.description ?? undefined}
disabled={table.initial_sync_status !== "complete"}
url={`/reference/databases/${table.db_id}/tables/${table.id}`}
icon="table2"
/>
);
-const createSchemaSeparator = (table: TableLike) => (
- <li className={R.schemaSeparator}>{table.schema_name}</li>
+const createSchemaSeparator = (table: Table) => (
+ <li className={R.schemaSeparator}>{table.schema}</li>
);
export const separateTablesBySchema = <T extends TableLike, S, I>(
@@ -70,7 +51,7 @@ export const separateTablesBySchema = <T extends TableLike, S, I>(
): Array<I | [S, I] | undefined> => {
const sortedTables = _.chain(tables)
.sortBy((table) => table.name)
- .sortBy((table) => table.schema_name)
+ .sortBy((table) => table.schema)
.value();
return sortedTables.map((table, index, sortedTables) => {
@@ -78,32 +59,31 @@ export const separateTablesBySchema = <T extends TableLike, S, I>(
return;
}
// add schema header for first element and if schema is different from previous
- return index === 0 ||
- sortedTables[index - 1].schema_name !== table.schema_name
+ return index === 0 || sortedTables[index - 1].schema !== table.schema
? [createSchemaSeparator(table), createListItem(table)]
: createListItem(table);
});
};
interface TableListProps {
- entities: Record<string, TableLike>;
- database: { name?: string };
- hasSingleSchema?: boolean;
+ database: Database | undefined;
+ tables: Table[];
loading?: boolean;
loadingError?: unknown;
}
class TableList extends Component<TableListProps> {
render() {
- const { entities, database, hasSingleSchema, loadingError, loading } =
- this.props;
+ const { database, tables, loadingError, loading } = this.props;
- const tables = Object.values(entities);
+ const hasSingleSchema =
+ tables.length === 0 ||
+ tables.every((table) => table.schema === tables[0].schema);
return (
<div data-testid="table-list">
<ReferenceHeader
- name={t`Tables in ${database.name}`}
+ name={t`Tables in ${database?.name}`}
headerIcon="database"
/>
<LoadingAndErrorWrapper
@@ -142,14 +122,4 @@ class TableList extends Component<TableListProps> {
}
// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default connect(
- mapStateToProps,
- // Unjustified type cast. FIXME
-)(
- // `connect` cannot match its inferred props against this component's own
- // props, because the `actions` spread in `mapDispatchToProps` is untyped.
- // The cast restores the props a caller actually passes.
- TableList as unknown as React.ComponentType<
- ReferenceRouteProps & ReferenceLoadingProps
- >,
-);
+export default TableList;
diff --git a/frontend/src/metabase/reference/databases/TableList.unit.spec.tsx b/frontend/src/metabase/reference/databases/TableList.unit.spec.tsx
index fcab60e6b37..29f33529e6a 100644
--- a/frontend/src/metabase/reference/databases/TableList.unit.spec.tsx
+++ b/frontend/src/metabase/reference/databases/TableList.unit.spec.tsx
@@ -1,5 +1,3 @@
-import { createMockState } from "__support__/state";
-import { createMockEntitiesState } from "__support__/store";
import { renderWithProviders, screen, within } from "__support__/ui";
import { getNextId } from "__support__/utils";
import { Route } from "metabase/router";
@@ -38,19 +36,13 @@ const database = createMockDatabase({
tables,
});
-const storeInitialState = createMockState({
- entities: createMockEntitiesState({
- databases: [database],
- }),
-});
-
function setup() {
return renderWithProviders(
<Route
path="/"
- element={<TableList params={{ databaseId: String(databaseId) }} />}
+ element={<TableList database={database} tables={tables} />}
/>,
- { storeInitialState, withRouter: true },
+ { withRouter: true },
);
}
diff --git a/frontend/src/metabase/reference/databases/TableListContainer.tsx b/frontend/src/metabase/reference/databases/TableListContainer.tsx
index 739f1aef4ce..4415b3eb165 100644
--- a/frontend/src/metabase/reference/databases/TableListContainer.tsx
+++ b/frontend/src/metabase/reference/databases/TableListContainer.tsx
@@ -2,7 +2,6 @@ import cx from "classnames";
import { useEffect } from "react";
import { usePrevious } from "react-use";
-import { useGetDatabaseMetadataQuery } from "metabase/api";
import CS from "metabase/css/core/index.css";
import { connect, useSelector } from "metabase/redux";
import { SidebarLayout } from "metabase/reference/components/SidebarLayout";
@@ -13,12 +12,12 @@ import { useLocation, useParams } from "metabase/router";
import type { ClearStateProps } from "../reference";
import {
type ReferenceRouteParams,
- getDatabase,
getDatabaseId,
getIsEditing,
} from "../selectors";
import DatabaseSidebar from "./DatabaseSidebar";
+import { useReferenceDatabase } from "./use-reference-database";
const mapDispatchToProps = {
...actions,
@@ -31,14 +30,10 @@ function TableListContainer(props: TableListContainerProps) {
const previousPathname = usePrevious(pathname);
const params = useParams<ReferenceRouteParams>();
- const database = useSelector((state) => getDatabase(state, { params }));
const databaseId = useSelector((state) => getDatabaseId(state, { params }));
const isEditing = useSelector(getIsEditing);
-
- const { isFetching, error } = useGetDatabaseMetadataQuery({
- id: databaseId,
- skip_fields: true,
- });
+ const { database, tables, isLoading, error } =
+ useReferenceDatabase(databaseId);
useEffect(() => {
const pathnameChanged =
@@ -52,9 +47,19 @@ function TableListContainer(props: TableListContainerProps) {
<SidebarLayout
className={cx(CS.flexFull, CS.relative)}
style={isEditing ? { paddingTop: "43px" } : {}}
- sidebar={<DatabaseSidebar database={database} />}
+ sidebar={
+ <DatabaseSidebar
+ databaseId={databaseId}
+ databaseName={database?.name}
+ />
+ }
>
- <TableList params={params} loading={isFetching} loadingError={error} />
+ <TableList
+ database={database}
+ tables={tables}
+ loading={isLoading}
+ loadingError={error}
+ />
</SidebarLayout>
);
}
diff --git a/frontend/src/metabase/reference/databases/TableListContainer.unit.spec.tsx b/frontend/src/metabase/reference/databases/TableListContainer.unit.spec.tsx
index d37db14e517..90adc32bfa6 100644
--- a/frontend/src/metabase/reference/databases/TableListContainer.unit.spec.tsx
+++ b/frontend/src/metabase/reference/databases/TableListContainer.unit.spec.tsx
@@ -41,7 +41,6 @@ describe("TableListContainer", () => {
it("resolves the database from the route param, not from a prop", async () => {
setup();
- // The name only reaches the header if `useParams` fed `getDatabase`.
expect(
await screen.findAllByText("Tables in Test Database"),
).not.toHaveLength(0);
diff --git a/frontend/src/metabase/reference/databases/TableQuestions.tsx b/frontend/src/metabase/reference/databases/TableQuestions.tsx
index df2a5d1c720..9b0f36e53ea 100644
--- a/frontend/src/metabase/reference/databases/TableQuestions.tsx
+++ b/frontend/src/metabase/reference/databases/TableQuestions.tsx
@@ -14,16 +14,15 @@ import { ListItem } from "metabase/reference/components/ListItem";
import * as Urls from "metabase/urls";
import { visualizations } from "metabase/viz-core";
import type * as Lib from "metabase-lib";
-import type { Card } from "metabase-types/api";
+import type { Card, Table } from "metabase-types/api";
import ReferenceHeader from "../components/ReferenceHeader";
-import type { ReferenceRouteProps, StateWithReference } from "../selectors";
-import { getTable, getTableQuestions } from "../selectors";
-import type { ReferenceLoadingProps, StubbedTable } from "../types";
+import type { StateWithReference } from "../selectors";
+import type { ReferenceLoadingProps } from "../types";
import { getQuestionUrl } from "../utils";
const emptyStateData = (
- table: StubbedTable,
+ table: Table,
metadataProvider: Lib.MetadataProvider,
) => {
return {
@@ -39,33 +38,30 @@ const emptyStateData = (
const mapStateToProps = (
state: StateWithReference,
- props: ReferenceRouteProps,
+ props: Pick<TableQuestionsProps, "table">,
) => ({
- table: getTable(state, props),
- entities: getTableQuestions(state, props),
- metadataProvider: selectMetadataProvider(
- state,
- getTable(state, props)?.db_id ?? null,
- ),
+ metadataProvider: selectMetadataProvider(state, props.table?.db_id ?? null),
});
interface TableQuestionsProps {
- table: StubbedTable;
+ table: Table | undefined;
metadataProvider: Lib.MetadataProvider;
- entities: Card[];
+ cards: Card[];
loading?: boolean;
loadingError?: unknown;
}
class TableQuestions extends Component<TableQuestionsProps> {
render() {
- const { entities, loadingError, loading, table, metadataProvider } =
+ const { cards, loadingError, loading, table, metadataProvider } =
this.props;
+ const questions = cards.filter((card) => card.table_id === table?.id);
+
return (
<div>
<ReferenceHeader
- name={t`Questions about ${this.props.table.display_name}`}
+ name={t`Questions about ${table?.display_name}`}
headerIcon="table2"
/>
<LoadingAndErrorWrapper
@@ -73,32 +69,29 @@ class TableQuestions extends Component<TableQuestionsProps> {
error={loadingError}
>
{() =>
- Object.keys(entities).length > 0 ? (
+ questions.length > 0 ? (
<div className={cx(CS.wrapper, CS.wrapperTrim)}>
<List>
- {Object.values(entities).map(
- (entity) =>
- entity &&
- entity.id &&
- entity.name && (
- <ListItem
- key={entity.id}
- name={entity.name}
- description={t`Created ${dayjs(
- entity.created_at,
- ).fromNow()} by ${entity.creator?.common_name ?? ""}`}
- url={Urls.card(entity)}
- icon={visualizations.get(entity.display)?.iconName}
- />
- ),
- )}
+ {questions.map((question) => (
+ <ListItem
+ key={question.id}
+ name={question.name}
+ description={t`Created ${dayjs(
+ question.created_at,
+ ).fromNow()} by ${question.creator?.common_name ?? ""}`}
+ url={Urls.card(question)}
+ icon={visualizations.get(question.display)?.iconName}
+ />
+ ))}
</List>
</div>
) : (
<div className={S.empty}>
- <AdminAwareEmptyState
- {...emptyStateData(table, metadataProvider)}
- />
+ {table && (
+ <AdminAwareEmptyState
+ {...emptyStateData(table, metadataProvider)}
+ />
+ )}
</div>
)
}
@@ -117,6 +110,6 @@ export default connect(
// props, because the `actions` spread in `mapDispatchToProps` is untyped.
// The cast restores the props a caller actually passes.
TableQuestions as unknown as React.ComponentType<
- ReferenceRouteProps & ReferenceLoadingProps
+ ReferenceLoadingProps & Pick<TableQuestionsProps, "table" | "cards">
>,
);
diff --git a/frontend/src/metabase/reference/databases/TableQuestionsContainer.tsx b/frontend/src/metabase/reference/databases/TableQuestionsContainer.tsx
index 84693a9e3c7..c4e54129975 100644
--- a/frontend/src/metabase/reference/databases/TableQuestionsContainer.tsx
+++ b/frontend/src/metabase/reference/databases/TableQuestionsContainer.tsx
@@ -2,7 +2,7 @@ import cx from "classnames";
import { useEffect } from "react";
import { usePrevious } from "react-use";
-import { useGetDatabaseMetadataQuery, useListCardsQuery } from "metabase/api";
+import { useListCardsQuery } from "metabase/api";
import CS from "metabase/css/core/index.css";
import { connect, useSelector } from "metabase/redux";
import { SidebarLayout } from "metabase/reference/components/SidebarLayout";
@@ -13,13 +13,13 @@ import { useLocation, useParams } from "metabase/router";
import type { ClearStateProps } from "../reference";
import {
type ReferenceRouteParams,
- getDatabase,
getDatabaseId,
getIsEditing,
- getTable,
+ getTableId,
} from "../selectors";
import TableSidebar from "./TableSidebar";
+import { useReferenceTable } from "./use-reference-database";
const mapDispatchToProps = {
...actions,
@@ -32,16 +32,21 @@ function TableQuestionsContainer(props: TableQuestionsContainerProps) {
const previousPathname = usePrevious(pathname);
const params = useParams<ReferenceRouteParams>();
- const database = useSelector((state) => getDatabase(state, { params }));
- const table = useSelector((state) => getTable(state, { params }));
const databaseId = useSelector((state) => getDatabaseId(state, { params }));
+ const tableId = useSelector((state) => getTableId(state, { params }));
const isEditing = useSelector(getIsEditing);
- const { isFetching: isFetchingMetadata, error: metadataError } =
- useGetDatabaseMetadataQuery({ id: databaseId, skip_fields: true });
- const { isFetching: isFetchingCards, error: cardsError } = useListCardsQuery(
- {},
- );
+ const {
+ database,
+ table,
+ isLoading: isLoadingTable,
+ error: tableError,
+ } = useReferenceTable(databaseId, tableId);
+ const {
+ data: cards = [],
+ isFetching: isFetchingCards,
+ error: cardsError,
+ } = useListCardsQuery({});
useEffect(() => {
const pathnameChanged =
@@ -55,12 +60,20 @@ function TableQuestionsContainer(props: TableQuestionsContainerProps) {
<SidebarLayout
className={cx(CS.flexFull, CS.relative)}
style={isEditing ? { paddingTop: "43px" } : {}}
- sidebar={<TableSidebar database={database} table={table} />}
+ sidebar={
+ <TableSidebar
+ databaseId={databaseId}
+ databaseName={database?.name}
+ tableId={tableId}
+ tableName={table?.name}
+ />
+ }
>
<TableQuestions
- params={params}
- loading={isFetchingMetadata || isFetchingCards}
- loadingError={metadataError ?? cardsError}
+ table={table}
+ cards={cards}
+ loading={isLoadingTable || isFetchingCards}
+ loadingError={tableError ?? cardsError}
/>
</SidebarLayout>
);
diff --git a/frontend/src/metabase/reference/databases/TableSidebar.tsx b/frontend/src/metabase/reference/databases/TableSidebar.tsx
index a3747ddce82..60cb4fd09c1 100644
--- a/frontend/src/metabase/reference/databases/TableSidebar.tsx
+++ b/frontend/src/metabase/reference/databases/TableSidebar.tsx
@@ -7,24 +7,31 @@ import CS from "metabase/css/core/index.css";
import S from "metabase/reference/components/Sidebar.module.css";
import { SidebarItem } from "metabase/reference/components/SidebarItem";
import MetabaseSettings from "metabase/utils/settings";
+import type { DatabaseId, TableId } from "metabase-types/api";
import { trackReferenceXRayClicked } from "../analytics";
-import type { StubbedDatabase, StubbedTable } from "../types";
interface TableSidebarProps {
- database: StubbedDatabase;
- table: StubbedTable;
+ databaseId: DatabaseId;
+ databaseName?: string;
+ tableId: TableId;
+ tableName?: string;
}
-const TableSidebar = ({ database, table }: TableSidebarProps) => (
+const TableSidebar = ({
+ databaseId,
+ databaseName,
+ tableId,
+ tableName,
+}: TableSidebarProps) => (
<div className={S.sidebar}>
<div>
<Breadcrumbs
className={cx(CS.py4, CS.ml3)}
crumbs={[
[t`Databases`, "/reference/databases"],
- [database.name, `/reference/databases/${database.id}`],
- [table.name],
+ [databaseName, `/reference/databases/${databaseId}`],
+ [tableName],
]}
inSidebar={true}
placeholder={t`Data Reference`}
@@ -32,27 +39,27 @@ const TableSidebar = ({ database, table }: TableSidebarProps) => (
</div>
<ol className={CS.mx3}>
<SidebarItem
- key={`/reference/databases/${database.id}/tables/${table.id}`}
- href={`/reference/databases/${database.id}/tables/${table.id}`}
+ key={`/reference/databases/${databaseId}/tables/${tableId}`}
+ href={`/reference/databases/${databaseId}/tables/${tableId}`}
icon="document"
name={t`Details`}
/>
<SidebarItem
- key={`/reference/databases/${database.id}/tables/${table.id}/fields`}
- href={`/reference/databases/${database.id}/tables/${table.id}/fields`}
+ key={`/reference/databases/${databaseId}/tables/${tableId}/fields`}
+ href={`/reference/databases/${databaseId}/tables/${tableId}/fields`}
icon="field"
name={t`Fields in this table`}
/>
<SidebarItem
- key={`/reference/databases/${database.id}/tables/${table.id}/questions`}
- href={`/reference/databases/${database.id}/tables/${table.id}/questions`}
+ key={`/reference/databases/${databaseId}/tables/${tableId}/questions`}
+ href={`/reference/databases/${databaseId}/tables/${tableId}/questions`}
icon="folder"
name={t`Questions about this table`}
/>
{MetabaseSettings.get("enable-xrays") && (
<SidebarItem
- key={`/auto/dashboard/table/${table.id}`}
- href={`/auto/dashboard/table/${table.id}`}
+ key={`/auto/dashboard/table/${tableId}`}
+ href={`/auto/dashboard/table/${tableId}`}
icon="bolt"
name={t`X-ray this table`}
onClick={() => trackReferenceXRayClicked("table")}
diff --git a/frontend/src/metabase/reference/databases/use-reference-database.ts b/frontend/src/metabase/reference/databases/use-reference-database.ts
new file mode 100644
index 00000000000..935738241e8
--- /dev/null
+++ b/frontend/src/metabase/reference/databases/use-reference-database.ts
@@ -0,0 +1,67 @@
+import {
+ skipToken,
+ useGetDatabaseMetadataQuery,
+ useGetTableQueryMetadataQuery,
+} from "metabase/api";
+import type { DatabaseId, TableId } from "metabase-types/api";
+
+/**
+ * The database a reference page names itself after, along with the tables it
+ * lists. Fields are left out: only the field pages need them, and they ask for
+ * the one table they show.
+ */
+export function useReferenceDatabase(databaseId: DatabaseId) {
+ const {
+ data: database,
+ isLoading,
+ error,
+ } = useGetDatabaseMetadataQuery(
+ Number.isFinite(databaseId)
+ ? { id: databaseId, skip_fields: true }
+ : skipToken,
+ );
+
+ return { database, tables: database?.tables ?? [], isLoading, error };
+}
+
+/**
+ * A table named by the route, taken from its database's table list.
+ */
+export function useReferenceTable(databaseId: DatabaseId, tableId: TableId) {
+ const { database, tables, isLoading, error } =
+ useReferenceDatabase(databaseId);
+
+ return {
+ database,
+ tables,
+ table: tables.find(({ id }) => id === tableId),
+ isLoading,
+ error,
+ };
+}
+
+/**
+ * A table with its fields, which the field pages read their columns from.
+ */
+export function useReferenceTableFields(
+ databaseId: DatabaseId,
+ tableId: TableId,
+) {
+ const { database } = useReferenceDatabase(databaseId);
+
+ const {
+ data: table,
+ isLoading,
+ error,
+ } = useGetTableQueryMetadataQuery(
+ Number.isFinite(tableId) ? { id: tableId } : skipToken,
+ );
+
+ return {
+ database,
+ table,
+ fields: table?.fields ?? [],
+ isLoading,
+ error,
+ };
+}
diff --git a/frontend/src/metabase/reference/selectors.ts b/frontend/src/metabase/reference/selectors.ts
index da38ba9a39b..14e7e353861 100644
--- a/frontend/src/metabase/reference/selectors.ts
+++ b/frontend/src/metabase/reference/selectors.ts
@@ -1,16 +1,7 @@
import { createSelector } from "@reduxjs/toolkit";
import { getIn } from "icepick";
-import {
- getShallowDatabases as getDatabases,
- getShallowFields as getFields,
- getShallowTables as getTables,
-} from "metabase/metadata-store";
import type { State } from "metabase/redux/store";
-import type { Card } from "metabase-types/api";
-
-import type { StubbedDatabase, StubbedField, StubbedTable } from "./types";
-import { idsToObjectMap } from "./utils";
// A `type`, not an `interface`, so `useParams<ReferenceRouteParams>()` accepts
// it: the hook's constraint needs an implicit index signature.
@@ -46,39 +37,11 @@ export const getSegmentId = (_state: State, props: ReferenceRouteProps) =>
export const getDatabaseId = (_state: State, props: ReferenceRouteProps) =>
Number.parseInt(props.params.databaseId ?? "");
-export const getDatabase = createSelector(
- [getDatabaseId, getDatabases],
- (databaseId, databases): StubbedDatabase =>
- databases?.[databaseId] || { id: databaseId },
-);
-
export const getTableId = (_state: State, props: ReferenceRouteProps) =>
Number.parseInt(props.params.tableId ?? "");
-// export const getTableId = (state, props) => Number.parseInt(props.params.tableId);
-export const getTablesByDatabase = createSelector(
- [getTables, getDatabase],
- (tables, database) =>
- tables && database.tables ? idsToObjectMap(database.tables, tables) : {},
-);
-export const getTable = createSelector(
- [getTableId, getTables],
- (tableId, tables): StubbedTable =>
- tableId ? tables?.[tableId] || { id: tableId } : { id: 0 },
-);
export const getFieldId = (_state: State, props: ReferenceRouteProps) =>
Number.parseInt(props.params.fieldId ?? "");
-export const getFieldsByTable = createSelector(
- [getTable, getFields],
- (table, fields) => (table.fields ? idsToObjectMap(table.fields, fields) : {}),
-);
-export const getField = createSelector(
- [getFieldId, getFields],
- (fieldId, fields): StubbedField => fields?.[fieldId] || { id: fieldId },
-);
-
-const getQuestions = (state: State) =>
- getIn(state, ["entities", "questions"]) || {};
const getRevisions = (state: State) =>
// Unjustified type cast. FIXME
@@ -89,30 +52,6 @@ export const getSegmentRevisions = createSelector(
(segmentId, revisions) => getIn(revisions, ["segment", segmentId]) || {},
);
-export const getTableQuestions = createSelector(
- [getTable, getQuestions],
- (table, questions): Card[] => {
- const tableId = table.id;
- // Unjustified type cast. FIXME
- return Object.values(questions as Record<string, Card>).filter(
- (question) => question.table_id === tableId,
- );
- },
-);
-
-export const getHasSingleSchema = createSelector(
- [getTablesByDatabase],
- (tables) => {
- const list = Object.values(tables);
- // NOTE: original compared each row's `schema_name` to the first row's
- // `schema` (different fields). Behavior preserved verbatim — likely a
- // pre-existing bug, but out of scope for the TS conversion.
- return list.length > 0
- ? list.every((table) => table.schema_name === list[0].schema)
- : true;
- },
-);
-
export const getIsEditing = (state: State) =>
// Unjustified type cast. FIXME
(state as StateWithReference).reference.isEditing;
diff --git a/frontend/src/metabase/reference/utils.ts b/frontend/src/metabase/reference/utils.ts
index feb877189a2..6671a67b117 100644
--- a/frontend/src/metabase/reference/utils.ts
+++ b/frontend/src/metabase/reference/utils.ts
@@ -14,20 +14,6 @@ import type {
import type { SegmentId } from "metabase-types/api/segment";
import type { TableId } from "metabase-types/api/table";
-export const idsToObjectMap = <T extends { id: unknown }>(
- ids: ReadonlyArray<string | number>,
- objects: Record<string, T>,
-): Record<string, T> =>
- ids
- .map((id) => objects[id])
- .reduce<Record<string, T>>(
- (map, object) => ({ ...map, [String(object.id)]: object }),
- {},
- );
-// recursive freezing done by assoc here is too expensive
-// hangs browser for large databases
-// .reduce((map, object) => assoc(map, object.id, object), {});
-
export const filterUntouchedFields = (
fields: Record<string, unknown>,
entity: Record<string, unknown> = {},
diff --git a/frontend/src/metabase/reference/utils.unit.spec.ts b/frontend/src/metabase/reference/utils.unit.spec.ts
index 5f4931d69b3..368069b7342 100644
--- a/frontend/src/metabase/reference/utils.unit.spec.ts
+++ b/frontend/src/metabase/reference/utils.unit.spec.ts
@@ -16,17 +16,16 @@ describe("Reference utils.js", () => {
describe("tablesToSchemaSeparatedTables()", () => {
it("should add schema separator to appropriate locations and sort tables by name", () => {
const tables = {
- 1: { id: 1, name: "Toucan", schema_name: "foo" },
- 2: { id: 2, name: "Elephant", schema_name: "bar" },
- 3: { id: 3, name: "Giraffe", schema_name: "boo" },
- 4: { id: 4, name: "Wombat", schema_name: "bar" },
- 5: { id: 5, name: "Anaconda", schema_name: "foo" },
- 6: { id: 6, name: "Buffalo", schema_name: "bar" },
+ 1: { id: 1, name: "Toucan", schema: "foo" },
+ 2: { id: 2, name: "Elephant", schema: "bar" },
+ 3: { id: 3, name: "Giraffe", schema: "boo" },
+ 4: { id: 4, name: "Wombat", schema: "bar" },
+ 5: { id: 5, name: "Anaconda", schema: "foo" },
+ 6: { id: 6, name: "Buffalo", schema: "bar" },
};
- const createSchemaSeparator = (table: { schema_name: string }) =>
- table.schema_name;
- const createListItem = (table: { schema_name: string }) => table;
+ const createSchemaSeparator = (table: { schema: string }) => table.schema;
+ const createListItem = (table: { schema: string }) => table;
const schemaSeparatedTables = separateTablesBySchema(
tables,
@@ -35,12 +34,12 @@ describe("Reference utils.js", () => {
);
expect(schemaSeparatedTables).toEqual([
- ["bar", { id: 6, name: "Buffalo", schema_name: "bar" }],
- { id: 2, name: "Elephant", schema_name: "bar" },
- { id: 4, name: "Wombat", schema_name: "bar" },
- ["boo", { id: 3, name: "Giraffe", schema_name: "boo" }],
- ["foo", { id: 5, name: "Anaconda", schema_name: "foo" }],
- { id: 1, name: "Toucan", schema_name: "foo" },
+ ["bar", { id: 6, name: "Buffalo", schema: "bar" }],
+ { id: 2, name: "Elephant", schema: "bar" },
+ { id: 4, name: "Wombat", schema: "bar" },
+ ["boo", { id: 3, name: "Giraffe", schema: "boo" }],
+ ["foo", { id: 5, name: "Anaconda", schema: "foo" }],
+ { id: 1, name: "Toucan", schema: "foo" },
]);
});
});