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
Data Reference – Glossary (#63576)
Stas Gavrylov0efa8eac5b6f
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 1b956112090..9a8fa5fa806 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -547,6 +547,13 @@settingsutil}}+ glossary+ {:team "Workflows"+ :api #{metabase.glossary.api}+ :uses #{api+ models+ util}}+indexed-entities{:team "UX West":api #{metabase.indexed-entities.apidiff --git a/e2e/test/scenarios/data-reference/glossary.cy.spec.ts b/e2e/test/scenarios/data-reference/glossary.cy.spec.tsnew file mode 100644index 00000000000..d583d41e4cb--- /dev/null+++ b/e2e/test/scenarios/data-reference/glossary.cy.spec.ts@@ -0,0 +1,122 @@+const { H } = cy;++describe("data reference > glossary", () => {+ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ });++ function visitGlossary() {+ cy.visit("/reference/glossary");+ }++ it("fetches existing definitions", () => {+ cy.intercept("GET", "/api/glossary", {+ statusCode: 200,+ body: {+ data: [+ { id: 1, term: "Alpha", definition: "First" },+ { id: 2, term: "Beta", definition: "Second" },+ ],+ },+ }).as("getGlossary");++ visitGlossary();++ cy.wait("@getGlossary");+ cy.get("table").within(() => {+ cy.findByText("Alpha").should("be.visible");+ cy.findByText("Beta").should("be.visible");+ });+ });++ it("creates a new definition and makes POST /api/glossary with trimmed values", () => {+ cy.intercept("POST", "/api/glossary", (req) => {+ expect(req.body).to.deep.equal({+ term: "Bird",+ definition: "A thing with wings.",+ });+ }).as("createGlossary");++ visitGlossary();++ cy.findByRole("button", { name: /new term/i }).click();++ cy.findByPlaceholderText(/bird/i).type(" Bird ");+ cy.findByPlaceholderText(/a warm-blooded.*/i).type(+ " A thing with wings. ",+ );++ cy.findByLabelText("Save").click();++ cy.wait("@createGlossary");++ cy.get("table").within(() => {+ cy.findByText("Bird").should("be.visible");+ cy.findByText("A thing with wings.").should("be.visible");+ });+ });++ it("updates an existing definition and makes PUT /api/glossary/:id", () => {+ cy.request("POST", "/api/glossary", {+ term: "Cat",+ definition: "Meows",+ }).then(({ body }) => {+ const { id } = body;++ cy.intercept("PUT", `/api/glossary/${id}`, (req) => {+ expect(req.body).to.deep.equal({+ term: "Kitten",+ definition: "Young cat",+ });+ }).as("updateGlossary");++ visitGlossary();++ cy.get("table").within(() => {+ cy.findByText("Cat").click();+ });++ cy.findByPlaceholderText(/bird/i).clear().type("Kitten");+ cy.findByPlaceholderText(/a warm-blooded.*/i)+ .clear()+ .type("Young cat");++ cy.findByRole("button", { name: /save/i }).click();++ cy.wait("@updateGlossary");++ cy.get("table").within(() => {+ cy.findByText("Kitten").should("be.visible");+ cy.findByText("Young cat").should("be.visible");+ });+ });+ });++ it("deletes an existing definition and makes DELETE /api/glossary/:id", () => {+ cy.request("POST", "/api/glossary", {+ term: "DeleteMe",+ definition: "To be removed",+ }).then(({ body }) => {+ const { id } = body;+ cy.intercept("DELETE", `/api/glossary/${id}`).as("deleteGlossary");++ visitGlossary();++ cy.get("table").within(() => {+ cy.findByText("DeleteMe").should("be.visible").realHover();+ cy.findByRole("button", { name: /delete/i }).click();+ });++ cy.findByRole("dialog").within(() => {+ cy.findByRole("button", { name: /delete/i }).click();+ });++ cy.wait("@deleteGlossary");++ cy.get("table").within(() => {+ cy.findByText("DeleteMe").should("not.exist");+ });+ });+ });+});diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/ingest.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/ingest.cljindex 78e9205b73c..ef00c8f9860 100644--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/ingest.clj+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/ingest.clj@@ -58,7 +58,7 @@read-timestamps))(def legal-top-level-paths "Known top-level paths for directory with serialization output"- #{"actions" "collections" "databases" "snippets"}) ; But return the hierarchy without labels.+ #{"actions" "collections" "databases" "snippets" "glossary"}) ; But return the hierarchy without labels.(defn- ingest-all [^File root-dir];; This returns a map {unlabeled-hierarchy [original-hierarchy File]}.diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.cljindex 69e4a02d82b..28fb3ac0631 100644--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj@@ -17,6 +17,7 @@"Collection""Dashboard""Document"+ "Glossary""NativeQuerySnippet""Timeline"])diff --git a/enterprise/backend/test/metabase_enterprise/models/entity_id_test.clj b/enterprise/backend/test/metabase_enterprise/models/entity_id_test.cljindex 10cc6f10d9f..12dcf8ea565 100644--- a/enterprise/backend/test/metabase_enterprise/models/entity_id_test.clj+++ b/enterprise/backend/test/metabase_enterprise/models/entity_id_test.clj@@ -23,7 +23,9 @@:model/FieldValues:model/FieldUserSettings;; Settings have human-selected unique names.- :model/Setting})+ :model/Setting+ ;; Glossary items have unique `term` key+ :model/Glossary})(def ^:private entities-not-exported"Entities that are either:diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.cljindex b1ee8002dcd..47e2378d7a2 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj@@ -1935,3 +1935,12 @@:DIMENSION [(str "$_card:" card-entity-id "_name")]}}}result (serdes/export-visualizer-settings input)](is (= expected result))))))))++(deftest glossary-test+ (testing "Glossary entries are extracted well"+ (mt/with-temp [:model/Glossary _ {:term "foobar"+ :definition "It's foobar2000 actually"}]+ (let [ser (serdes/extract-one "Glossary" {} (t2/select-one :model/Glossary :term "foobar"))]+ (is (=? {:serdes/meta [{:model "Glossary" :id "foobar"}]+ :term "foobar"}+ ser))))))diff --git a/frontend/src/metabase/api/glossary.ts b/frontend/src/metabase/api/glossary.tsnew file mode 100644index 00000000000..97d1ed7f670--- /dev/null+++ b/frontend/src/metabase/api/glossary.ts@@ -0,0 +1,162 @@+import { Api } from "./api";+import { idTag, invalidateTags, listTag } from "./tags";++export type GlossaryItem = {+ id: number;+ term: string;+ definition: string;+};++export type ListGlossaryRequest = {+ search?: string;+};++export type CreateGlossaryRequest = {+ term: string;+ definition: string;+};++export type UpdateGlossaryRequest = {+ id: number;+ term: string;+ definition: string;+};++export const glossaryApi = Api.injectEndpoints({+ endpoints: (builder) => ({+ listGlossary: builder.query<GlossaryItem[], ListGlossaryRequest | void>({+ query: (params) => ({+ method: "GET",+ url: "/api/glossary",+ params,+ }),+ transformResponse: (response: { data: GlossaryItem[] }) => response.data,+ providesTags: (items = []) => [+ listTag("glossary"),+ ...items.map((item) => idTag("glossary", item.id)),+ ],+ }),+ createGlossary: builder.mutation<GlossaryItem, CreateGlossaryRequest>({+ query: (body) => ({+ method: "POST",+ url: "/api/glossary",+ body,+ }),+ // Optimistically add the new item to the list cache+ async onQueryStarted(arg, { dispatch, queryFulfilled }) {+ const tempId = Date.now();+ const patchResult = dispatch(+ glossaryApi.util.updateQueryData(+ "listGlossary",+ undefined,+ (draft) => {+ // Add a temporary item to appear immediately+ draft.unshift({+ id: tempId,+ term: arg.term,+ definition: arg.definition,+ });+ },+ ),+ );++ try {+ const { data } = await queryFulfilled;+ // Replace temporary item with the server response+ dispatch(+ glossaryApi.util.updateQueryData(+ "listGlossary",+ undefined,+ (draft) => {+ const idx = draft.findIndex((g) => g.id === tempId);+ if (idx !== -1) {+ draft[idx] = data;+ } else {+ draft.unshift(data);+ }+ },+ ),+ );+ } catch {+ // Revert if the request failed+ patchResult.undo();+ }+ },+ invalidatesTags: (item, error) =>+ item ? invalidateTags(error, [listTag("glossary")]) : [],+ }),+ updateGlossary: builder.mutation<GlossaryItem, UpdateGlossaryRequest>({+ query: ({ id, ...body }) => ({+ method: "PUT",+ url: `/api/glossary/${id}`,+ body,+ }),++ async onQueryStarted(arg, { dispatch, queryFulfilled }) {+ const patchResult = dispatch(+ glossaryApi.util.updateQueryData(+ "listGlossary",+ undefined,+ (draft) => {+ const item = draft.find((g) => g.id === arg.id);+ if (item) {+ item.term = arg.term;+ item.definition = arg.definition;+ }+ },+ ),+ );++ try {+ await queryFulfilled;+ // No action needed; server result matches optimistic update+ } catch {+ patchResult.undo();+ }+ },+ invalidatesTags: (item, error) =>+ item+ ? invalidateTags(error, [+ listTag("glossary"),+ idTag("glossary", item.id),+ ])+ : [],+ }),+ deleteGlossary: builder.mutation<void, { id: number }>({+ query: ({ id }) => ({+ method: "DELETE",+ url: `/api/glossary/${id}`,+ }),++ async onQueryStarted({ id }, { dispatch, queryFulfilled }) {+ const patchResult = dispatch(+ glossaryApi.util.updateQueryData(+ "listGlossary",+ undefined,+ (draft) => {+ const idx = draft.findIndex((g) => g.id === id);+ if (idx !== -1) {+ draft.splice(idx, 1);+ }+ },+ ),+ );++ try {+ await queryFulfilled;+ } catch {+ patchResult.undo();+ }+ },+ invalidatesTags: (_, error, { id }) =>+ invalidateTags(error, [listTag("glossary"), idTag("glossary", id)]),+ }),+ }),+});++export const {+ useListGlossaryQuery,+ useCreateGlossaryMutation,+ useUpdateGlossaryMutation,+ useDeleteGlossaryMutation,+} = glossaryApi;diff --git a/frontend/src/metabase/api/index.ts b/frontend/src/metabase/api/index.tsindex 0b6a9fc0c05..d93f667c22e 100644--- a/frontend/src/metabase/api/index.ts+++ b/frontend/src/metabase/api/index.ts@@ -12,6 +12,7 @@ export * from "./collection";export * from "./dashboard";export * from "./database";export * from "./dataset";+export * from "./glossary";export * from "./entity-id";export * from "./field";export * from "./google";diff --git a/frontend/src/metabase/api/tags/constants.ts b/frontend/src/metabase/api/tags/constants.tsindex c06daefa989..99999866831 100644--- a/frontend/src/metabase/api/tags/constants.ts+++ b/frontend/src/metabase/api/tags/constants.ts@@ -17,6 +17,7 @@ export const TAG_TYPES = ["embedding-hub-checklist","field","field-values",+ "glossary","indexed-entity","logger-preset","model-index",diff --git a/frontend/src/metabase/reference/glossary/Glossary.module.css b/frontend/src/metabase/reference/glossary/Glossary.module.cssnew file mode 100644index 00000000000..e5176fbacbe--- /dev/null+++ b/frontend/src/metabase/reference/glossary/Glossary.module.css@@ -0,0 +1,54 @@+.card {+ box-shadow: 0 0.5rem 1.25rem var(--mb-color-shadow);+}++.table {+ table-layout: fixed;+ background-color: var(--mb-color-bg-white);+ border: none;++ th {+ padding-block: var(--mantine-spacing-sm);+ width: 50px;+ }++ td {+ padding: var(--mantine-spacing-sm) var(--mantine-spacing-md)+ var(--mantine-spacing-sm) var(--mantine-spacing-md);+ }++ tr:last-child td {+ border-bottom-color: transparent;+ }+}++.row {+ cursor: pointer;++ &:hover {+ .action {+ visibility: visible;+ }+ }+}++.rowEditor {+ td {+ padding-top: 0;+ padding-bottom: 4px;+ line-height: 1.2;+ }++ &:hover {+ background-color: transparent !important;+ }+}++.action {+ visibility: hidden;+}++.input {+ border: none;+ padding-inline: 0 !important;+}diff --git a/frontend/src/metabase/reference/glossary/GlossaryContainer.tsx b/frontend/src/metabase/reference/glossary/GlossaryContainer.tsxnew file mode 100644index 00000000000..44de240e515--- /dev/null+++ b/frontend/src/metabase/reference/glossary/GlossaryContainer.tsx@@ -0,0 +1,65 @@+import cx from "classnames";+import { t } from "ttag";++import {+ useCreateGlossaryMutation,+ useDeleteGlossaryMutation,+ useListGlossaryQuery,+ useUpdateGlossaryMutation,+} from "metabase/api";+import SidebarLayout from "metabase/common/components/SidebarLayout";+import CS from "metabase/css/core/index.css";+import BaseSidebar from "metabase/reference/guide/BaseSidebar";+import { Card, Group, Stack, Text } from "metabase/ui";++import S from "./Glossary.module.css";+import { GlossaryTable } from "./GlossaryTable";++export function GlossaryContainer() {+ const { data: glossary = [] } = useListGlossaryQuery();+ const [createGlossary] = useCreateGlossaryMutation();+ const [updateGlossary] = useUpdateGlossaryMutation();+ const [deleteGlossary] = useDeleteGlossaryMutation();++ return (+ <SidebarLayout+ className={cx(CS.flexFull, CS.relative)}+ sidebar={<BaseSidebar />}+ >+ <Stack w="100%">+ <Group+ align="center"+ wrap="nowrap"+ px="2.625rem"+ h="3rem"+ mt="2rem"+ justify="space-between"+ >+ <Text fw="bold" fz="1.5rem">{t`Glossary`}</Text>+ </Group>+ <Stack+ w="100%"+ gap={0}+ m={0}+ className={cx(CS.wrapper, CS.wrapperTrim)}+ >+ <Card px="lg" className={cx(CS.bordered, S.card)}>+ <GlossaryTable+ className={S.table}+ glossary={glossary}+ onCreate={async (term, definition) => {+ await createGlossary({ term, definition });+ }}+ onEdit={async (id, term, definition) => {+ await updateGlossary({ id, term, definition });+ }}+ onDelete={async (id) => {+ await deleteGlossary({ id });+ }}+ />+ </Card>+ </Stack>+ </Stack>+ </SidebarLayout>+ );+}diff --git a/frontend/src/metabase/reference/glossary/GlossaryRowEditor.tsx b/frontend/src/metabase/reference/glossary/GlossaryRowEditor.tsxnew file mode 100644index 00000000000..52196f9e140--- /dev/null+++ b/frontend/src/metabase/reference/glossary/GlossaryRowEditor.tsx@@ -0,0 +1,144 @@+import { useHotkeys } from "@mantine/hooks";+import { useCallback, useEffect, useRef, useState } from "react";+import { t } from "ttag";++import type { GlossaryItem } from "metabase/api";+import {+ ActionIcon,+ Box,+ Group,+ Icon,+ TextInput,+ Textarea,+ Tooltip,+} from "metabase/ui";++import S from "./Glossary.module.css";++type GlossaryRowEditorProps = {+ item: Pick<GlossaryItem, "term" | "definition">;+ onSave: (term: string, definition: string) => void | Promise<void>;+ onCancel: () => void;+ autoFocusField?: "term" | "definition";+};++export function GlossaryRowEditor({+ item,+ onSave,+ onCancel,+ autoFocusField = "term",+}: GlossaryRowEditorProps) {+ const [term, setTerm] = useState(item.term);+ const [definition, setDefinition] = useState(item.definition);++ const canSave = term.trim() !== "" && definition.trim() !== "";++ const save = useCallback(() => {+ void onSave(term.trim(), definition.trim());+ onCancel();+ }, [onSave, onCancel, term, definition]);++ useHotkeys(+ [+ ["mod+Enter", save],+ ["Escape", onCancel],+ ],+ [],+ );++ const { termRef, definitionRef } = useFocusOnMount(autoFocusField);++ return (+ <>+ <Box component="td" valign="top">+ <TextInput+ classNames={{+ input: S.input,+ }}+ fw="bold"+ variant="unstyled"+ autoFocus={autoFocusField === "term"}+ placeholder={t`Bird`}+ value={term}+ onChange={(e) => setTerm(e.currentTarget.value)}+ miw="8rem"+ ref={termRef}+ />+ </Box>+ <Box component="td" valign="top" pr="0">+ <Textarea+ classNames={{+ input: S.input,+ }}+ variant="unstyled"+ placeholder={t`A warm-blooded, egg-laying vertebrate of the class Aves.`}+ value={definition}+ onChange={(e) => setDefinition(e.currentTarget.value)}+ autosize+ minRows={1}+ maxRows={6}+ autoFocus={autoFocusField === "definition"}+ styles={{+ input: {+ paddingTop: "0.75rem",+ paddingBottom: "0.25rem",+ lineHeight: 1.2,+ },+ }}+ ref={definitionRef}+ />+ </Box>+ <Box component="td" valign="top" align="center" px="md" pt="sm" pb={0}>+ <Group justify="flex-end" gap="xs" wrap="nowrap">+ <Tooltip label={t`Cancel`}>+ <ActionIcon+ aria-label={t`Cancel`}+ variant="subtle"+ onClick={onCancel}+ >+ <Icon name="close" />+ </ActionIcon>+ </Tooltip>+ <Tooltip label={t`Save`}>+ <ActionIcon+ aria-label={t`Save`}+ variant={canSave ? "filled" : "subtle"}+ disabled={!canSave}+ onClick={save}+ >+ <Icon name="check" />+ </ActionIcon>+ </Tooltip>+ </Group>+ </Box>+ </>+ );+}++function useFocusOnMount(autoFocusField: "term" | "definition") {+ const termRef = useRef<HTMLInputElement>(null);+ const definitionRef = useRef<HTMLTextAreaElement>(null);++ useEffect(() => {+ if (autoFocusField === "term" && termRef.current) {+ const el = termRef.current;+ el.focus();+ const len = el.value.length;+ el.setSelectionRange(len, len);+ }+ }, [autoFocusField]);++ useEffect(() => {+ if (autoFocusField === "definition" && definitionRef.current) {+ const el = definitionRef.current;+ el.focus();+ const len = el.value.length;+ el.setSelectionRange(len, len);+ }+ }, [autoFocusField]);++ return {+ termRef,+ definitionRef,+ };+}diff --git a/frontend/src/metabase/reference/glossary/GlossaryTable.tsx b/frontend/src/metabase/reference/glossary/GlossaryTable.tsxnew file mode 100644index 00000000000..a2b414fdfb1--- /dev/null+++ b/frontend/src/metabase/reference/glossary/GlossaryTable.tsx@@ -0,0 +1,239 @@+import cx from "classnames";+import { useMemo, useState } from "react";+import { t } from "ttag";++import { EmptyState } from "metabase/actions/containers/ActionPicker/ActionPicker.styled";+import type { GlossaryItem } from "metabase/api";+import { ConfirmModal } from "metabase/common/components/ConfirmModal";+import { Table as CommonTable } from "metabase/common/components/Table/Table";+import { NoObjectError } from "metabase/common/components/errors/NoObjectError";+import { useHasTokenFeature } from "metabase/common/hooks";+import {+ ActionIcon,+ Box,+ Button,+ Center,+ Group,+ Icon,+ Text,+ Tooltip,+} from "metabase/ui";+import { SortDirection } from "metabase-types/api/sorting";++import S from "./Glossary.module.css";+import { GlossaryRowEditor } from "./GlossaryRowEditor";++export type GlossaryTableProps = {+ className?: string;+ glossary: GlossaryItem[];+ onCreate: (term: string, definition: string) => Promise<void> | void;+ onEdit: (+ id: number,+ term: string,+ definition: string,+ ) => Promise<void> | void;+ onDelete: (id: number) => Promise<void> | void;+};++export function GlossaryTable({+ className,+ glossary,+ onCreate,+ onEdit,+ onDelete,+}: GlossaryTableProps) {+ const [isCreating, setIsCreating] = useState(false);+ const [editingId, setEditingId] = useState<number | null>(null);+ const [editingField, setEditingField] = useState<+ "term" | "definition" | null+ >(null);+ const [deletingItem, setDeletingItem] = useState<GlossaryItem | null>(null);+ const [sortColumnName, setSortColumnName] = useState<+ keyof GlossaryItem | null+ >(null);+ const [sortDirection, setSortDirection] = useState<SortDirection>(+ SortDirection.Asc,+ );++ const hasMetabot = useHasTokenFeature("metabot_v3");++ const sortedRows = useMemo(() => {+ if (!sortColumnName) {+ return [+ ...(isCreating ? [{ id: -1, kind: "create" as const }] : []),+ ...glossary,+ ];+ }+ const data = glossary.toSorted((a, b) => {+ const ak = a[sortColumnName] ?? "";+ const bk = b[sortColumnName] ?? "";+ const cmp = String(ak).localeCompare(String(bk));+ return sortDirection === SortDirection.Asc ? cmp : -cmp;+ });+ return [+ ...(isCreating ? [{ id: -1, kind: "create" as const }] : []),+ ...data,+ ];+ }, [isCreating, glossary, sortColumnName, sortDirection]);++ return (+ <>+ <Group justify="space-between" mb="xs">+ <Text>+ {hasMetabot+ ? t`Define terms to help your team and Metabot understand your data.`+ : t`Define terms to help your team understand your data.`}+ </Text>+ <Button+ variant="default"+ size="sm"+ leftSection={<Icon name="add" />}+ onClick={() => {+ if (editingId) {+ setEditingId(null);+ setEditingField(null);+ }+ setIsCreating(true);+ }}+ >+ {t`New term`}+ </Button>+ </Group>+ <CommonTable+ className={cx(S.table, className)}+ columns={[+ { name: t`Term`, key: "term", sortable: true },+ { name: t`Definition`, key: "definition", sortable: true },+ { name: "", key: "actions", sortable: false },+ ]}+ rows={sortedRows}+ cols={+ <>+ <col style={{ width: "22.5%" }} />+ <col style={{ width: "65%" }} />+ <col style={{ width: "5rem" }} />+ </>+ }+ emptyBody={+ <Center>+ <EmptyState+ message={t`No terms yet`}+ illustrationElement={<NoObjectError mb="-1.5rem" />}+ />+ </Center>+ }+ sortColumnName={sortColumnName}+ sortDirection={sortDirection}+ onSort={(column, dir) => {+ setSortColumnName(column as keyof GlossaryItem);+ setSortDirection(dir);+ }}+ rowRenderer={(row) => {+ // Create row+ if ("kind" in row && row.kind === "create") {+ return (+ <tr className={cx(S.row, S.rowEditor)}>+ <GlossaryRowEditor+ item={{ term: "", definition: "" }}+ onCancel={() => setIsCreating(false)}+ onSave={async (term, definition) => {+ await onCreate(term, definition);+ setIsCreating(false);+ }}+ />+ </tr>+ );+ }++ const item = row as GlossaryItem;+ const isEditing = editingId === item.id;++ return (+ <tr className={cx(S.row, { [S.rowEditor]: isEditing })}>+ {isEditing ? (+ <GlossaryRowEditor+ item={item}+ autoFocusField={editingField ?? "term"}+ onCancel={() => setEditingId(null)}+ onSave={async (newTerm, newDefinition) => {+ await onEdit(item.id, newTerm, newDefinition);+ setEditingId(null);+ setEditingField(null);+ }}+ />+ ) : (+ <>+ <Box+ component="td"+ valign="top"+ onClick={() => {+ if (isCreating) {+ setIsCreating(false);+ }++ setEditingId(item.id);+ setEditingField("term");+ }}+ >+ <Text lh="1.2" fw="bold" pt="xs">+ {item.term}+ </Text>+ </Box>+ <Box+ component="td"+ valign="top"+ style={{ wordBreak: "break-word", whiteSpace: "pre-wrap" }}+ onClick={() => {+ if (isCreating) {+ setIsCreating(false);+ }+ setEditingId(item.id);+ setEditingField("definition");+ }}+ >+ <Text lh="1.2" pt="xs">+ {item.definition}+ </Text>+ </Box>++ <Box+ component="td"+ valign="top"+ align="center"+ p="sm"+ w="25px"+ >+ <Tooltip label={t`Delete`}>+ <ActionIcon+ aria-label={t`Delete`}+ variant="subtle"+ c="text-light"+ className={cx(S.action)}+ onClick={() => setDeletingItem(item)}+ >+ <Icon name="trash" />+ </ActionIcon>+ </Tooltip>+ </Box>+ </>+ )}+ </tr>+ );+ }}+ />+ <ConfirmModal+ opened={deletingItem != null}+ title={t`Delete “${deletingItem?.term}”?`}+ confirmButtonText={t`Delete`}+ message={t`This can't be undone.`}+ onClose={() => setDeletingItem(null)}+ onConfirm={async () => {+ if (deletingItem) {+ await onDelete(deletingItem.id);+ setDeletingItem(null);+ }+ }}+ />+ </>+ );+}diff --git a/frontend/src/metabase/reference/glossary/GlossaryTable.unit.spec.tsx b/frontend/src/metabase/reference/glossary/GlossaryTable.unit.spec.tsxnew file mode 100644index 00000000000..36a9118d714--- /dev/null+++ b/frontend/src/metabase/reference/glossary/GlossaryTable.unit.spec.tsx@@ -0,0 +1,249 @@+import userEvent from "@testing-library/user-event";++import { renderWithProviders, screen, within } from "__support__/ui";+import type { GlossaryItem } from "metabase/api";++import { GlossaryTable } from "./GlossaryTable";++function makeItem(overrides: Partial<GlossaryItem> = {}): GlossaryItem {+ return {+ id: overrides.id ?? 1,+ term: overrides.term ?? "Alpha",+ definition: overrides.definition ?? "First",+ } as GlossaryItem;+}++describe("GlossaryTable", () => {+ it("shows empty state", () => {+ renderWithProviders(+ <GlossaryTable+ className="test"+ glossary={[]}+ onCreate={jest.fn()}+ onEdit={jest.fn()}+ onDelete={jest.fn()}+ />,+ );++ expect(screen.getByText(/No terms yet/i)).toBeInTheDocument();+ });++ it("creates a new record", async () => {+ const user = userEvent.setup();+ const onCreate = jest.fn();++ renderWithProviders(+ <GlossaryTable+ glossary={[makeItem({ id: 1 })]}+ onCreate={onCreate}+ onEdit={jest.fn()}+ onDelete={jest.fn()}+ />,+ );++ await user.click(screen.getByRole("button", { name: /new term/i }));++ const termInput = screen.getByPlaceholderText(/bird/i);+ const defInput = screen.getByPlaceholderText(/a warm-blooded.*/i);+ await user.clear(termInput);+ await user.type(termInput, " Bird ");+ await user.type(defInput, " Flies sometimes ");++ const table0 = screen.getByRole("table");+ const rows0 = within(table0).getAllByRole("row");+ const createRow0 = rows0.find((r) =>+ within(r).queryByPlaceholderText(/bird/i),+ );+ expect(createRow0).toBeTruthy();+ const saveInCreate = within(createRow0 as HTMLElement).getByRole("button", {+ name: /save/i,+ });++ expect(saveInCreate).toBeEnabled();+ await user.click(saveInCreate);++ expect(onCreate).toHaveBeenCalledTimes(1);+ expect(onCreate).toHaveBeenCalledWith("Bird", "Flies sometimes");+ });++ it("edits a record", async () => {+ const user = userEvent.setup();+ const item = makeItem({ id: 42, term: "Cat", definition: "Meows" });+ const onEdit = jest.fn();++ renderWithProviders(+ <GlossaryTable+ glossary={[item]}+ onCreate={jest.fn()}+ onEdit={onEdit}+ onDelete={jest.fn()}+ />,+ );++ await user.click(screen.getByText("Cat"));++ const termInput = screen.getByPlaceholderText(/bird/i);+ const defInput = screen.getByPlaceholderText(/a warm-blooded.*/i);++ await user.clear(termInput);+ await user.type(termInput, "Kitten");+ await user.clear(defInput);+ await user.type(defInput, "Young cat");++ await user.click(screen.getByRole("button", { name: /save/i }));++ expect(onEdit).toHaveBeenCalledTimes(1);+ expect(onEdit).toHaveBeenCalledWith(42, "Kitten", "Young cat");+ });++ it("focuses proper field when starting edit from term vs definition", async () => {+ const user = userEvent.setup();+ const item = makeItem({ term: "Dog", definition: "Barks" });++ const { rerender } = renderWithProviders(+ <GlossaryTable+ glossary={[item]}+ onCreate={jest.fn()}+ onEdit={jest.fn()}+ onDelete={jest.fn()}+ />,+ );++ // Click term -> term input should be focused+ await user.click(screen.getByText("Dog"));+ const termInput = screen.getByPlaceholderText(/bird/i);+ expect(termInput).toHaveFocus();++ await user.click(screen.getByRole("button", { name: /cancel/i }));++ // Re-render to reset DOM state and click definition cell+ rerender(+ <GlossaryTable+ glossary={[item]}+ onCreate={jest.fn()}+ onEdit={jest.fn()}+ onDelete={jest.fn()}+ />,+ );++ await user.click(screen.getByText("Barks"));+ const defInput = screen.getByPlaceholderText(/a warm-blooded.*/i);+ expect(defInput).toHaveFocus();+ });++ it("sorts by term header", async () => {+ const user = userEvent.setup();+ const rows: GlossaryItem[] = [+ makeItem({ id: 1, term: "Beta", definition: "Second" }),+ makeItem({ id: 2, term: "Alpha", definition: "First" }),+ makeItem({ id: 3, term: "Gamma", definition: "Third" }),+ ];++ renderWithProviders(+ <GlossaryTable+ glossary={rows}+ onCreate={jest.fn()}+ onEdit={jest.fn()}+ onDelete={jest.fn()}+ />,+ );++ const termHeader = screen.getByRole("columnheader", { name: /^term$/i });+ const getTermsOrder = (): string[] => {+ const table = screen.getByRole("table");+ const rowEls = within(table).getAllByRole("row");+ const dataRows = rowEls.slice(1); // skip header row+ return dataRows.map((r) => {+ const firstCell = within(r).getAllByRole("cell")[0];+ return firstCell.textContent?.trim() || "";+ });+ };++ const orders: string[][] = [];+ await user.click(within(termHeader).getByText(/^term$/i));+ orders.push(getTermsOrder());+ await user.click(within(termHeader).getByText(/^term$/i));+ orders.push(getTermsOrder());+ await user.click(within(termHeader).getByText(/^term$/i));+ orders.push(getTermsOrder());++ const ASC = ["Alpha", "Beta", "Gamma"].join("|");+ const DESC = ["Gamma", "Beta", "Alpha"].join("|");+ const serialized = orders.map((o) => o.join("|"));++ expect(serialized).toEqual(expect.arrayContaining([ASC, DESC, ASC]));+ });++ it("deletes a record with confirmation", async () => {+ const user = userEvent.setup();+ const item = makeItem({+ id: 7,+ term: "DeleteMe",+ definition: "To be removed",+ });+ const onDelete = jest.fn();++ renderWithProviders(+ <GlossaryTable+ glossary={[item]}+ onCreate={jest.fn()}+ onEdit={jest.fn()}+ onDelete={onDelete}+ />,+ );++ // Hover row to reveal delete icon: find the row that contains DeleteMe+ const table = screen.getByRole("table");+ const rows = within(table).getAllByRole("row");+ const row = rows.find((r) => within(r).queryByText("DeleteMe"));+ expect(row).toBeTruthy();+ await user.hover(row as HTMLElement);++ await user.click(screen.getByRole("button", { name: /delete/i }));++ // Confirm modal: scope search within the modal dialog+ const modal = await screen.findByRole("dialog");+ await user.click(within(modal).getByRole("button", { name: /delete/i }));++ expect(onDelete).toHaveBeenCalledTimes(1);+ expect(onDelete).toHaveBeenCalledWith(7);+ });++ it("disables Add until both fields are filled in create/edit mode", async () => {+ const user = userEvent.setup();++ renderWithProviders(+ <GlossaryTable+ glossary={[]}+ onCreate={jest.fn()}+ onEdit={jest.fn()}+ onDelete={jest.fn()}+ />,+ );++ await user.click(screen.getByRole("button", { name: /new term/i }));++ // Add button (check icon) should be disabled until both fields filled+ const table2 = screen.getByRole("table");+ const rows2 = within(table2).getAllByRole("row");+ const createRow = rows2.find((r) =>+ within(r).queryByPlaceholderText(/bird/i),+ );+ expect(createRow).toBeTruthy();+ const saveBtn = within(createRow as HTMLElement).getByRole("button", {+ name: /save/i,+ });+ expect(saveBtn).toBeDisabled();++ // Fill only one field and still disabled+ await user.type(screen.getByPlaceholderText(/bird/i), "Sparrow");+ expect(saveBtn).toBeDisabled();++ // Fill both fields and enabled+ await user.type(+ screen.getByPlaceholderText(/a warm-blooded.*/i),+ "Flies sometimes",+ );+ expect(saveBtn).toBeEnabled();+ });+});diff --git a/frontend/src/metabase/reference/guide/BaseSidebar.jsx b/frontend/src/metabase/reference/guide/BaseSidebar.jsxindex 88e635191f5..11d5e8c1577 100644--- a/frontend/src/metabase/reference/guide/BaseSidebar.jsx+++ b/frontend/src/metabase/reference/guide/BaseSidebar.jsx@@ -32,6 +32,12 @@ const BaseSidebar = ({ style, className }) => (icon="database"name={t`Our data`}/>+ <SidebarItem+ key="/reference/glossary"+ href="/reference/glossary"+ icon="globe"+ name={t`Glossary`}+ /></ol></div>);diff --git a/frontend/src/metabase/routes.jsx b/frontend/src/metabase/routes.jsxindex d280c1bac9c..a8bfc823b54 100644--- a/frontend/src/metabase/routes.jsx+++ b/frontend/src/metabase/routes.jsx@@ -55,6 +55,7 @@ import FieldListContainer from "metabase/reference/databases/FieldListContainer"import TableDetailContainer from "metabase/reference/databases/TableDetailContainer";import TableListContainer from "metabase/reference/databases/TableListContainer";import TableQuestionsContainer from "metabase/reference/databases/TableQuestionsContainer";+import { GlossaryContainer } from "metabase/reference/glossary/GlossaryContainer";import SegmentDetailContainer from "metabase/reference/segments/SegmentDetailContainer";import SegmentFieldDetailContainer from "metabase/reference/segments/SegmentFieldDetailContainer";import SegmentFieldListContainer from "metabase/reference/segments/SegmentFieldListContainer";@@ -379,6 +380,7 @@ export const getRoutes = (store) => {path="databases/:databaseId/tables/:tableId/questions"component={TableQuestionsContainer}/>+ <Route path="glossary" component={GlossaryContainer} /></Route>{/* ACCOUNT */}diff --git a/resources/migrations/057_update_migrations.yaml b/resources/migrations/057_update_migrations.yamlindex d1900c08cba..293aa53190b 100644--- a/resources/migrations/057_update_migrations.yaml+++ b/resources/migrations/057_update_migrations.yaml@@ -1399,6 +1399,51 @@ databaseChangeLog:nullable: falsedefaultValueComputed: current_timestamp+ - changeSet:+ id: v57.2025-09-12T16:08:00+ author: piranha+ comment: Create glossary table+ changes:+ - createTable:+ tableName: glossary+ remarks: Table to store glossary terms and their definitions+ columns:+ - column:+ name: id+ type: int+ autoIncrement: true+ remarks: Primary key identifier for glossary entries+ constraints:+ primaryKey: true+ nullable: false+ - column:+ name: term+ type: varchar(255)+ remarks: The glossary term or phrase being defined+ constraints:+ nullable: false+ unique: true+ - column:+ name: definition+ type: ${text.type}+ remarks: The detailed definition or explanation of the term+ constraints:+ nullable: false+ - column:+ name: created_at+ type: ${timestamp_type}+ remarks: Timestamp when comment was created+ defaultValueComputed: current_timestamp+ constraints:+ nullable: false+ - column:+ name: updated_at+ type: ${timestamp_type}+ remarks: Timestamp when comment was last updated+ defaultValueComputed: current_timestamp+ constraints:+ nullable: false+# >>>>>>>>>> DO NOT ADD NEW MIGRATIONS BELOW THIS LINE! ADD THEM ABOVE <<<<<<<<<<########################################################################################################################diff --git a/src/metabase/api_routes/routes.clj b/src/metabase/api_routes/routes.cljindex 416328bccd8..5dba7c47712 100644--- a/src/metabase/api_routes/routes.clj+++ b/src/metabase/api_routes/routes.clj@@ -22,6 +22,7 @@[metabase.eid-translation.api][metabase.embedding.api][metabase.geojson.api]+ [metabase.glossary.api][metabase.indexed-entities.api][metabase.logger.api][metabase.login-history.api]@@ -69,6 +70,7 @@metabase.dashboards.api/keep-memetabase.eid-translation.api/keep-memetabase.geojson.api/keep-me+ metabase.glossary.api/keep-memetabase.indexed-entities.api/keep-memetabase.logger.api/keep-memetabase.login-history.api/keep-me@@ -149,6 +151,7 @@"/embed" (+message-only-exceptions metabase.embedding.api/embedding-routes)"/field" (+auth metabase.warehouse-schema.api/field-routes)"/geojson" 'metabase.geojson.api+ "/glossary" (+auth 'metabase.glossary.api)"/google" (+auth metabase.sso.api/google-auth-routes)"/ldap" (+auth metabase.sso.api/ldap-routes)"/logger" (+auth 'metabase.logger.api)diff --git a/src/metabase/cmd/copy.clj b/src/metabase/cmd/copy.cljindex b1de67f24b4..890f59bba60 100644--- a/src/metabase/cmd/copy.clj+++ b/src/metabase/cmd/copy.clj@@ -112,7 +112,9 @@:model/NotificationSubscription:model/NotificationHandler:model/NotificationRecipient- :model/NotificationCard]+ :model/NotificationCard+ ;; 57++ :model/Glossary](when config/ee-available?[:model/Sandbox:model/ConnectionImpersonationdiff --git a/src/metabase/glossary/api.clj b/src/metabase/glossary/api.cljnew file mode 100644index 00000000000..454a72f7db5--- /dev/null+++ b/src/metabase/glossary/api.clj@@ -0,0 +1,45 @@+(ns metabase.glossary.api+ "API endpoints for managing glossary entries."+ (:require+ [metabase.api.common :as api]+ [metabase.api.macros :as api.macros]+ [metabase.util.malli.schema :as ms]+ [toucan2.core :as t2]))++(api.macros/defendpoint :get "/"+ "Fetch all glossary entries, optionally filtered by search term."+ [_route-params+ {:keys [search]} :- [:maybe [:map [:search {:optional true} [:maybe ms/NonBlankString]]]]]+ (let [where (when search+ [:or+ [:like [:lower :term] [:lower (str "%" search "%")]]+ [:like [:lower :definition] [:lower (str "%" search "%")]]])]+ {:data (t2/select :model/Glossary (cond-> {:order-by [[:term :asc]]}+ where (assoc :where where)))}))++(api.macros/defendpoint :post "/"+ "Create a new glossary entry."+ [_route-params+ _query-params+ {:keys [term definition]} :- [:map+ [:term ms/NonBlankString]+ [:definition ms/NonBlankString]]]+ (t2/insert-returning-instance! :model/Glossary {:term term :definition definition}))++(api.macros/defendpoint :put "/:id"+ "Update an existing glossary entry."+ [{:keys [id]} :- [:map [:id ms/PositiveInt]]+ _query-params+ {:keys [term definition]} :- [:map+ [:term ms/NonBlankString]+ [:definition ms/NonBlankString]]]+ (api/check-404 (t2/select-one :model/Glossary :id id))+ (t2/update! :model/Glossary id {:term term :definition definition})+ (t2/select-one :model/Glossary :id id))++(api.macros/defendpoint :delete "/:id"+ "Delete a glossary entry."+ [{:keys [id]} :- [:map [:id ms/PositiveInt]]]+ (api/check-404 (t2/select-one :model/Glossary :id id))+ (t2/delete! :model/Glossary :id id)+ api/generic-204-no-content)diff --git a/src/metabase/glossary/models/glossary.clj b/src/metabase/glossary/models/glossary.cljnew file mode 100644index 00000000000..e4b426fb0ba--- /dev/null+++ b/src/metabase/glossary/models/glossary.clj@@ -0,0 +1,40 @@+(ns metabase.glossary.models.glossary+ (:require+ [metabase.models.serialization :as serdes]+ [metabase.util.malli.schema :as ms]+ [methodical.core :as methodical]+ [toucan2.core :as t2]))++(methodical/defmethod t2/table-name :model/Glossary [_model] :glossary)++(doto :model/Glossary+ (derive :metabase/model)+ (derive :hook/timestamped?))++(def GlossaryEntry+ "Schema for a glossary entry."+ [:map {:closed true}+ [:id ms/PositiveInt]+ [:term ms/NonBlankString]+ [:definition ms/NonBlankString]])++;;; ---------------------- Serialization ----------------------------++(defmethod serdes/entity-id "Glossary" [_ {:keys [term]}]+ term)++(defmethod serdes/load-find-local "Glossary"+ [path]+ (t2/select-one :model/Glossary :term (:id (first path))))++(defmethod serdes/hash-fields :model/Glossary+ [_item]+ [:term])++(defmethod serdes/make-spec "Glossary" [_model-name _opts]+ {:copy [:term :definition]+ :transform {:created_at (serdes/date)+ :updated_at (serdes/date)}})++(defmethod serdes/storage-path "Glossary" [item _]+ ["glossary" (:term item)])diff --git a/src/metabase/models/resolution.clj b/src/metabase/models/resolution.cljindex da883baffea..f2814a9e489 100644--- a/src/metabase/models/resolution.clj+++ b/src/metabase/models/resolution.clj@@ -44,6 +44,7 @@:model/Field metabase.warehouse-schema.models.field:model/FieldUserSettings metabase.warehouse-schema.models.field-user-settings:model/FieldValues metabase.warehouse-schema.models.field-values+ :model/Glossary metabase.glossary.models.glossary:model/Sandbox metabase-enterprise.sandbox.models.sandbox:model/HTTPAction metabase.actions.models:model/ImplicitAction metabase.actions.modelsdiff --git a/test/metabase/cloud_migration/models/cloud_migration_test.clj b/test/metabase/cloud_migration/models/cloud_migration_test.cljindex 89f90ac0959..d23a2bbbb18 100644--- a/test/metabase/cloud_migration/models/cloud_migration_test.clj+++ b/test/metabase/cloud_migration/models/cloud_migration_test.clj@@ -65,7 +65,7 @@(dissoc @progress-calls :upload))"one progress call during other stages"))))))-(deftest migrate!-test-menaged-scheduler+(deftest migrate!-test-managed-scheduler(let [migration (mock-external-calls! (mt/user-http-request :crowberto :post 200 "cloud-migration"))](with-redefs [cloud-migration/cluster? (constantly false)](http-fake/with-fake-routes-in-isolation (fake-upload-route-handler migration)diff --git a/test/metabase/glossary/api_test.clj b/test/metabase/glossary/api_test.cljnew file mode 100644index 00000000000..f4ea17df32e--- /dev/null+++ b/test/metabase/glossary/api_test.clj@@ -0,0 +1,80 @@+(ns metabase.glossary.api-test+ "Tests for /api/glossary endpoints."+ (:require+ [clojure.set :as set]+ [clojure.test :refer :all]+ [metabase.test :as mt]+ [toucan2.core :as t2]))++(deftest glossary-api-test+ (mt/with-model-cleanup [:model/Glossary]+ (testing "POST /api/glossary"+ (testing "can create a new glossary entry as superuser"+ (let [response (mt/user-http-request :crowberto :post 200 "glossary"+ {:term "API"+ :definition "Application Programming Interface"})]+ (is (= "API" (:term response)))+ (is (= "Application Programming Interface" (:definition response)))+ (is (pos-int? (:id response)))))++ (testing "cannot create glossary entry with missing fields"+ (is (=? {:errors {:term "value must be a non-blank string."}}+ (mt/user-http-request :crowberto :post 400 "glossary"+ {:definition "Missing term field"})))+ (is (=? {:errors {:definition "value must be a non-blank string."}}+ (mt/user-http-request :crowberto :post 400 "glossary"+ {:term "Missing definition field"}))))))++ (testing "GET /api/glossary"+ (mt/with-temp [:model/Glossary _g1 {:term "Database" :definition "A structured collection of data"}+ :model/Glossary _g2 {:term "Query" :definition "A request for data from a database"}]+ (testing "can list all glossary entries"+ (let [response (mt/user-http-request :rasta :get 200 "glossary")+ data (:data response)]+ (is (<= 2 (count data)))+ (is (set/subset? #{"Database" "Query"} (set (map :term data))))))++ (testing "can search glossary entries by term"+ (let [response (mt/user-http-request :rasta :get 200 "glossary" :search "data")+ data (:data response)]+ (is (= 2 (count data)))+ (is (every? #(or (re-find #"(?i)data" (:term %))+ (re-find #"(?i)data" (:definition %))) data))))++ (testing "search is case insensitive"+ (let [response (mt/user-http-request :rasta :get 200 "glossary" :search "DATABASE")+ data (:data response)]+ (is (<= 1 (count data)))+ (is (set/subset? #{"Database"} (set (map :term data))))))++ (testing "search returns empty when no matches"+ (let [response (mt/user-http-request :rasta :get 200 "glossary" :search (str "nonexistent-" (random-uuid)))+ data (:data response)]+ (is (= 0 (count data)))))))++ (testing "PUT /api/glossary/:id"+ (mt/with-temp [:model/Glossary {gid :id} {:term "Old Term" :definition "Old definition"}]+ (testing "can update glossary entry as superuser"+ (let [response (mt/user-http-request :crowberto :put 200 (str "glossary/" gid)+ {:term "Updated Term"+ :definition "Updated definition"})]+ (is (= "Updated Term" (:term response)))+ (is (= "Updated definition" (:definition response)))+ (is (= gid (:id response)))))++ (testing "returns 404 when updating non-existent entry"+ (is (= "Not found."+ (mt/user-http-request :crowberto :put 404 "glossary/99999"+ {:term "Does not exist"+ :definition "Does not exist"}))))))++ (testing "DELETE /api/glossary/:id"+ (mt/with-temp [:model/Glossary {gid :id} {:term "To Delete" :definition "Will be deleted"}]+ (testing "can delete glossary entry as superuser"+ (is (= nil+ (mt/user-http-request :crowberto :delete 204 (str "glossary/" gid))))+ (is (nil? (t2/select-one :model/Glossary :id gid))))++ (testing "returns 404 when deleting non-existent entry"+ (is (= "Not found."+ (mt/user-http-request :crowberto :delete 404 "glossary/99999")))))))diff --git a/test_resources/serialization_baseline/glossary/foobar.yaml b/test_resources/serialization_baseline/glossary/foobar.yamlnew file mode 100644index 00000000000..52d72c470b1--- /dev/null+++ b/test_resources/serialization_baseline/glossary/foobar.yaml@@ -0,0 +1,7 @@+created_at: '2025-09-18T13:38:26.721389Z'+definition: It's foobar2000 actually+term: foobar+updated_at: '2025-09-18T13:38:26.721389Z'+serdes/meta:+- id: foobar+ model: Glossary